From f4ca6f3b6abb6b621bc0e8a1d71c9f9a01483938 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 14:20:09 +1100 Subject: [PATCH 01/78] new ledgerjs --- js/ledger.js | 12088 +------------------------------------------------ 1 file changed, 2 insertions(+), 12086 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index a33a2f0a..918a75f6 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,12091 +2,7 @@ window.global = window; window.Buffer = buffer.Buffer; -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.NewLedger = {}))); -}(this, (function (exports) { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var runtime_1 = createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - - }( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports - )); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); - } - }); - - var utils = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.defer = defer; - exports.splitPath = splitPath; - exports.eachSeries = eachSeries; - exports.foreach = foreach; - exports.doIf = doIf; - exports.asyncWhile = asyncWhile; - function defer() { - var resolve = void 0, - reject = void 0; - var promise = new Promise(function (success, failure) { - resolve = success; - reject = failure; - }); - if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy - return { promise: promise, resolve: resolve, reject: reject }; - } - - // TODO use bip32-path library - /******************************************************************************** - * Ledger Node JS API - * (c) 2016-2017 Ledger - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ********************************************************************************/ - - - function splitPath(path) { - var result = []; - var components = path.split("/"); - components.forEach(function (element) { - var number = parseInt(element, 10); - if (isNaN(number)) { - return; // FIXME shouldn't it throws instead? - } - if (element.length > 1 && element[element.length - 1] === "'") { - number += 0x80000000; - } - result.push(number); - }); - return result; - } - - // TODO use async await - - function eachSeries(arr, fun) { - return arr.reduce(function (p, e) { - return p.then(function () { - return fun(e); - }); - }, Promise.resolve()); - } - - function foreach(arr, callback) { - function iterate(index, array, result) { - if (index >= array.length) { - return result; - } else return callback(array[index], index).then(function (res) { - result.push(res); - return iterate(index + 1, array, result); - }); - } - return Promise.resolve().then(function () { - return iterate(0, arr, []); - }); - } - - function doIf(condition, callback) { - return Promise.resolve().then(function () { - if (condition) { - return callback(); - } - }); - } - - function asyncWhile(predicate, callback) { - function iterate(result) { - if (!predicate()) { - return result; - } else { - return callback().then(function (res) { - result.push(res); - return iterate(result); - }); - } - } - return Promise.resolve([]).then(iterate); - } - - var isLedgerDevice = exports.isLedgerDevice = function isLedgerDevice(device) { - return device.vendorId === 0x2581 && device.productId === 0x3b7c || device.vendorId === 0x2c97; - }; - - }); - - unwrapExports(utils); - var utils_1 = utils.defer; - var utils_2 = utils.splitPath; - var utils_3 = utils.eachSeries; - var utils_4 = utils.foreach; - var utils_5 = utils.doIf; - var utils_6 = utils.asyncWhile; - var utils_7 = utils.isLedgerDevice; - - var require$$0 = {}; - - var createHash = require$$0.createHash; - - var Btc_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - // TODO future refactoring - // - drop utils.js & refactoring with async/await style - // - try to avoid every place we do hex<>Buffer conversion. also accept Buffer as func parameters (could accept both a string or a Buffer in the API) - // - there are redundant code across apps (see Eth vs Btc). we might want to factorize it somewhere. also each app apdu call should be abstracted it out as an api - - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - /** - * address format is one of legacy | p2sh | bech32 - */ - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2 - }; - - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - - var Btc = function () { - function Btc(transport) { - var scrambleKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "BTC"; - - _classCallCheck(this, Btc); - - this.transport = transport; - transport.decorateAppAPIMethods(this, ["getWalletPublicKey", "signP2SHTransaction", "signMessageNew", "createPaymentTransactionNew"], scrambleKey); - } - - _createClass(Btc, [{ - key: "hashPublicKey", - value: function hashPublicKey(buffer) { - return window.createHash("rmd160").update(window.createHash("sha256").update(buffer).digest()).digest(); - } - }, { - key: "getWalletPublicKey_private", - value: function getWalletPublicKey_private(path) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var _verify$format$option = _extends({ - verify: false, - format: "legacy" - }, options), - verify = _verify$format$option.verify, - format = _verify$format$option.format; - - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - var paths = (0, utils.splitPath)(path); - var p1 = verify ? 1 : 0; - var p2 = addressFormatMap[format]; - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x40, p1, p2, buffer).then(function (response) { - var publicKeyLength = response[0]; - var addressLength = response[1 + publicKeyLength]; - var publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - var bitcoinAddress = response.slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength).toString("ascii"); - var chainCode = response.slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32).toString("hex"); - return { publicKey: publicKey, bitcoinAddress: bitcoinAddress, chainCode: chainCode }; - }); - } - - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - - }, { - key: "getWalletPublicKey", - value: function getWalletPublicKey(path, opts) { - var options = void 0; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - format: arguments[2] ? "p2sh" : "legacy" - }; - } else { - options = opts || {}; - } - return this.getWalletPublicKey_private(path, options); - } - }, { - key: "getTrustedInputRaw", - value: function getTrustedInputRaw(transactionData, indexLookup) { - var data = void 0; - var firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - var prefix = Buffer.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer.concat([prefix, transactionData], transactionData.length + 4); - } else { - data = transactionData; - } - return this.transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data).then(function (trustedInput) { - return trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - }); - } - }, { - key: "getTrustedInput", - value: function getTrustedInput(indexLookup, transaction) { - var _this = this; - - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var inputs = transaction.inputs, - outputs = transaction.outputs, - locktime = transaction.locktime; - - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var processScriptBlocks = function processScriptBlocks(script, sequence) { - var scriptBlocks = []; - var offset = 0; - while (offset !== script.length) { - var blockSize = script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), sequence])); - } - offset += blockSize; - } - - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(sequence); - } - - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this.getTrustedInputRaw(scriptBlock); - }); - }; - - var processWholeScriptBlock = function processWholeScriptBlock(block) { - return _this.getTrustedInputRaw(block); - }; - - var processInputs = function processInputs() { - return (0, utils.eachSeries)(inputs, function (input) { - var treeField = isDecred ? input.tree || Buffer.from([0x00]) : Buffer.alloc(0); - var data = Buffer.concat([input.prevout, treeField, isXST ? Buffer.from([0x00]) : _this.createVarint(input.script.length)]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return isDecred ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) : isXST ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence); - }); - }).then(function () { - var data = _this.createVarint(outputs.length); - return _this.getTrustedInputRaw(data); - }); - }; - - var processOutputs = function processOutputs() { - return (0, utils.eachSeries)(outputs, function (output) { - var data = output.amount; - data = Buffer.concat([data, isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), //Version script - _this.createVarint(output.script.length), output.script]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("output"); - }); - }).then(function () { - //Add expiry height for decred - var finalData = isDecred ? Buffer.concat([locktime, Buffer.from([0x00, 0x00, 0x00, 0x00])]) : locktime; - return _this.getTrustedInputRaw(finalData); - }); - }; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), this.createVarint(inputs.length)]); - return this.getTrustedInputRaw(data, indexLookup).then(processInputs).then(processOutputs); - } - }, { - key: "getTrustedInputBIP143", - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(indexLookup, transaction) { - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var isDecred, sha, hash, data, outputs, locktime; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (transaction) { - _context.next = 2; - break; - } - - throw new Error("getTrustedInputBIP143: missing tx"); - - case 2: - isDecred = additionals.includes("decred"); - - if (!isDecred) { - _context.next = 5; - break; - } - - throw new Error("Decred does not implement BIP143"); - - case 5: - sha = window.createHash("sha256"); - - sha.update(this.serializeTransaction(transaction, true)); - hash = sha.digest(); - - sha = window.createHash("sha256"); - sha.update(hash); - hash = sha.digest(); - data = Buffer.alloc(4); - - data.writeUInt32LE(indexLookup, 0); - outputs = transaction.outputs, locktime = transaction.locktime; - - if (!(!outputs || !locktime)) { - _context.next = 16; - break; - } - - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - - case 16: - if (outputs[indexLookup]) { - _context.next = 18; - break; - } - - throw new Error("getTrustedInputBIP143: wrong index"); - - case 18: - hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); - _context.next = 21; - return hash.toString("hex"); - - case 21: - return _context.abrupt("return", _context.sent); - - case 22: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function getTrustedInputBIP143(_x4, _x5) { - return _ref.apply(this, arguments); - } - - return getTrustedInputBIP143; - }() - }, { - key: "getVarint", - value: function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [(data[offset + 4] << 24) + (data[offset + 3] << 16) + (data[offset + 2] << 8) + data[offset + 1], 5]; - } - - throw new Error("getVarint called with unexpected parameters"); - } - }, { - key: "startUntrustedHashTransactionInputRaw", - value: function startUntrustedHashTransactionInputRaw(newTransaction, firstRound, transactionData) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var p2 = bip143 ? additionals.includes("sapling") ? 0x05 : overwinter ? 0x04 : 0x02 : 0x00; - return this.transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - }, { - key: "startUntrustedHashTransactionInput", - value: function startUntrustedHashTransactionInput(newTransaction, transaction, inputs) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - - var _this2 = this; - - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), this.createVarint(transaction.inputs.length)]); - return this.startUntrustedHashTransactionInputRaw(newTransaction, true, data, bip143, overwinter, additionals).then(function () { - var i = 0; - var isDecred = additionals.includes("decred"); - return (0, utils.eachSeries)(transaction.inputs, function (input) { - var prefix = void 0; - if (bip143) { - prefix = Buffer.from([0x02]); - } else { - if (inputs[i].trustedInput) { - prefix = Buffer.from([0x01, inputs[i].value.length]); - } else { - prefix = Buffer.from([0x00]); - } - } - data = Buffer.concat([prefix, inputs[i].value, isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), _this2.createVarint(input.script.length)]); - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, data, bip143, overwinter, additionals).then(function () { - var scriptBlocks = []; - var offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } else { - while (offset !== input.script.length) { - var blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([input.script.slice(offset, offset + blockSize), input.sequence])); - } - offset += blockSize; - } - } - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, scriptBlock, bip143, overwinter, additionals); - }).then(function () { - i++; - }); - }); - }); - }); - } - }, { - key: "provideOutputFullChangePath", - value: function provideOutputFullChangePath(path) { - var paths = (0, utils.splitPath)(path); - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - }, { - key: "hashOutputFull", - value: function hashOutputFull(outputScript) { - var _this3 = this; - - var additionals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - var offset = 0; - var p1 = 0x80; - var isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return this.transport.send(0xe0, 0x4a, p1, 0x00, outputScript); - } - return (0, utils.asyncWhile)(function () { - return offset < outputScript.length; - }, function () { - var blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length ? outputScript.length - offset : MAX_SCRIPT_BLOCK; - var p1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - var data = outputScript.slice(offset, offset + blockSize); - - return _this3.transport.send(0xe0, 0x4a, p1, 0x00, data).then(function () { - offset += blockSize; - }); - }); - } - }, { - key: "signTransaction", - value: function signTransaction(path) { - var lockTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SIGHASH_ALL; - var expiryHeight = arguments[3]; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var isDecred = additionals.includes("decred"); - var paths = (0, utils.splitPath)(path); - var offset = 0; - var pathsBuffer = Buffer.alloc(paths.length * 4); - paths.forEach(function (element) { - pathsBuffer.writeUInt32BE(element, offset); - offset += 4; - }); - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred ? Buffer.concat([Buffer.from([paths.length]), pathsBuffer, lockTimeBuffer, expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), Buffer.from([sigHashType])]) : Buffer.concat([Buffer.from([paths.length]), pathsBuffer, Buffer.from([0x00]), lockTimeBuffer, Buffer.from([sigHashType])]); - if (expiryHeight && !isDecred) { - buffer = Buffer.concat([buffer, expiryHeight]); - } - return this.transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - - }, { - key: "signMessageNew", - value: function signMessageNew(path, messageHex) { - var _this4 = this; - - var paths = (0, utils.splitPath)(path); - var message = new Buffer(messageHex, "hex"); - var offset = 0; - var toSend = []; - - var _loop = function _loop() { - var maxChunkSize = offset === 0 ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 : MAX_SCRIPT_BLOCK; - var chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - var buffer = new Buffer(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - toSend.push(buffer); - offset += chunkSize; - }; - - while (offset !== message.length) { - _loop(); - } - return (0, utils.foreach)(toSend, function (data, i) { - return _this4.transport.send(0xe0, 0x4e, 0x00, i === 0 ? 0x01 : 0x80, data); - }).then(function () { - return _this4.transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00])).then(function (response) { - var v = response[0] - 0x30; - var r = response.slice(4, 4 + response[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - var offset = 4 + response[3] + 2; - var s = response.slice(offset, offset + response[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return { v: v, r: r, s: s }; - }); - }); - } - - /** - * To sign a transaction involving standard (P2PKH) inputs, call createPaymentTransactionNew with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @return the signed transaction ready to be broadcast - * @example - btc.createPaymentTransactionNew( - [ [tx1, 1] ], - ["0'/0/0"], - undefined, - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(res => ...); - */ - - }, { - key: "createPaymentTransactionNew", - value: function createPaymentTransactionNew(inputs, associatedKeysets, changePath, outputScriptHex) { - var lockTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SIGHASH_ALL; - var segwit = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; - var initialTimestamp = arguments[7]; - - var _this5 = this; - - var additionals = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; - var expiryHeight = arguments[9]; - - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var hasTimestamp = initialTimestamp !== undefined; - var startTime = Date.now(); - var sapling = additionals.includes("sapling"); - var bech32 = segwit && additionals.includes("bech32"); - var useBip143 = segwit || !!additionals && (additionals.includes("abc") || additionals.includes("gold") || additionals.includes("bip143")) || !!expiryHeight && !isDecred; - // Inputs are provided as arrays of [transaction, output_index, optional redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST ? defaultVersion.writeUInt32LE(2, 0) : defaultVersion.writeUInt32LE(1, 0); // Default version to 2 for XST not to have timestamp - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var publicKeys = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer.alloc(0) - }; - var getTrustedInputCall = useBip143 ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0], additionals).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer.from(trustedInput, "hex"), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }).then(function () { - if (!!expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); - } else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - }); - }).then(function () { - for (var i = 0; i < inputs.length; i++) { - var _sequence = Buffer.alloc(4); - _sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence - }); - } - }).then(function () { - return (0, utils.doIf)(!resuming, function () { - return ( - // Collect public keys - (0, utils.foreach)(inputs, function (input, i) { - return _this5.getWalletPublicKey_private(associatedKeysets[i]); - }).then(function (result) { - for (var index = 0; index < result.length; index++) { - publicKeys.push(_this5.compressPublicKey(Buffer.from(result[index].publicKey, "hex"))); - } - }) - ); - }); - }).then(function () { - if (hasTimestamp) { - targetTransaction.timestamp = Buffer.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - }).then(function () { - return (0, utils.doIf)(useBip143, function () { - return ( - // Do the first run with all inputs - _this5.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals).then(function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript); - }); - }) - ); - }); - }).then(function () { - return (0, utils.doIf)(!!expiryHeight && !isDecred, function () { - return ( - // FIXME: I think we should always pass lockTime here. - _this5.signTransaction("", lockTime, SIGHASH_ALL, expiryHeight) - ); - }); - }).then(function () { - return ( - // Do the second run with the individual transaction - (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : !segwit ? regularOutputs[i].script : Buffer.concat([Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), _this5.hashPublicKey(publicKeys[i]), Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])]); - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this5.startUntrustedHashTransactionInput(!useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals).then(function () { - return (0, utils.doIf)(!useBip143, function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript, additionals); - }); - }); - }).then(function () { - return _this5.signTransaction(associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals); - }).then(function (signature) { - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }) - ); - }).then(function () { - // Populate the final input scripts - for (var _i = 0; _i < inputs.length; _i++) { - if (segwit) { - targetTransaction.witness = Buffer.alloc(0); - if (!bech32) { - targetTransaction.inputs[_i].script = Buffer.concat([Buffer.from("160014", "hex"), _this5.hashPublicKey(publicKeys[_i])]); - } - } else { - var signatureSize = Buffer.alloc(1); - var keySize = Buffer.alloc(1); - signatureSize[0] = signatures[_i].length; - keySize[0] = publicKeys[_i].length; - targetTransaction.inputs[_i].script = Buffer.concat([signatureSize, signatures[_i], keySize, publicKeys[_i]]); - } - var offset = useBip143 ? 0 : 4; - targetTransaction.inputs[_i].prevout = trustedInputs[_i].value.slice(offset, offset + 0x24); - } - - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - - var result = Buffer.concat([_this5.serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript]); - - if (segwit && !isDecred) { - var witness = Buffer.alloc(0); - for (var i = 0; i < inputs.length; i++) { - var tmpScriptData = Buffer.concat([Buffer.from("02", "hex"), Buffer.from([signatures[i].length]), signatures[i], Buffer.from([publicKeys[i].length]), publicKeys[i]]); - witness = Buffer.concat([witness, tmpScriptData]); - } - result = Buffer.concat([result, witness]); - } - - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer.concat([result, lockTimeBuffer]); - - if (expiryHeight) { - result = Buffer.concat([result, targetTransaction.nExpiryHeight || Buffer.alloc(0), targetTransaction.extraData || Buffer.alloc(0)]); - } - - if (isDecred) { - var decredWitness = Buffer.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness = Buffer.concat([decredWitness, Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Buffer.from([0x00, 0x00, 0x00, 0x00]), //Block height - Buffer.from([0xff, 0xff, 0xff, 0xff]), //Block index - Buffer.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script]); - }); - - result = Buffer.concat([result, decredWitness]); - } - - return result.toString("hex"); - }); - } - - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction( - [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - ["0'/0/0"], - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(result => ...); - */ - - }, { - key: "signP2SHTransaction", - value: function signP2SHTransaction(inputs, associatedKeysets, outputScriptHex) { - var lockTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SIGHASH_ALL; - var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; - - var _this6 = this; - - var transactionVersion = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_VERSION; - var timeStamp = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; - - // Inputs are provided as arrays of [transaction, output_index, redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - var defaultTime = Buffer.alloc(4); - defaultTime.writeUInt32LE(timeStamp, 0); - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion - }; - - if (timeStamp > 0) { - targetTransaction.timestamp = defaultTime; - } - var getTrustedInputCall = segwit ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0]).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit ? Buffer.from(trustedInput, "hex") : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }); - }).then(function () { - // Pre-build the target transaction - for (var i = 0; i < inputs.length; i++) { - var _sequence2 = Buffer.alloc(4); - _sequence2.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence2 - }); - } - }).then(function () { - return (0, utils.doIf)(segwit, function () { - return ( - // Do the first run with all inputs - _this6.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true).then(function () { - return _this6.hashOutputFull(outputScript); - }) - ); - }); - }).then(function () { - return (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : regularOutputs[i].script; - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this6.startUntrustedHashTransactionInput(!segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit).then(function () { - return (0, utils.doIf)(!segwit, function () { - return _this6.hashOutputFull(outputScript); - }); - }).then(function () { - return _this6.signTransaction(associatedKeysets[i], lockTime, sigHashType).then(function (signature) { - signatures.push(signature.toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }); - }); - }).then(function () { - return signatures; - }); - } - }, { - key: "compressPublicKey", - value: function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer.alloc(1); - prefixBuffer[0] = prefix; - return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - }, { - key: "createVarint", - value: function createVarint(value) { - if (value < 0xfd) { - var _buffer = Buffer.alloc(1); - _buffer[0] = value; - return _buffer; - } - if (value <= 0xffff) { - var _buffer2 = Buffer.alloc(3); - _buffer2[0] = 0xfd; - _buffer2[1] = value & 0xff; - _buffer2[2] = value >> 8 & 0xff; - return _buffer2; - } - var buffer = Buffer.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = value >> 8 & 0xff; - buffer[3] = value >> 16 & 0xff; - buffer[4] = value >> 24 & 0xff; - return buffer; - } - - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - - }, { - key: "splitTransaction", - value: function splitTransaction(transactionHex) { - var isSegwitSupported = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var hasTimestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var hasExtraData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer.alloc(0); - var nExpiryHeight = Buffer.alloc(0); - var nVersionGroupId = Buffer.alloc(0); - var extraData = Buffer.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && isSegwitSupported && transaction[offset] === 0 && transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = this.getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var _prevout = transaction.slice(offset, offset + 36); - offset += 36; - var _script = Buffer.alloc(0); - var _tree = Buffer.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - _script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } else { - //Tree field - _tree = transaction.slice(offset, offset + 1); - offset += 1; - } - - var _sequence3 = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ prevout: _prevout, script: _script, sequence: _sequence3, tree: _tree }); - } - varint = this.getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var _i2 = 0; _i2 < numberOutputs; _i2++) { - var _amount = transaction.slice(offset, offset + 8); - offset += 8; - - if (isDecred) { - //Script version - offset += 2; - } - - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script2 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ amount: _amount, script: _script2 }); - } - var witnessScript = void 0, - locktime = void 0; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - - //Get witnesses for Decred - if (isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var _i3 = 0; _i3 < numberInputs; _i3++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script3 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[_i3].script = _script3; - } - } - - return { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - - }, { - key: "serializeTransactionOutputs", - value: function serializeTransactionOutputs(_ref2) { - var _this7 = this; - - var outputs = _ref2.outputs; - - var outputBuffer = Buffer.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, this.createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer.concat([outputBuffer, output.amount, _this7.createVarint(output.script.length), output.script]); - }); - } - return outputBuffer; - } - - /** - */ - - }, { - key: "serializeTransaction", - value: function serializeTransaction(transaction, skipWitness, timestamp) { - var _this8 = this; - - var additionals = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; - - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = isDecred || isBech32 ? Buffer.concat([inputBuffer, input.prevout, Buffer.from([0x00]), //tree - input.sequence]) : Buffer.concat([inputBuffer, input.prevout, _this8.createVarint(input.script.length), input.script, input.sequence]); - }); - - var outputBuffer = this.serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, useWitness && transaction.witness || Buffer.alloc(0), transaction.locktime, transaction.nExpiryHeight || Buffer.alloc(0), transaction.extraData || Buffer.alloc(0)]); - } - - return Buffer.concat([transaction.version, timestamp ? timestamp : Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), this.createVarint(transaction.inputs.length), inputBuffer, outputBuffer]); - } - - /** - */ - - }, { - key: "displayTransactionDebug", - value: function displayTransactionDebug(transaction) { - console.log("version " + transaction.version.toString("hex")); - transaction.inputs.forEach(function (input, i) { - var prevout = input.prevout.toString("hex"); - var script = input.script.toString("hex"); - var sequence = input.sequence.toString("hex"); - console.log("input " + i + " prevout " + prevout + " script " + script + " sequence " + sequence); - }); - (transaction.outputs || []).forEach(function (output, i) { - var amount = output.amount.toString("hex"); - var script = output.script.toString("hex"); - console.log("output " + i + " amount " + amount + " script " + script); - }); - if (typeof transaction.locktime !== "undefined") { - console.log("locktime " + transaction.locktime.toString("hex")); - } - } - }]); - - return Btc; - }(); - - /** - */ - - - exports.default = Btc; - - /** - */ - - - /** - */ - - }); - - var Btc = unwrapExports(Btc_1); - - var Btc$1 = /*#__PURE__*/Object.freeze({ - default: Btc, - __moduleExports: Btc_1 - }); - - var domain; - - // This constructor is used to store event handlers. Instantiating this is - // faster than explicitly calling `Object.create(null)` to get a "clean" empty - // object (tested with v8 v4.9). - function EventHandlers() {} - EventHandlers.prototype = Object.create(null); - - function EventEmitter() { - EventEmitter.init.call(this); - } - - // nodejs oddity - // require('events') === require('events').EventEmitter - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.usingDomains = false; - - EventEmitter.prototype.domain = undefined; - EventEmitter.prototype._events = undefined; - 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. - EventEmitter.defaultMaxListeners = 10; - - EventEmitter.init = function() { - this.domain = null; - if (EventEmitter.usingDomains) { - // if there is an active domain, then attach to it. - if (domain.active && !(this instanceof domain.Domain)) { - this.domain = domain.active; - } - } - - if (!this._events || this._events === Object.getPrototypeOf(this)._events) { - this._events = new EventHandlers(); - 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 || isNaN(n)) - throw new TypeError('"n" argument must be a positive number'); - 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); - }; - - // These standalone emit* functions are used to optimize calling of event - // handlers for fast cases because emit() itself often has a variable number of - // arguments and can be deoptimized because of that. These functions always have - // the same number of arguments and thus do not get deoptimized, so the code - // inside them can execute faster. - function emitNone(handler, isFn, self) { - if (isFn) - handler.call(self); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self); - } - } - function emitOne(handler, isFn, self, arg1) { - if (isFn) - handler.call(self, arg1); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1); - } - } - function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) - handler.call(self, arg1, arg2); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2); - } - } - function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) - handler.call(self, arg1, arg2, arg3); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2, arg3); - } - } - - function emitMany(handler, isFn, self, args) { - if (isFn) - handler.apply(self, args); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].apply(self, args); - } - } - - EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events, domain; - var needDomainExit = false; - var doError = (type === 'error'); - - events = this._events; - if (events) - doError = (doError && events.error == null); - else if (!doError) - return false; - - domain = this.domain; - - // If there is no 'error' event listener then throw. - if (doError) { - er = arguments[1]; - if (domain) { - if (!er) - er = new Error('Uncaught, unspecified "error" event'); - er.domainEmitter = this; - er.domain = domain; - er.domainThrown = false; - domain.emit('error', er); - } else if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - return false; - } - - handler = events[type]; - - if (!handler) - return false; - - var isFn = typeof handler === 'function'; - len = arguments.length; - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - default: - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - emitMany(handler, isFn, this, args); - } - - if (needDomainExit) - domain.exit(); - - return true; - }; - - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = target._events; - if (!events) { - events = target._events = new EventHandlers(); - 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) { - 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) { - // 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]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } - - // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + type + ' listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - emitWarning(w); - } - } - } - - return target; - } - function emitWarning(e) { - typeof console.warn === 'function' ? console.warn(e) : console.log(e); - } - 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 _onceWrap(target, type, listener) { - var fired = false; - function g() { - target.removeListener(type, g); - if (!fired) { - fired = true; - listener.apply(target, arguments); - } - } - g.listener = listener; - return g; - } - - EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - - EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = this._events; - if (!events) - return this; - - list = events[type]; - if (!list) - return this; - - if (list === listener || (list.listener && list.listener === listener)) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - 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; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list[0] = undefined; - if (--this._eventsCount === 0) { - this._events = new EventHandlers(); - return this; - } else { - delete events[type]; - } - } else { - spliceOne(list, position); - } - - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events; - - events = this._events; - if (!events) - return this; - - // not listening for removeListener, no need to emit - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = new EventHandlers(); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - for (var i = 0, key; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = new EventHandlers(); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - do { - this.removeListener(type, listeners[listeners.length - 1]); - } while (listeners[0]); - } - - return this; - }; - - EventEmitter.prototype.listeners = function listeners(type) { - var evlistener; - var ret; - var events = this._events; - - if (!events) - ret = []; - else { - evlistener = events[type]; - if (!evlistener) - ret = []; - else if (typeof evlistener === 'function') - ret = [evlistener.listener || evlistener]; - else - ret = unwrapListeners(evlistener); - } - - return ret; - }; - - 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) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; - } - - EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; - }; - - // About 1.5x faster than the two-arg version of Array#splice(). - function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; - list.pop(); - } - - function arrayClone(arr, i) { - var copy = new Array(i); - while (i--) - copy[i] = arr[i]; - return copy; - } - - 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; - } - - var helpers = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = exports.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = exports.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - }); - - unwrapExports(helpers); - var helpers_1 = helpers.addCustomErrorDeserializer; - var helpers_2 = helpers.createCustomErrorClass; - var helpers_3 = helpers.deserializeError; - var helpers_4 = helpers.serializeError; - - var lib = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughGas = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; - exports.TransportError = TransportError; - exports.getAltStatusMessage = getAltStatusMessage; - exports.TransportStatusError = TransportStatusError; - - - - exports.serializeError = helpers.serializeError; - exports.deserializeError = helpers.deserializeError; - exports.createCustomErrorClass = helpers.createCustomErrorClass; - exports.addCustomErrorDeserializer = helpers.addCustomErrorDeserializer; - var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers.createCustomErrorClass)("AccountNameRequired"); - var BluetoothRequired = exports.BluetoothRequired = (0, helpers.createCustomErrorClass)("BluetoothRequired"); - var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers.createCustomErrorClass)("BtcUnmatchedApp"); - var CantOpenDevice = exports.CantOpenDevice = (0, helpers.createCustomErrorClass)("CantOpenDevice"); - var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers.createCustomErrorClass)("CashAddrNotSupported"); - var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers.createCustomErrorClass)("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers.createCustomErrorClass)("DeviceNotGenuine"); - var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); - var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers.createCustomErrorClass)("DeviceInOSUExpected"); - var DeviceHalted = exports.DeviceHalted = (0, helpers.createCustomErrorClass)("DeviceHalted"); - var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers.createCustomErrorClass)("DeviceNameInvalid"); - var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers.createCustomErrorClass)("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers.createCustomErrorClass)("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = exports.EnpointConfigError = (0, helpers.createCustomErrorClass)("EnpointConfig"); - var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers.createCustomErrorClass)("FeeEstimationFailed"); - var HardResetFail = exports.HardResetFail = (0, helpers.createCustomErrorClass)("HardResetFail"); - var InvalidAddress = exports.InvalidAddress = (0, helpers.createCustomErrorClass)("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers.createCustomErrorClass)("LatestMCUInstalledError"); - var UnknownMCU = exports.UnknownMCU = (0, helpers.createCustomErrorClass)("UnknownMCU"); - var LedgerAPIError = exports.LedgerAPIError = (0, helpers.createCustomErrorClass)("LedgerAPIError"); - var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers.createCustomErrorClass)("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); - var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers.createCustomErrorClass)("ManagerDeviceLocked"); - var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); - var NetworkDown = exports.NetworkDown = (0, helpers.createCustomErrorClass)("NetworkDown"); - var NoAddressesFound = exports.NoAddressesFound = (0, helpers.createCustomErrorClass)("NoAddressesFound"); - var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers.createCustomErrorClass)("NotEnoughBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - var NotEnoughGas = exports.NotEnoughGas = (0, helpers.createCustomErrorClass)("NotEnoughGas"); - var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers.createCustomErrorClass)("PasswordsDontMatch"); - var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers.createCustomErrorClass)("PasswordIncorrect"); - var TimeoutTagged = exports.TimeoutTagged = (0, helpers.createCustomErrorClass)("TimeoutTagged"); - var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers.createCustomErrorClass)("UnexpectedBootloader"); - var UpdateYourApp = exports.UpdateYourApp = (0, helpers.createCustomErrorClass)("UpdateYourApp"); - var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); - var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers.createCustomErrorClass)("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers.createCustomErrorClass)("UserRefusedAllowManager"); - var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers.createCustomErrorClass)("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); - var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers.createCustomErrorClass)("DeviceShouldStayInApp"); - var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers.createCustomErrorClass)("WebsocketConnectionError"); - var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers.createCustomErrorClass)("WebsocketConnectionFailed"); - var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers.createCustomErrorClass)("WrongDeviceForAccount"); - var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers.createCustomErrorClass)("ETHAddressNonEIP"); - var CantScanQRCode = exports.CantScanQRCode = (0, helpers.createCustomErrorClass)("CantScanQRCode"); - var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers.createCustomErrorClass)("FeeNotLoaded"); - var FeeRequired = exports.FeeRequired = (0, helpers.createCustomErrorClass)("FeeRequired"); - var SyncError = exports.SyncError = (0, helpers.createCustomErrorClass)("SyncError"); - var PairingFailed = exports.PairingFailed = (0, helpers.createCustomErrorClass)("PairingFailed"); - var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers.createCustomErrorClass)("GenuineCheckFailed"); - var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers.createCustomErrorClass)("LedgerAPI4xx"); - var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers.createCustomErrorClass)("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers.createCustomErrorClass)("NoDBPathGiven"); - var DBWrongPassword = exports.DBWrongPassword = (0, helpers.createCustomErrorClass)("DBWrongPassword"); - var DBNotReset = exports.DBNotReset = (0, helpers.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = exports.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - }); - - unwrapExports(lib); - var lib_1 = lib.StatusCodes; - var lib_2 = lib.DBNotReset; - var lib_3 = lib.DBWrongPassword; - var lib_4 = lib.NoDBPathGiven; - var lib_5 = lib.FirmwareOrAppUpdateRequired; - var lib_6 = lib.LedgerAPI5xx; - var lib_7 = lib.LedgerAPI4xx; - var lib_8 = lib.GenuineCheckFailed; - var lib_9 = lib.PairingFailed; - var lib_10 = lib.SyncError; - var lib_11 = lib.FeeRequired; - var lib_12 = lib.FeeNotLoaded; - var lib_13 = lib.CantScanQRCode; - var lib_14 = lib.ETHAddressNonEIP; - var lib_15 = lib.WrongDeviceForAccount; - var lib_16 = lib.WebsocketConnectionFailed; - var lib_17 = lib.WebsocketConnectionError; - var lib_18 = lib.DeviceShouldStayInApp; - var lib_19 = lib.TransportInterfaceNotAvailable; - var lib_20 = lib.TransportOpenUserCancelled; - var lib_21 = lib.UserRefusedOnDevice; - var lib_22 = lib.UserRefusedAllowManager; - var lib_23 = lib.UserRefusedFirmwareUpdate; - var lib_24 = lib.UserRefusedAddress; - var lib_25 = lib.UserRefusedDeviceNameChange; - var lib_26 = lib.UpdateYourApp; - var lib_27 = lib.UnexpectedBootloader; - var lib_28 = lib.TimeoutTagged; - var lib_29 = lib.PasswordIncorrectError; - var lib_30 = lib.PasswordsDontMatchError; - var lib_31 = lib.NotEnoughGas; - var lib_32 = lib.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_33 = lib.NotEnoughBalance; - var lib_34 = lib.NoAddressesFound; - var lib_35 = lib.NetworkDown; - var lib_36 = lib.ManagerUninstallBTCDep; - var lib_37 = lib.ManagerNotEnoughSpaceError; - var lib_38 = lib.ManagerDeviceLockedError; - var lib_39 = lib.ManagerAppRelyOnBTCError; - var lib_40 = lib.ManagerAppAlreadyInstalledError; - var lib_41 = lib.LedgerAPINotAvailable; - var lib_42 = lib.LedgerAPIErrorWithMessage; - var lib_43 = lib.LedgerAPIError; - var lib_44 = lib.UnknownMCU; - var lib_45 = lib.LatestMCUInstalledError; - var lib_46 = lib.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_47 = lib.InvalidAddress; - var lib_48 = lib.HardResetFail; - var lib_49 = lib.FeeEstimationFailed; - var lib_50 = lib.EthAppPleaseEnableContractData; - var lib_51 = lib.EnpointConfigError; - var lib_52 = lib.DisconnectedDeviceDuringOperation; - var lib_53 = lib.DisconnectedDevice; - var lib_54 = lib.DeviceSocketNoBulkStatus; - var lib_55 = lib.DeviceSocketFail; - var lib_56 = lib.DeviceNameInvalid; - var lib_57 = lib.DeviceHalted; - var lib_58 = lib.DeviceInOSUExpected; - var lib_59 = lib.DeviceOnDashboardExpected; - var lib_60 = lib.DeviceNotGenuineError; - var lib_61 = lib.DeviceGenuineSocketEarlyClose; - var lib_62 = lib.DeviceAppVerifyNotSupported; - var lib_63 = lib.CurrencyNotSupported; - var lib_64 = lib.CashAddrNotSupported; - var lib_65 = lib.CantOpenDevice; - var lib_66 = lib.BtcUnmatchedApp; - var lib_67 = lib.BluetoothRequired; - var lib_68 = lib.AccountNameRequiredError; - var lib_69 = lib.addCustomErrorDeserializer; - var lib_70 = lib.createCustomErrorClass; - var lib_71 = lib.deserializeError; - var lib_72 = lib.serializeError; - var lib_73 = lib.TransportError; - var lib_74 = lib.getAltStatusMessage; - var lib_75 = lib.TransportStatusError; - - var Transport_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _events3 = _interopRequireDefault(EventEmitter); - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - exports.TransportError = lib.TransportError; - exports.TransportStatusError = lib.TransportStatusError; - exports.StatusCodes = lib.StatusCodes; - exports.getAltStatusMessage = lib.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new lib.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new lib.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new lib.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new lib.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new lib.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new lib.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; - - }); - - unwrapExports(Transport_1); - var Transport_2 = Transport_1.getAltStatusMessage; - var Transport_3 = Transport_1.StatusCodes; - var Transport_4 = Transport_1.TransportStatusError; - var Transport_5 = Transport_1.TransportError; - - var hidFraming = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - - var Tag = 0x05; - - function asUInt16BE(value) { - var b = Buffer.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - - var initialAcc = { - data: Buffer.alloc(0), - dataLength: 0, - sequence: 0 - }; - - /** - * - */ - var createHIDframing = function createHIDframing(channel, packetSize) { - return { - makeBlocks: function makeBlocks(apdu) { - var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer.concat([data, // fill data with padding - Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); - - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function reduceResponse(acc, chunk) { - var _ref = acc || initialAcc, - data = _ref.data, - dataLength = _ref.dataLength, - sequence = _ref.sequence; - - if (chunk.readUInt16BE(0) !== channel) { - throw new lib.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new lib.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new lib.TransportError("Invalid sequence", "InvalidSequence"); - } - - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - - exports.default = createHIDframing; - - }); - - unwrapExports(hidFraming); - - var lib$1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - /** - * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) - * - ** Model - * Ledger Nano S : 0x10 - * Ledger Blue : 0x00 - * Ledger Nano X : 0x40 - * - ** Interface support bitfield - * Generic HID : 0x01 - * Keyboard HID : 0x02 - * U2F : 0x04 - * CCID : 0x08 - * WebUSB : 0x10 - */ - - var IIGenericHID = exports.IIGenericHID = 0x01; - var IIKeyboardHID = exports.IIKeyboardHID = 0x02; - var IIU2F = exports.IIU2F = 0x04; - var IICCID = exports.IICCID = 0x08; - var IIWebUSB = exports.IIWebUSB = 0x10; - - var devices = { - blue: { - id: "blue", - productName: "Ledger Blue", - productIdMM: 0, - legacyUsbProductId: 0x0000, - usbOnly: true - }, - nanoS: { - id: "nanoS", - productName: "Ledger Nano S", - productIdMM: 1, - legacyUsbProductId: 0x0001, - usbOnly: true - }, - nanoX: { - id: "nanoX", - productName: "Ledger Nano X", - productIdMM: 4, - legacyUsbProductId: 0x0004, - usbOnly: false, - bluetoothSpec: [{ - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" - }, { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572" - }] - } - }; - - // $FlowFixMe - var devicesList = Object.values(devices); - - /** - * - */ - var ledgerUSBVendorId = exports.ledgerUSBVendorId = 0x2c97; - - /** - * - */ - var getDeviceModel = exports.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; - - /** - * - */ - var identifyUSBProductId = exports.identifyUSBProductId = function identifyUSBProductId(usbProductId) { - var legacy = devicesList.find(function (d) { - return d.legacyUsbProductId === usbProductId; - }); - if (legacy) return legacy; - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { - return d.productIdMM === mm; - }); - return deviceModel; - }; - - var bluetoothServices = []; - var serviceUuidToInfos = {}; - - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; - - if (_bluetoothSpec) { - for (var i = 0; i < _bluetoothSpec.length; i++) { - var spec = _bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); - } - } - } - - /** - * - */ - var getBluetoothServiceUuids = exports.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - var getInfosForServiceUuid = exports.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; - - /** - * - */ - - - /** - * - */ - - - /** - * - */ - - }); - - unwrapExports(lib$1); - var lib_1$1 = lib$1.IIGenericHID; - var lib_2$1 = lib$1.IIKeyboardHID; - var lib_3$1 = lib$1.IIU2F; - var lib_4$1 = lib$1.IICCID; - var lib_5$1 = lib$1.IIWebUSB; - var lib_6$1 = lib$1.ledgerUSBVendorId; - var lib_7$1 = lib$1.getDeviceModel; - var lib_8$1 = lib$1.identifyUSBProductId; - var lib_9$1 = lib$1.getBluetoothServiceUuids; - var lib_10$1 = lib$1.getInfosForServiceUuid; - - var lib$2 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - /** - * A Log object - */ - var id = 0; - var subscribers = []; - - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = exports.log = function log(type, message, data) { - var obj = { type: type, id: String(++id), date: new Date() }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = exports.listen = function listen(cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } - - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; - - }); - - var index$2 = unwrapExports(lib$2); - var lib_1$2 = lib$2.log; - var lib_2$2 = lib$2.listen; - - var index$3 = /*#__PURE__*/Object.freeze({ - default: index$2, - __moduleExports: lib$2, - log: lib_1$2, - listen: lib_2$2 - }); - - var webusb = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.isSupported = exports.getFirstLedgerDevice = exports.getLedgerDevices = exports.requestLedgerDevice = undefined; - - var requestLedgerDevice = exports.requestLedgerDevice = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var device; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return navigator.usb.requestDevice({ filters: ledgerDevices }); - - case 2: - device = _context.sent; - return _context.abrupt("return", device); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function requestLedgerDevice() { - return _ref.apply(this, arguments); - }; - }(); - - var getLedgerDevices = exports.getLedgerDevices = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var devices; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return navigator.usb.getDevices(); - - case 2: - devices = _context2.sent; - return _context2.abrupt("return", devices.filter(function (d) { - return d.vendorId === lib$1.ledgerUSBVendorId; - })); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function getLedgerDevices() { - return _ref2.apply(this, arguments); - }; - }(); - - var getFirstLedgerDevice = exports.getFirstLedgerDevice = function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var existingDevices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getLedgerDevices(); - - case 2: - existingDevices = _context3.sent; - - if (!(existingDevices.length > 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", existingDevices[0]); - - case 5: - return _context3.abrupt("return", requestLedgerDevice()); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); - - - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - var ledgerDevices = [{ vendorId: lib$1.ledgerUSBVendorId }]; - - var isSupported = exports.isSupported = function isSupported() { - return Promise.resolve( - // $FlowFixMe - !!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; - - }); - - unwrapExports(webusb); - var webusb_1 = webusb.isSupported; - var webusb_2 = webusb.getFirstLedgerDevice; - var webusb_3 = webusb.getLedgerDevices; - var webusb_4 = webusb.requestLedgerDevice; - - var TransportWebUSB_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _hwTransport2 = _interopRequireDefault(Transport_1); - - - - var _hidFraming2 = _interopRequireDefault(hidFraming); - - - - - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var configurationValue = 1; - var interfaceNumber = 2; - var endpointNumber = 3; - - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ - - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); - - function TransportWebUSB(device) { - _classCallCheck(this, TransportWebUSB); - - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); - - _initialiseProps.call(_this); - - _this.device = device; - _this.deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - return _this; - } - - /** - * Check if WebUSB transport is supported. - */ - - - /** - * List the WebUSB devices that was previously authorized by the user. - */ - - - /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! - */ - - - _createClass(TransportWebUSB, [{ - key: "close", - - - /** - * Release the transport device - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.exchangeBusyPromise; - - case 2: - _context.next = 4; - return this.device.releaseInterface(interfaceNumber); - - case 4: - _context.next = 6; - return this.device.reset(); - - case 6: - _context.next = 8; - return this.device.close(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _ref.apply(this, arguments); - } - - return close; - }() - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey() {} - }], [{ - key: "request", - - - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var device; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return (0, webusb.requestLedgerDevice)(); - - case 2: - device = _context2.sent; - return _context2.abrupt("return", TransportWebUSB.open(device)); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function request() { - return _ref2.apply(this, arguments); - } - - return request; - }() - - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ - - }, { - key: "openConnected", - value: function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var devices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return (0, webusb.getLedgerDevices)(); - - case 2: - devices = _context3.sent; - - if (!(devices.length === 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", null); - - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function openConnected() { - return _ref3.apply(this, arguments); - } - - return openConnected; - }() - - /** - * Create a Ledger transport with a USBDevice - */ - - }, { - key: "open", - value: function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { - var transport, onDisconnect; - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return device.open(); - - case 2: - if (!(device.configuration === null)) { - _context4.next = 5; - break; - } - - _context4.next = 5; - return device.selectConfiguration(configurationValue); - - case 5: - _context4.next = 7; - return device.reset(); - - case 7: - _context4.prev = 7; - _context4.next = 10; - return device.claimInterface(interfaceNumber); - - case 10: - _context4.next = 17; - break; - - case 12: - _context4.prev = 12; - _context4.t0 = _context4["catch"](7); - _context4.next = 16; - return device.close(); - - case 16: - throw new lib.TransportInterfaceNotAvailable(_context4.t0.message); - - case 17: - transport = new TransportWebUSB(device); - - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new lib.DisconnectedDevice()); - } - }; - // $FlowFixMe - - - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); - - case 21: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[7, 12]]); - })); - - function open(_x) { - return _ref4.apply(this, arguments); - } - - return open; - }() - }]); - - return TransportWebUSB; - }(_hwTransport2.default); - - TransportWebUSB.isSupported = webusb.isSupported; - TransportWebUSB.list = webusb.getLedgerDevices; - - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - (0, webusb.getFirstLedgerDevice)().then(function (device) { - if (!unsubscribed) { - var deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); - observer.complete(); - } - }, function (error) { - observer.error(new lib.TransportOpenUserCancelled(error.message)); - }); - function unsubscribe() { - unsubscribed = true; - } - return { unsubscribe: unsubscribe }; - }; - - var _initialiseProps = function _initialiseProps() { - var _this2 = this; - - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; - - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; - - this.exchange = function (apdu) { - return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - channel = _this2.channel, packetSize = _this2.packetSize; - - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); - - framing = (0, _hidFraming2.default)(channel, packetSize); - - // Write... - - blocks = framing.makeBlocks(apdu); - i = 0; - - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } - - (0, lib$2.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); - - case 9: - i++; - _context5.next = 5; - break; - - case 12: - - // Read... - result = void 0; - acc = void 0; - - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } - - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); - - case 17: - r = _context5.sent; - buffer = Buffer.from(r.data.buffer); - - (0, lib$2.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; - - case 23: - - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); - - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5, _this2); - }))).catch(function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this2._emitDisconnect(e); - throw new lib.DisconnectedDeviceDuringOperation(e.message); - } - throw e; - }); - }; - }; - - exports.default = TransportWebUSB; - - }); - - var TransportWebUSB = unwrapExports(TransportWebUSB_1); - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ - default: TransportWebUSB, - __moduleExports: TransportWebUSB_1 - }); - - // Copyright 2014 Google Inc. All rights reserved - - /** Namespace for the U2F api. - * @type {Object} - */ - var u2f = u2f || {}; - - var googleU2fApi = u2f; // Adaptation for u2f-api package - - /** - * The U2F extension id - * @type {string} - * @const - */ - u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; - - /** - * Message types for messsages to/from the extension - * @const - * @enum {string} - */ - u2f.MessageTypes = { - 'U2F_REGISTER_REQUEST': 'u2f_register_request', - 'U2F_SIGN_REQUEST': 'u2f_sign_request', - 'U2F_REGISTER_RESPONSE': 'u2f_register_response', - 'U2F_SIGN_RESPONSE': 'u2f_sign_response' - }; - - /** - * Response status codes - * @const - * @enum {number} - */ - u2f.ErrorCodes = { - 'OK': 0, - 'OTHER_ERROR': 1, - 'BAD_REQUEST': 2, - 'CONFIGURATION_UNSUPPORTED': 3, - 'DEVICE_INELIGIBLE': 4, - 'TIMEOUT': 5 - }; - - - // Low level MessagePort API support - - /** - * Call MessagePort disconnect - */ - u2f.disconnect = function() { - if (u2f.port_ && u2f.port_.port_) { - u2f.port_.port_.disconnect(); - u2f.port_ = null; - } - }; - - /** - * Sets up a MessagePort to the U2F extension using the - * available mechanisms. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - */ - u2f.getMessagePort = function(callback) { - if (typeof chrome != 'undefined' && chrome.runtime) { - // The actual message here does not matter, but we need to get a reply - // for the callback to run. Thus, send an empty signature request - // in order to get a failure response. - var msg = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: [] - }; - chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { - if (!chrome.runtime.lastError) { - // We are on a whitelisted origin and can talk directly - // with the extension. - u2f.getChromeRuntimePort_(callback); - } else { - // chrome.runtime was available, but we couldn't message - // the extension directly, use iframe - u2f.getIframePort_(callback); - } - }); - } else { - // chrome.runtime was not available at all, which is normal - // when this origin doesn't have access to any extensions. - u2f.getIframePort_(callback); - } - }; - - /** - * Connects directly to the extension via chrome.runtime.connect - * @param {function(u2f.WrappedChromeRuntimePort_)} callback - * @private - */ - u2f.getChromeRuntimePort_ = function(callback) { - var port = chrome.runtime.connect(u2f.EXTENSION_ID, - {'includeTlsChannelId': true}); - setTimeout(function() { - callback(null, new u2f.WrappedChromeRuntimePort_(port)); - }, 0); - }; - - /** - * A wrapper for chrome.runtime.Port that is compatible with MessagePort. - * @param {Port} port - * @constructor - * @private - */ - u2f.WrappedChromeRuntimePort_ = function(port) { - this.port_ = port; - }; - - /** - * Posts a message on the underlying channel. - * @param {Object} message - */ - u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { - this.port_.postMessage(message); - }; - - /** - * Emulates the HTML 5 addEventListener interface. Works only for the - * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. - * @param {string} eventName - * @param {function({data: Object})} handler - */ - u2f.WrappedChromeRuntimePort_.prototype.addEventListener = - function(eventName, handler) { - var name = eventName.toLowerCase(); - if (name == 'message' || name == 'onmessage') { - this.port_.onMessage.addListener(function(message) { - // Emulate a minimal MessageEvent object - handler({'data': message}); - }); - } else { - console.error('WrappedChromeRuntimePort only supports onMessage'); - } - }; - - /** - * Sets up an embedded trampoline iframe, sourced from the extension. - * @param {function(MessagePort)} callback - * @private - */ - u2f.getIframePort_ = function(callback) { - // Create the iframe - var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; - var iframe = document.createElement('iframe'); - iframe.src = iframeOrigin + '/u2f-comms.html'; - iframe.setAttribute('style', 'display:none'); - document.body.appendChild(iframe); - - var hasCalledBack = false; - - var channel = new MessageChannel(); - var ready = function(message) { - if (message.data == 'ready') { - channel.port1.removeEventListener('message', ready); - if (!hasCalledBack) - { - hasCalledBack = true; - callback(null, channel.port1); - } - } else { - console.error('First event on iframe port was not "ready"'); - } - }; - channel.port1.addEventListener('message', ready); - channel.port1.start(); - - iframe.addEventListener('load', function() { - // Deliver the port to the iframe and initialize - iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); - }); - - // Give this 200ms to initialize, after that, we treat this method as failed - setTimeout(function() { - if (!hasCalledBack) - { - hasCalledBack = true; - callback(new Error("IFrame extension not supported")); - } - }, 200); - }; - - - // High-level JS API - - /** - * Default extension response timeout in seconds. - * @const - */ - u2f.EXTENSION_TIMEOUT_SEC = 30; - - /** - * A singleton instance for a MessagePort to the extension. - * @type {MessagePort|u2f.WrappedChromeRuntimePort_} - * @private - */ - u2f.port_ = null; - - /** - * Callbacks waiting for a port - * @type {Array.} - * @private - */ - u2f.waitingForPort_ = []; - - /** - * A counter for requestIds. - * @type {number} - * @private - */ - u2f.reqCounter_ = 0; - - /** - * A map from requestIds to client callbacks - * @type {Object.} - * @private - */ - u2f.callbackMap_ = {}; - - /** - * Creates or retrieves the MessagePort singleton to use. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - * @private - */ - u2f.getPortSingleton_ = function(callback) { - if (u2f.port_) { - callback(null, u2f.port_); - } else { - if (u2f.waitingForPort_.length == 0) { - u2f.getMessagePort(function(err, port) { - if (!err) { - u2f.port_ = port; - u2f.port_.addEventListener('message', - /** @type {function(Event)} */ (u2f.responseHandler_)); - } - - // Careful, here be async callbacks. Maybe. - while (u2f.waitingForPort_.length) - u2f.waitingForPort_.shift()(err, port); - }); - } - u2f.waitingForPort_.push(callback); - } - }; - - /** - * Handles response messages from the extension. - * @param {MessageEvent.} message - * @private - */ - u2f.responseHandler_ = function(message) { - var response = message.data; - var reqId = response['requestId']; - if (!reqId || !u2f.callbackMap_[reqId]) { - console.error('Unknown or missing requestId in response.'); - return; - } - var cb = u2f.callbackMap_[reqId]; - delete u2f.callbackMap_[reqId]; - cb(null, response['responseData']); - }; - - /** - * Calls the callback with true or false as first and only argument - * @param {Function} callback - */ - u2f.isSupported = function(callback) { - u2f.getPortSingleton_(function(err, port) { - callback(!err); - }); - }; - - /** - * Dispatches an array of sign requests to available U2F tokens. - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.SignResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: signRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - /** - * Dispatches register requests to available U2F tokens. An array of sign - * requests identifies already registered tokens. - * @param {Array.} registerRequests - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.RegisterResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.register = function(registerRequests, signRequests, - callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_REGISTER_REQUEST, - signRequests: signRequests, - registerRequests: registerRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - var u2fApi = API; - - - - // Feature detection (yes really) - var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; - var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) - && !navigator.userAgent.match( /Chrome\// ); - var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); - - var _backend = null; - function getBackend( Promise ) - { - if ( !_backend ) - _backend = new Promise( function( resolve, reject ) - { - function notSupported( ) - { - // Note; {native: true} means *not* using Google's hack - resolve( { u2f: null, native: true } ); - } - - if ( !isBrowser ) - return notSupported( ); - - if ( isSafari ) - // Safari doesn't support U2F, and the Safari-FIDO-U2F - // extension lacks full support (Multi-facet apps), so we - // block it until proper support. - return notSupported( ); - - var hasNativeSupport = - ( typeof window.u2f !== 'undefined' ) && - ( typeof window.u2f.sign === 'function' ); - - if ( hasNativeSupport ) - resolve( { u2f: window.u2f, native: true } ); - - if ( isEDGE ) - // We don't want to check for Google's extension hack on EDGE - // as it'll cause trouble (popups, etc) - return notSupported( ); - - if ( location.protocol === 'http:' ) - // U2F isn't supported over http, only https - return notSupported( ); - - if ( typeof MessageChannel === 'undefined' ) - // Unsupported browser, the chrome hack would throw - return notSupported( ); - - // Test for google extension support - googleU2fApi.isSupported( function( ok ) - { - if ( ok ) - resolve( { u2f: googleU2fApi, native: false } ); - else - notSupported( ); - } ); - } ); - - return _backend; - } - - function API( Promise ) - { - return { - isSupported : isSupported.bind( Promise ), - ensureSupport : ensureSupport.bind( Promise ), - register : register.bind( Promise ), - sign : sign.bind( Promise ), - ErrorCodes : API.ErrorCodes, - ErrorNames : API.ErrorNames - }; - } - - API.ErrorCodes = { - CANCELLED: -1, - OK: 0, - OTHER_ERROR: 1, - BAD_REQUEST: 2, - CONFIGURATION_UNSUPPORTED: 3, - DEVICE_INELIGIBLE: 4, - TIMEOUT: 5 - }; - API.ErrorNames = { - "-1": "CANCELLED", - "0": "OK", - "1": "OTHER_ERROR", - "2": "BAD_REQUEST", - "3": "CONFIGURATION_UNSUPPORTED", - "4": "DEVICE_INELIGIBLE", - "5": "TIMEOUT" - }; - - function makeError( msg, err ) - { - var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR - var type = API.ErrorNames[ '' + code ]; - var error = new Error( msg ); - error.metaData = { - type: type, - code: code - }; - return error; - } - - function deferPromise( Promise, promise ) - { - var ret = { }; - ret.promise = new Promise( function( resolve, reject ) { - ret.resolve = resolve; - ret.reject = reject; - promise.then( resolve, reject ); - } ); - /** - * Reject request promise and disconnect port if 'disconnect' flag is true - * @param {string} msg - * @param {boolean} disconnect - */ - ret.promise.cancel = function( msg, disconnect ) - { - getBackend( Promise ) - .then( function( backend ) - { - if ( disconnect && !backend.native ) - backend.u2f.disconnect( ); - - ret.reject( makeError( msg, { errorCode: -1 } ) ); - } ); - }; - return ret; - } - - function isSupported( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( function( backend ) - { - return !!backend.u2f; - } ); - } - - function _ensureSupport( backend ) - { - if ( !backend.u2f ) - { - if ( location.protocol === 'http:' ) - throw new Error( "U2F isn't supported over http, only https" ); - throw new Error( "U2F not supported" ); - } - } - - function ensureSupport( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( _ensureSupport ); - } - - function register( registerRequests, signRequests /* = null */, timeout ) - { - var Promise = this; - - if ( !Array.isArray( registerRequests ) ) - registerRequests = [ registerRequests ]; - - if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) - { - timeout = signRequests; - signRequests = null; - } - - if ( !signRequests ) - signRequests = [ ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = registerRequests[ 0 ].appId; - - u2f.register( - appId, registerRequests, signRequests, cbNative, timeout ); - } - else - { - u2f.register( - registerRequests, signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function sign( signRequests, timeout ) - { - var Promise = this; - - if ( !Array.isArray( signRequests ) ) - signRequests = [ signRequests ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = signRequests[ 0 ].appId; - var challenge = signRequests[ 0 ].challenge; - - u2f.sign( appId, challenge, signRequests, cbNative, timeout ); - } - else - { - u2f.sign( signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function makeDefault( func ) - { - API[ func ] = function( ) - { - if ( !commonjsGlobal.Promise ) - // This is very unlikely to ever happen, since browsers - // supporting U2F will most likely support Promises. - throw new Error( "The platform doesn't natively support promises" ); - - var args = [ ].slice.call( arguments ); - return API( commonjsGlobal.Promise )[ func ].apply( null, args ); - }; - } - - // Provide default functions using the built-in Promise if available. - makeDefault( 'isSupported' ); - makeDefault( 'ensureSupport' ); - makeDefault( 'register' ); - makeDefault( 'sign' ); - - var u2fApi$1 = u2fApi; - - var helpers$2 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = exports.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = exports.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - }); - - unwrapExports(helpers$2); - var helpers_1$1 = helpers$2.addCustomErrorDeserializer; - var helpers_2$1 = helpers$2.createCustomErrorClass; - var helpers_3$1 = helpers$2.deserializeError; - var helpers_4$1 = helpers$2.serializeError; - - var lib$3 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughGas = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; - exports.TransportError = TransportError; - exports.getAltStatusMessage = getAltStatusMessage; - exports.TransportStatusError = TransportStatusError; - - - - exports.serializeError = helpers$2.serializeError; - exports.deserializeError = helpers$2.deserializeError; - exports.createCustomErrorClass = helpers$2.createCustomErrorClass; - exports.addCustomErrorDeserializer = helpers$2.addCustomErrorDeserializer; - var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers$2.createCustomErrorClass)("AccountNameRequired"); - var BluetoothRequired = exports.BluetoothRequired = (0, helpers$2.createCustomErrorClass)("BluetoothRequired"); - var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers$2.createCustomErrorClass)("BtcUnmatchedApp"); - var CantOpenDevice = exports.CantOpenDevice = (0, helpers$2.createCustomErrorClass)("CantOpenDevice"); - var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers$2.createCustomErrorClass)("CashAddrNotSupported"); - var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers$2.createCustomErrorClass)("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers$2.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers$2.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers$2.createCustomErrorClass)("DeviceNotGenuine"); - var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers$2.createCustomErrorClass)("DeviceOnDashboardExpected"); - var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers$2.createCustomErrorClass)("DeviceInOSUExpected"); - var DeviceHalted = exports.DeviceHalted = (0, helpers$2.createCustomErrorClass)("DeviceHalted"); - var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers$2.createCustomErrorClass)("DeviceNameInvalid"); - var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers$2.createCustomErrorClass)("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers$2.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers$2.createCustomErrorClass)("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers$2.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = exports.EnpointConfigError = (0, helpers$2.createCustomErrorClass)("EnpointConfig"); - var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers$2.createCustomErrorClass)("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers$2.createCustomErrorClass)("FeeEstimationFailed"); - var HardResetFail = exports.HardResetFail = (0, helpers$2.createCustomErrorClass)("HardResetFail"); - var InvalidAddress = exports.InvalidAddress = (0, helpers$2.createCustomErrorClass)("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers$2.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers$2.createCustomErrorClass)("LatestMCUInstalledError"); - var UnknownMCU = exports.UnknownMCU = (0, helpers$2.createCustomErrorClass)("UnknownMCU"); - var LedgerAPIError = exports.LedgerAPIError = (0, helpers$2.createCustomErrorClass)("LedgerAPIError"); - var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers$2.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers$2.createCustomErrorClass)("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers$2.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers$2.createCustomErrorClass)("ManagerAppRelyOnBTC"); - var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers$2.createCustomErrorClass)("ManagerDeviceLocked"); - var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers$2.createCustomErrorClass)("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers$2.createCustomErrorClass)("ManagerUninstallBTCDep"); - var NetworkDown = exports.NetworkDown = (0, helpers$2.createCustomErrorClass)("NetworkDown"); - var NoAddressesFound = exports.NoAddressesFound = (0, helpers$2.createCustomErrorClass)("NoAddressesFound"); - var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers$2.createCustomErrorClass)("NotEnoughBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers$2.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - var NotEnoughGas = exports.NotEnoughGas = (0, helpers$2.createCustomErrorClass)("NotEnoughGas"); - var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers$2.createCustomErrorClass)("PasswordsDontMatch"); - var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers$2.createCustomErrorClass)("PasswordIncorrect"); - var TimeoutTagged = exports.TimeoutTagged = (0, helpers$2.createCustomErrorClass)("TimeoutTagged"); - var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers$2.createCustomErrorClass)("UnexpectedBootloader"); - var UpdateYourApp = exports.UpdateYourApp = (0, helpers$2.createCustomErrorClass)("UpdateYourApp"); - var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers$2.createCustomErrorClass)("UserRefusedDeviceNameChange"); - var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers$2.createCustomErrorClass)("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers$2.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers$2.createCustomErrorClass)("UserRefusedAllowManager"); - var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers$2.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers$2.createCustomErrorClass)("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers$2.createCustomErrorClass)("TransportInterfaceNotAvailable"); - var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers$2.createCustomErrorClass)("DeviceShouldStayInApp"); - var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers$2.createCustomErrorClass)("WebsocketConnectionError"); - var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers$2.createCustomErrorClass)("WebsocketConnectionFailed"); - var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers$2.createCustomErrorClass)("WrongDeviceForAccount"); - var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers$2.createCustomErrorClass)("ETHAddressNonEIP"); - var CantScanQRCode = exports.CantScanQRCode = (0, helpers$2.createCustomErrorClass)("CantScanQRCode"); - var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers$2.createCustomErrorClass)("FeeNotLoaded"); - var FeeRequired = exports.FeeRequired = (0, helpers$2.createCustomErrorClass)("FeeRequired"); - var SyncError = exports.SyncError = (0, helpers$2.createCustomErrorClass)("SyncError"); - var PairingFailed = exports.PairingFailed = (0, helpers$2.createCustomErrorClass)("PairingFailed"); - var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers$2.createCustomErrorClass)("GenuineCheckFailed"); - var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers$2.createCustomErrorClass)("LedgerAPI4xx"); - var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers$2.createCustomErrorClass)("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers$2.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers$2.createCustomErrorClass)("NoDBPathGiven"); - var DBWrongPassword = exports.DBWrongPassword = (0, helpers$2.createCustomErrorClass)("DBWrongPassword"); - var DBNotReset = exports.DBNotReset = (0, helpers$2.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, helpers$2.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = exports.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, helpers$2.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - }); - - unwrapExports(lib$3); - var lib_1$3 = lib$3.StatusCodes; - var lib_2$3 = lib$3.DBNotReset; - var lib_3$2 = lib$3.DBWrongPassword; - var lib_4$2 = lib$3.NoDBPathGiven; - var lib_5$2 = lib$3.FirmwareOrAppUpdateRequired; - var lib_6$2 = lib$3.LedgerAPI5xx; - var lib_7$2 = lib$3.LedgerAPI4xx; - var lib_8$2 = lib$3.GenuineCheckFailed; - var lib_9$2 = lib$3.PairingFailed; - var lib_10$2 = lib$3.SyncError; - var lib_11$1 = lib$3.FeeRequired; - var lib_12$1 = lib$3.FeeNotLoaded; - var lib_13$1 = lib$3.CantScanQRCode; - var lib_14$1 = lib$3.ETHAddressNonEIP; - var lib_15$1 = lib$3.WrongDeviceForAccount; - var lib_16$1 = lib$3.WebsocketConnectionFailed; - var lib_17$1 = lib$3.WebsocketConnectionError; - var lib_18$1 = lib$3.DeviceShouldStayInApp; - var lib_19$1 = lib$3.TransportInterfaceNotAvailable; - var lib_20$1 = lib$3.TransportOpenUserCancelled; - var lib_21$1 = lib$3.UserRefusedOnDevice; - var lib_22$1 = lib$3.UserRefusedAllowManager; - var lib_23$1 = lib$3.UserRefusedFirmwareUpdate; - var lib_24$1 = lib$3.UserRefusedAddress; - var lib_25$1 = lib$3.UserRefusedDeviceNameChange; - var lib_26$1 = lib$3.UpdateYourApp; - var lib_27$1 = lib$3.UnexpectedBootloader; - var lib_28$1 = lib$3.TimeoutTagged; - var lib_29$1 = lib$3.PasswordIncorrectError; - var lib_30$1 = lib$3.PasswordsDontMatchError; - var lib_31$1 = lib$3.NotEnoughGas; - var lib_32$1 = lib$3.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_33$1 = lib$3.NotEnoughBalance; - var lib_34$1 = lib$3.NoAddressesFound; - var lib_35$1 = lib$3.NetworkDown; - var lib_36$1 = lib$3.ManagerUninstallBTCDep; - var lib_37$1 = lib$3.ManagerNotEnoughSpaceError; - var lib_38$1 = lib$3.ManagerDeviceLockedError; - var lib_39$1 = lib$3.ManagerAppRelyOnBTCError; - var lib_40$1 = lib$3.ManagerAppAlreadyInstalledError; - var lib_41$1 = lib$3.LedgerAPINotAvailable; - var lib_42$1 = lib$3.LedgerAPIErrorWithMessage; - var lib_43$1 = lib$3.LedgerAPIError; - var lib_44$1 = lib$3.UnknownMCU; - var lib_45$1 = lib$3.LatestMCUInstalledError; - var lib_46$1 = lib$3.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_47$1 = lib$3.InvalidAddress; - var lib_48$1 = lib$3.HardResetFail; - var lib_49$1 = lib$3.FeeEstimationFailed; - var lib_50$1 = lib$3.EthAppPleaseEnableContractData; - var lib_51$1 = lib$3.EnpointConfigError; - var lib_52$1 = lib$3.DisconnectedDeviceDuringOperation; - var lib_53$1 = lib$3.DisconnectedDevice; - var lib_54$1 = lib$3.DeviceSocketNoBulkStatus; - var lib_55$1 = lib$3.DeviceSocketFail; - var lib_56$1 = lib$3.DeviceNameInvalid; - var lib_57$1 = lib$3.DeviceHalted; - var lib_58$1 = lib$3.DeviceInOSUExpected; - var lib_59$1 = lib$3.DeviceOnDashboardExpected; - var lib_60$1 = lib$3.DeviceNotGenuineError; - var lib_61$1 = lib$3.DeviceGenuineSocketEarlyClose; - var lib_62$1 = lib$3.DeviceAppVerifyNotSupported; - var lib_63$1 = lib$3.CurrencyNotSupported; - var lib_64$1 = lib$3.CashAddrNotSupported; - var lib_65$1 = lib$3.CantOpenDevice; - var lib_66$1 = lib$3.BtcUnmatchedApp; - var lib_67$1 = lib$3.BluetoothRequired; - var lib_68$1 = lib$3.AccountNameRequiredError; - var lib_69$1 = lib$3.addCustomErrorDeserializer; - var lib_70$1 = lib$3.createCustomErrorClass; - var lib_71$1 = lib$3.deserializeError; - var lib_72$1 = lib$3.serializeError; - var lib_73$1 = lib$3.TransportError; - var lib_74$1 = lib$3.getAltStatusMessage; - var lib_75$1 = lib$3.TransportStatusError; - - var Transport_1$1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _events3 = _interopRequireDefault(EventEmitter); - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - exports.TransportError = lib$3.TransportError; - exports.TransportStatusError = lib$3.TransportStatusError; - exports.StatusCodes = lib$3.StatusCodes; - exports.getAltStatusMessage = lib$3.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib$3.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new lib$3.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new lib$3.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new lib$3.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new lib$3.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new lib$3.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new lib$3.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; - - }); - - unwrapExports(Transport_1$1); - var Transport_2$1 = Transport_1$1.getAltStatusMessage; - var Transport_3$1 = Transport_1$1.StatusCodes; - var Transport_4$1 = Transport_1$1.TransportStatusError; - var Transport_5$1 = Transport_1$1.TransportError; - - var TransportU2F_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - - - var _hwTransport2 = _interopRequireDefault(Transport_1$1); - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - function wrapU2FTransportError(originalError, message, id) { - var err = new lib$3.TransportError(message, id); - // $FlowFixMe - err.originalError = originalError; - return err; - } - - function wrapApdu(apdu, key) { - var result = Buffer.alloc(apdu.length); - for (var i = 0; i < apdu.length; i++) { - result[i] = apdu[i] ^ key[i % key.length]; - } - return result; - } - - // Convert from normal to web-safe, strip trailing "="s - var webSafe64 = function webSafe64(base64) { - return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); - }; - - // Convert from web-safe to normal, add trailing "="s - var normal64 = function normal64(base64) { - return base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); - }; - - function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { - var keyHandle = wrapApdu(apdu, scrambleKey); - var challenge = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); - var signRequest = { - version: "U2F_V2", - keyHandle: webSafe64(keyHandle.toString("base64")), - challenge: webSafe64(challenge.toString("base64")), - appId: location.origin - }; - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); - return (0, u2fApi$1.sign)(signRequest, timeoutMillis / 1000).then(function (response) { - var signatureData = response.signatureData; - - if (typeof signatureData === "string") { - var data = Buffer.from(normal64(signatureData), "base64"); - var result = void 0; - if (!unwrap) { - result = data; - } else { - result = data.slice(5); - } - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return result; - } else { - throw response; - } - }); - } - - var transportInstances = []; - - function emitDisconnect() { - transportInstances.forEach(function (t) { - return t.emit("disconnect"); - }); - transportInstances = []; - } - - function isTimeoutU2FError(u2fError) { - return u2fError.metaData.code === 5; - } - - /** - * U2F web Transport implementation - * @example - * import TransportU2F from "@ledgerhq/hw-transport-u2f"; - * ... - * TransportU2F.create().then(transport => ...) - */ - - var TransportU2F = function (_Transport) { - _inherits(TransportU2F, _Transport); - - _createClass(TransportU2F, null, [{ - key: "open", - - - /** - * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) - */ - - - /* - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_) { - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", new TransportU2F()); - - case 1: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function open(_x) { - return _ref.apply(this, arguments); - } - - return open; - }() - - /* - */ - - }]); - - function TransportU2F() { - _classCallCheck(this, TransportU2F); - - var _this = _possibleConstructorReturn(this, (TransportU2F.__proto__ || Object.getPrototypeOf(TransportU2F)).call(this)); - - _this.unwrap = true; - - transportInstances.push(_this); - return _this; - } - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - - _createClass(TransportU2F, [{ - key: "exchange", - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(apdu) { - var isU2FError; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.prev = 0; - _context2.next = 3; - return attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); - - case 3: - return _context2.abrupt("return", _context2.sent); - - case 6: - _context2.prev = 6; - _context2.t0 = _context2["catch"](0); - isU2FError = _typeof(_context2.t0.metaData) === "object"; - - if (!isU2FError) { - _context2.next = 14; - break; - } - - if (isTimeoutU2FError(_context2.t0)) { - emitDisconnect(); - } - // the wrapping make error more usable and "printable" to the end user. - throw wrapU2FTransportError(_context2.t0, "Failed to sign with Ledger device: U2F " + _context2.t0.metaData.type, "U2F_" + _context2.t0.metaData.code); - - case 14: - throw _context2.t0; - - case 15: - case "end": - return _context2.stop(); - } - } - }, _callee2, this, [[0, 6]]); - })); - - function exchange(_x3) { - return _ref2.apply(this, arguments); - } - - return exchange; - }() - - /** - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer.from(scrambleKey, "ascii"); - } - - /** - */ - - }, { - key: "setUnwrap", - value: function setUnwrap(unwrap) { - this.unwrap = unwrap; - } - }, { - key: "close", - value: function close() { - // u2f have no way to clean things up - return Promise.resolve(); - } - }]); - - return TransportU2F; - }(_hwTransport2.default); - - TransportU2F.isSupported = u2fApi$1.isSupported; - - TransportU2F.list = function () { - return ( - // this transport is not discoverable but we are going to guess if it is here with isSupported() - (0, u2fApi$1.isSupported)().then(function (supported) { - return supported ? [null] : []; - }) - ); - }; - - TransportU2F.listen = function (observer) { - var unsubscribed = false; - (0, u2fApi$1.isSupported)().then(function (supported) { - if (unsubscribed) return; - if (supported) { - observer.next({ type: "add", descriptor: null }); - observer.complete(); - } else { - observer.error(new lib$3.TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); - } - }); - return { - unsubscribe: function unsubscribe() { - unsubscribed = true; - } - }; - }; - - exports.default = TransportU2F; - - }); - - var TransportU2F = unwrapExports(TransportU2F_1); - - var TransportU2F$1 = /*#__PURE__*/Object.freeze({ - default: TransportU2F, - __moduleExports: TransportU2F_1 - }); - - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop() {} - - var on = noop; - var addListener = noop; - var once = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; - - function binding(name) { - throw new Error('process.binding is not supported'); - } - - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - - var process = { - nextTick: nextTick, - title: title, - browser: browser, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - var inherits; - if (typeof Object.create === 'function'){ - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$1 = inherits; - - // Copyright Joyent, Inc. and other Node contributors. - var formatRegExp = /%[sdj%]/g; - function format(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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - 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 debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, 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 - _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); - } - - // 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 !== 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 length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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()`. - function isArray(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - - function isNull(arg) { - return arg === null; - } - - function isNullOrUndefined(arg) { - return arg == null; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isString(arg) { - return typeof arg === 'string'; - } - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - - function isBuffer(maybeBuf) { - return Buffer.isBuffer(maybeBuf); - } - - 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 - function log() { - console.log('%s - %s', timestamp(), format.apply(null, arguments)); - } - - function _extend(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 require$$0$1 = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray, - inspect: inspect, - deprecate: deprecate, - format: format, - debuglog: debuglog - } - - var inherits_browser = createCommonjsModule(function (module) { - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, 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) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - }); - - var inherits$2 = createCommonjsModule(function (module) { - try { - var util = require$$0$1; - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; - } catch (e) { - module.exports = inherits_browser; - } - }); - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } - - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - 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]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') - } - - function read (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) - } - - function write (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; - } - - var toString = {}.toString; - - var isArray$1 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use 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+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$1.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : true; - - /* - * Export kMaxLength after typed array support is determined. - */ - var _kMaxLength = kMaxLength(); - - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } - - return that - } - - /** - * 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$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer$1.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr - }; - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, 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$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - var actual = that.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') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that - } - - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray$1(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; - } - return Buffer$1.alloc(+length) - } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var 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$1.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$1.concat = function concat (list, length) { - if (!isArray$1(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer$1.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - 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 utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer$1.byteLength = byteLength; - - function slowToString (encoding, start, end) { - var 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 coersion 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; - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$1.prototype._isBuffer = true; - - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this - }; - - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this - }; - - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var 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$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; - - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 - }; - - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' - }; - - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - 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 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var 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 (isNaN(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$1.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(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 (Buffer$1.TYPED_ARRAY_SUPPORT && - 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) { - var indexSize = 1; - var arrLength = arr.length; - var 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$$1 (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read$$1(arr, i) === read$$1(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--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read$$1(arr, i + j) !== read$$1(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(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 latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, 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$1.prototype.write = function write$$1 (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; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var 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'; - - var 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': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(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$1.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 fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var 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 - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray (codePoints) { - var 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". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res - } - - Buffer$1.prototype.slice = function slice (start, end) { - var 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; - - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - 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$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val - }; - - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val - }; - - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; - - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var 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$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var 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$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(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$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var 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$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var 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$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.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; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - 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) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - 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('sourceStart out of bounds') - 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; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.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 (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // 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; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).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 stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var 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) { - var byteArray = []; - for (var 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) { - var c, hi, lo; - var byteArray = []; - for (var 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 toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } - - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } - - var buffer = /*#__PURE__*/Object.freeze({ - INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, - kMaxLength: _kMaxLength, - Buffer: Buffer$1, - SlowBuffer: SlowBuffer, - isBuffer: isBuffer$1 - }); - - var safeBuffer = createCommonjsModule(function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - - 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) - } - - // 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) - }; - }); - var safeBuffer_1 = safeBuffer.Buffer; - - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer$1.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer$1.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - // Copyright Joyent, Inc. and other Node contributors. - var isBufferEncoding = Buffer$1.isEncoding - || function(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 assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } - - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - function StringDecoder(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$1(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - } - - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; - }; - - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; - - StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; - }; - - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } - - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } - - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - - var stringDecoder = /*#__PURE__*/Object.freeze({ - StringDecoder: StringDecoder - }); - - Readable.ReadableState = ReadableState; - - var debug = debuglog('stream'); - inherits$1(Readable, EventEmitter); - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount$1 (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState(options, stream) { - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options && typeof options.read === 'function') this._read = options.read; - - EventEmitter.call(this); - } - - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); - }; - - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; - - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } - - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); - } - - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } - - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; - - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } - - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } - - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; - }; - - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } - - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } - - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); - } - } - - function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); - } - - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } - } - - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; - } - - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false); - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; - }; - - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } - - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } - } - - function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} - } - - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; - }; - - // exposed for testing purposes only. - Readable._fromList = fromList; - - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; - } - - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; - } - - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } - - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } - - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } - - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } - - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } - - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$1(Writable, EventEmitter); - - function nop() {} - - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } - - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable(options) { - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - } - - EventEmitter.call(this); - } - - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; - - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } - - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; - } - - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } - - return ret; - }; - - Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; - }; - - Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$1.from(chunk, encoding); - } - return chunk; - } - - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } - - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } - - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } - - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; - - Writable.prototype._writev = null; - - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; - } - - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } - - inherits$1(Duplex, Readable); - - var keys = Object.keys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); - } - - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - // a transform stream is a readable/writable stream where you do - inherits$1(Transform, Duplex); - - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } - - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) stream.push(data); - - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); - } - - Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; - - Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; - - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - function done(stream, er) { - if (er) return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); - } - - inherits$1(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); - } - - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - inherits$1(Stream, EventEmitter); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform; - Stream.PassThrough = PassThrough; - - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; - - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - - function Stream() { - EventEmitter.call(this); - } - - Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; - - var Buffer$2 = safeBuffer.Buffer; - var Transform$1 = Stream.Transform; - - - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$2.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } - - function HashBase (blockSize) { - Transform$1.call(this); - - this._block = Buffer$2.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; - - this._finalized = false; - } - - inherits$2(HashBase, Transform$1); - - HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$2.isBuffer(data)) data = Buffer$2.from(data, encoding); - - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } - - return this - }; - - HashBase.prototype._update = function () { - throw new Error('_update is not implemented') - }; - - HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); - - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; - - return digest - }; - - HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; - - var hashBase = HashBase; - - var Buffer$3 = safeBuffer.Buffer; - - var ARRAY16 = new Array(16); - - function MD5 () { - hashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } - - inherits$2(MD5, hashBase); - - MD5.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; - - MD5.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$3.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; - - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } - - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } - - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } - - function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } - - var md5_js = MD5; - - var Buffer$4 = buffer.Buffer; - - - - var ARRAY16$1 = new Array(16); - - var zl = [ - 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 zr = [ - 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 sl = [ - 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 sr = [ - 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 - ]; - - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - - function RIPEMD160 () { - hashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } - - inherits$2(RIPEMD160, hashBase); - - RIPEMD160.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; - - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; - - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } - - al = el; - el = dl; - dl = rotl$1(cl, 10); - cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; - } - - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer$$1 = Buffer$4.alloc ? Buffer$4.alloc(20) : new Buffer$4(20); - buffer$$1.writeInt32LE(this._a, 0); - buffer$$1.writeInt32LE(this._b, 4); - buffer$$1.writeInt32LE(this._c, 8); - buffer$$1.writeInt32LE(this._d, 12); - buffer$$1.writeInt32LE(this._e, 16); - return buffer$$1 - }; - - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } - - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } - - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } - - var ripemd160 = RIPEMD160; - - var Buffer$5 = safeBuffer.Buffer; - - // prototype class for hash functions - function Hash (blockSize, finalSize) { - this._block = Buffer$5.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } - - Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$5.from(data, enc); - } - - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); - } - } - - this._len += length; - return this - }; - - Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); - - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } - - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; - - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } - - this._update(this._block); - var hash = this._hash(); - - return enc ? hash.toString(enc) : hash - }; - - Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; - - var hash = Hash; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - - - - var Buffer$6 = safeBuffer.Buffer; - - var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W = new Array(80); - - function Sha () { - this.init(); - this._w = W; - - hash.call(this, 64, 56); - } - - inherits$2(Sha, hash); - - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } - - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - - - - var Buffer$7 = safeBuffer.Buffer; - - var K$1 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$1 = new Array(80); - - function Sha1 () { - this.init(); - this._w = W$1; - - hash.call(this, 64, 56); - } - - inherits$2(Sha1, hash); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } - - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } - - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$1[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha1 = Sha1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - - - var Buffer$8 = safeBuffer.Buffer; - - var K$2 = [ - 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 W$2 = new Array(64); - - function Sha256 () { - this.init(); - - this._w = W$2; // new Array(64) - - hash.call(this, 64, 56); - } - - inherits$2(Sha256, hash); - - Sha256.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this - }; - - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } - - function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } - - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } - - Sha256.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0(a) + maj(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); - - return H - }; - - var sha256 = Sha256; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - - - - var Buffer$9 = safeBuffer.Buffer; - - var W$3 = new Array(64); - - function Sha224 () { - this.init(); - - this._w = W$3; // new Array(64) - - hash.call(this, 64, 56); - } - - inherits$2(Sha224, sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this - }; - - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - - return H - }; - - var sha224 = Sha224; - - var Buffer$10 = safeBuffer.Buffer; - - var K$3 = [ - 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 W$4 = new Array(160); - - function Sha512 () { - this.init(); - this._w = W$4; - - hash.call(this, 128, 112); - } - - inherits$2(Sha512, hash); - - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; - - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - - return this - }; - - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0$1 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } - - function sigma1$1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } - - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } - - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } - - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } - - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } - - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } - - Sha512.prototype._update = function (M) { - var W = this._w; - - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; - - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - - W[i] = Wih; - W[i + 1] = Wil; - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj$1(ah, bh, ch); - var majl = maj$1(al, bl, cl); - - var sigma0h = sigma0$1(ah, al); - var sigma0l = sigma0$1(al, ah); - var sigma1h = sigma1$1(eh, el); - var sigma1l = sigma1$1(el, eh); - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$3[j]; - var Kil = K$3[j + 1]; - - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function () { - var H = Buffer$10.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; - - var sha512 = Sha512; - - var Buffer$11 = safeBuffer.Buffer; - - var W$5 = new Array(160); - - function Sha384 () { - this.init(); - this._w = W$5; - - hash.call(this, 128, 112); - } - - inherits$2(Sha384, sha512); - - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; - - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - - return this - }; - - Sha384.prototype._hash = function () { - var H = Buffer$11.allocUnsafe(48); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; - - var sha_js = createCommonjsModule(function (module) { - var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); - - var Algorithm = exports[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() - }; - - exports.sha = sha; - exports.sha1 = sha1; - exports.sha224 = sha224; - exports.sha256 = sha256; - exports.sha384 = sha384; - exports.sha512 = sha512; - }); - - var Buffer$12 = safeBuffer.Buffer; - var Transform$2 = Stream.Transform; - var StringDecoder$1 = stringDecoder.StringDecoder; - - - function CipherBase (hashMode) { - Transform$2.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$2(CipherBase, Transform$2); - - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$12.from(data, inputEnc); - } - - var outData = this._update(data); - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - - return outData - }; - - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; - - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; - - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; - - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer$12.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder$1(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; - - var cipherBase = CipherBase; - - function Hash$1 (hash) { - cipherBase.call(this, 'digest'); - - this._hash = hash; - } - - inherits$2(Hash$1, cipherBase); - - Hash$1.prototype._update = function (data) { - this._hash.update(data); - }; - - Hash$1.prototype._final = function () { - return this._hash.digest() - }; - - var browser$1 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new md5_js() - if (alg === 'rmd160' || alg === 'ripemd160') return new ripemd160() - - return new Hash$1(sha_js(alg)) - }; - - var browser$2 = /*#__PURE__*/Object.freeze({ - default: browser$1, - __moduleExports: browser$1 - }); - - exports.Btc = Btc$1; - exports.TransportWebUSB = TransportWebUSB$1; - exports.TransportU2F = TransportU2F$1; - exports.Log = index$3; - exports.createHash = browser$2; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.NewLedger={})}(this,(function(e){"use strict";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,r){return e(r={exports:{}},r.exports),r.exports}n((function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",i=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag";function u(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{u({},"")}catch(e){u=function(e,r,t){return e[r]=t}}function c(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),i=new A(n||[]);return a._invoke=function(e,r,t){var n=f;return function(o,a){if(n===p)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return N()}for(t.method=o,t.arg=a;;){var i=t.delegate;if(i){var s=D(i,t);if(s){if(s===v)continue;return s}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===f)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=p;var u=l(e,r,t);if("normal"===u.type){if(n=t.done?h:d,u.arg===v)continue;return{value:u.arg,done:t.done}}"throw"===u.type&&(n=h,t.method="throw",t.arg=u.arg)}}}(e,t,i),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var f="suspendedStart",d="suspendedYield",p="executing",h="completed",v={};function g(){}function m(){}function E(){}var y={};u(y,a,(function(){return this}));var C=Object.getPrototypeOf,w=C&&C(C(x([])));w&&w!==t&&n.call(w,a)&&(y=w);var I=E.prototype=g.prototype=Object.create(y);function b(e){["next","throw","return"].forEach((function(r){u(e,r,(function(e){return this._invoke(r,e)}))}))}function B(e,r){function t(o,a,i,s){var u=l(e[o],e,a);if("throw"!==u.type){var c=u.arg,f=c.value;return f&&"object"==typeof f&&n.call(f,"__await")?r.resolve(f.__await).then((function(e){t("next",e,i,s)}),(function(e){t("throw",e,i,s)})):r.resolve(f).then((function(e){c.value=e,i(c)}),(function(e){return t("throw",e,i,s)}))}s(u.arg)}var o;this._invoke=function(e,n){function a(){return new r((function(r,o){t(e,n,r,o)}))}return o=o?o.then(a,a):a()}}function D(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,D(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function T(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function S(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function x(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function t(){for(;++o=0;--a){var i=this.tryEntries[a],s=i.completion;if("root"===i.tryLoc)return o("end");if(i.tryLoc<=this.prev){var u=n.call(i,"catchLoc"),c=n.call(i,"finallyLoc");if(u&&c){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),S(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;S(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:x(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}));var o=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.defer=function(){var e=void 0,r=void 0,t=new Promise((function(t,n){e=t,r=n}));if(!e||!r)throw"defer() error";return{promise:t,resolve:e,reject:r}},r.splitPath=function(e){var r=[];return e.split("/").forEach((function(e){var t=parseInt(e,10);isNaN(t)||(e.length>1&&"'"===e[e.length-1]&&(t+=2147483648),r.push(t))})),r},r.eachSeries=function(e,r){return e.reduce((function(e,t){return e.then((function(){return r(t)}))}),Promise.resolve())},r.foreach=function(e,r){function t(e,n,o){return e>=n.length?o:r(n[e],e).then((function(r){return o.push(r),t(e+1,n,o)}))}return Promise.resolve().then((function(){return t(0,e,[])}))},r.doIf=function(e,r){return Promise.resolve().then((function(){if(e)return r()}))},r.asyncWhile=function(e,r){return Promise.resolve([]).then((function t(n){return e()?r().then((function(e){return n.push(e),t(n)})):n}))};r.isLedgerDevice=function(e){return 9601===e.vendorId&&15228===e.productId||11415===e.vendorId}}));t(o);o.defer,o.splitPath,o.eachSeries,o.foreach,o.doIf,o.asyncWhile,o.isLedgerDevice;var a,i={}.createHash,s=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t,n=Object.assign||function(e){for(var r=1;r1&&void 0!==arguments[1]?arguments[1]:"BTC";u(this,e),this.transport=r,r.decorateAppAPIMethods(this,["getWalletPublicKey","signP2SHTransaction","signMessageNew","createPaymentTransactionNew"],t)}var r,t;return a(e,[{key:"hashPublicKey",value:function(e){return(0,s.default)("rmd160").update((0,s.default)("sha256").update(e).digest()).digest()}},{key:"getWalletPublicKey_private",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=n({verify:!1,format:"legacy"},r),a=t.verify,i=t.format;if(!(i in c))throw new Error("btc.getWalletPublicKey invalid format="+i);var s=(0,o.splitPath)(e),u=a?1:0,l=c[i],f=Buffer.alloc(1+4*s.length);return f[0]=s.length,s.forEach((function(e,r){f.writeUInt32BE(e,1+4*r)})),this.transport.send(224,64,u,l,f).then((function(e){var r=e[0],t=e[1+r];return{publicKey:e.slice(1,1+r).toString("hex"),bitcoinAddress:e.slice(1+r+1,1+r+1+t).toString("ascii"),chainCode:e.slice(1+r+1+t,1+r+1+t+32).toString("hex")}}))}},{key:"getWalletPublicKey",value:function(e,r){var t=void 0;return arguments.length>2||"boolean"==typeof r?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),t={verify:!!r,format:arguments[2]?"p2sh":"legacy"}):t=r||{},this.getWalletPublicKey_private(e,t)}},{key:"getTrustedInputRaw",value:function(e,r){var t=void 0,n=!1;if("number"==typeof r){n=!0;var o=Buffer.alloc(4);o.writeUInt32BE(r,0),t=Buffer.concat([o,e],e.length+4)}else t=e;return this.transport.send(224,66,n?0:128,0,t).then((function(e){return e.slice(0,e.length-2).toString("hex")}))}},{key:"getTrustedInput",value:function(e,r){var t=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],a=r.version,i=r.inputs,s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");var c=n.includes("decred"),f=n.includes("stealthcoin"),d=function(e,r){for(var n=[],a=0;a!==e.length;){var i=e.length-a>l?l:e.length-a;a+i!==e.length?n.push(e.slice(a,a+i)):n.push(Buffer.concat([e.slice(a,a+i),r])),a+=i}return 0===e.length&&n.push(r),(0,o.eachSeries)(n,(function(e){return t.getTrustedInputRaw(e)}))},p=function(e){return t.getTrustedInputRaw(e)},h=function(){return(0,o.eachSeries)(i,(function(e){var r=f&&0===Buffer.compare(a,Buffer.from([2,0,0,0])),n=c?e.tree||Buffer.from([0]):Buffer.alloc(0),o=Buffer.concat([e.prevout,n,r?Buffer.from([0]):t.createVarint(e.script.length)]);return t.getTrustedInputRaw(o).then((function(){return c?p(Buffer.concat([e.script,e.sequence])):r?p(e.sequence):d(e.script,e.sequence)}))})).then((function(){var e=t.createVarint(s.length);return t.getTrustedInputRaw(e)}))},v=function(){return(0,o.eachSeries)(s,(function(e){var r=e.amount;return r=Buffer.concat([r,c?Buffer.from([0,0]):Buffer.alloc(0),t.createVarint(e.script.length),e.script]),t.getTrustedInputRaw(r).then((function(){}))})).then((function(){var e=c?Buffer.concat([u,Buffer.from([0,0,0,0])]):u;return t.getTrustedInputRaw(e)}))},g=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),this.createVarint(i.length)]);return this.getTrustedInputRaw(g,e).then(h).then(v)}},{key:"getTrustedInputBIP143",value:(r=regeneratorRuntime.mark((function e(r,t){var n,o,a,i,u,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}throw new Error("getTrustedInputBIP143: missing tx");case 2:if(!c.includes("decred")){e.next=5;break}throw new Error("Decred does not implement BIP143");case 5:if((n=(0,s.default)("sha256")).update(this.serializeTransaction(t,!0)),o=n.digest(),(n=(0,s.default)("sha256")).update(o),o=n.digest(),(a=Buffer.alloc(4)).writeUInt32LE(r,0),i=t.outputs,u=t.locktime,i&&u){e.next=16;break}throw new Error("getTrustedInputBIP143: locktime & outputs is expected");case 16:if(i[r]){e.next=18;break}throw new Error("getTrustedInputBIP143: wrong index");case 18:return o=Buffer.concat([o,a,i[r].amount]),e.next=21,o.toString("hex");case 21:return e.abrupt("return",e.sent);case 22:case"end":return e.stop()}}),e,this)})),t=function(){var e=r.apply(this,arguments);return new Promise((function(r,t){return function n(o,a){try{var i=e[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then((function(e){n("next",e)}),(function(e){n("throw",e)}));r(s)}("next")}))},function(e,r){return t.apply(this,arguments)})},{key:"getVarint",value:function(e,r){if(e[r]<253)return[e[r],1];if(253===e[r])return[(e[r+2]<<8)+e[r+1],3];if(254===e[r])return[(e[r+4]<<24)+(e[r+3]<<16)+(e[r+2]<<8)+e[r+1],5];throw new Error("getVarint called with unexpected parameters")}},{key:"startUntrustedHashTransactionInputRaw",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],i=n?a.includes("sapling")?5:o?4:2:0;return this.transport.send(224,68,r?0:128,e?i:128,t)}},{key:"startUntrustedHashTransactionInput",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=this,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],u=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),this.createVarint(r.inputs.length)]);return this.startUntrustedHashTransactionInputRaw(e,!0,u,n,i,s).then((function(){var c=0,f=s.includes("decred");return(0,o.eachSeries)(r.inputs,(function(r){var d=void 0;return d=n?Buffer.from([2]):t[c].trustedInput?Buffer.from([1,t[c].value.length]):Buffer.from([0]),u=Buffer.concat([d,t[c].value,f?Buffer.from([0]):Buffer.alloc(0),a.createVarint(r.script.length)]),a.startUntrustedHashTransactionInputRaw(e,!1,u,n,i,s).then((function(){var t=[],u=0;if(0===r.script.length)t.push(r.sequence);else for(;u!==r.script.length;){var f=r.script.length-u>l?l:r.script.length-u;u+f!==r.script.length?t.push(r.script.slice(u,u+f)):t.push(Buffer.concat([r.script.slice(u,u+f),r.sequence])),u+=f}return(0,o.eachSeries)(t,(function(r){return a.startUntrustedHashTransactionInputRaw(e,!1,r,n,i,s)})).then((function(){c++}))}))}))}))}},{key:"provideOutputFullChangePath",value:function(e){var r=(0,o.splitPath)(e),t=Buffer.alloc(1+4*r.length);return t[0]=r.length,r.forEach((function(e,r){t.writeUInt32BE(e,1+4*r)})),this.transport.send(224,74,255,0,t)}},{key:"hashOutputFull",value:function(e){var r=this,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=0,a=128,i=t.includes("decred");return i?this.transport.send(224,74,a,0,e):(0,o.asyncWhile)((function(){return n=e.length?e.length-n:l,o=n+t===e.length?128:0,a=e.slice(n,n+t);return r.transport.send(224,74,o,0,a).then((function(){n+=t}))}))}},{key:"signTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments[3],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],i=a.includes("decred"),s=(0,o.splitPath)(e),u=0,c=Buffer.alloc(4*s.length);s.forEach((function(e){c.writeUInt32BE(e,u),u+=4}));var l=Buffer.alloc(4);l.writeUInt32BE(r,0);var f=i?Buffer.concat([Buffer.from([s.length]),c,l,n||Buffer.from([0,0,0,0]),Buffer.from([t])]):Buffer.concat([Buffer.from([s.length]),c,Buffer.from([0]),l,Buffer.from([t])]);return n&&!i&&(f=Buffer.concat([f,n])),this.transport.send(224,72,0,0,f).then((function(e){return e.length>0?(e[0]=48,e.slice(0,e.length-2)):e}))}},{key:"signMessageNew",value:function(e,r){for(var t=this,n=(0,o.splitPath)(e),a=new Buffer(r,"hex"),i=0,s=[],u=function(){var e=0===i?49-4*n.length-4:l,r=i+e>a.length?a.length-i:e,t=new Buffer(0===i?1+4*n.length+2+r:r);0===i?(t[0]=n.length,n.forEach((function(e,r){t.writeUInt32BE(e,1+4*r)})),t.writeUInt16BE(a.length,1+4*n.length),a.copy(t,1+4*n.length+2,i,i+r)):a.copy(t,0,i,i+r),s.push(t),i+=r};i!==a.length;)u();return(0,o.foreach)(s,(function(e,r){return t.transport.send(224,78,0,0===r?1:128,e)})).then((function(){return t.transport.send(224,78,128,0,Buffer.from([0])).then((function(e){var r=e[0]-48,t=e.slice(4,4+e[3]);0===t[0]&&(t=t.slice(1)),t=t.toString("hex");var n=4+e[3]+2,o=e.slice(n,n+e[n-1]);return 0===o[0]&&(o=o.slice(1)),{v:r,r:t,s:o=o.toString("hex")}}))}))}},{key:"createPaymentTransactionNew",value:function(e,r,t,a){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1,u=arguments.length>6&&void 0!==arguments[6]&&arguments[6],c=arguments[7],l=this,d=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],p=arguments[9],h=d.includes("decred"),v=d.includes("stealthcoin"),g=void 0!==c,m=Date.now(),E=d.includes("sapling"),y=u&&d.includes("bech32"),C=u||!!d&&(d.includes("abc")||d.includes("gold")||d.includes("bip143"))||!!p&&!h,w=Buffer.alloc(0),I=Buffer.alloc(0),b=Buffer.alloc(4);p&&!h?b.writeUInt32LE(E?2147483652:2147483651,0):v?b.writeUInt32LE(2,0):b.writeUInt32LE(1,0);var B=[],D=[],T=[],S=[],A=!0,x=!1,N={inputs:[],version:b,timestamp:Buffer.alloc(0)},U=C?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),L=Buffer.from(a,"hex");return(0,o.foreach)(e,(function(e){return(0,o.doIf)(!x,(function(){return U(e[1],e[0],d).then((function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:f,0),B.push({trustedInput:!0,value:Buffer.from(r,"hex"),sequence:t})}))})).then((function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&D.push(r[t])})).then((function(){p&&!h?(N.nVersionGroupId=Buffer.from(E?[133,32,47,137]:[112,130,196,3]),N.nExpiryHeight=p,N.extraData=Buffer.from(E?[0,0,0,0,0,0,0,0,0,0,0]:[0])):h&&(N.nExpiryHeight=p)}))})).then((function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:f,0),N.inputs.push({script:w,prevout:I,sequence:t})}})).then((function(){return(0,o.doIf)(!x,(function(){return(0,o.foreach)(e,(function(e,t){return l.getWalletPublicKey_private(r[t])})).then((function(e){for(var r=0;r=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):u?Buffer.concat([Buffer.from([118,169,20]),l.hashPublicKey(S[c]),Buffer.from([136,172])]):D[c].script,v=Object.assign({},N),g=C?[B[c]]:B;return C?v.inputs=[n({},v.inputs[c],{script:f})]:v.inputs[c].script=f,l.startUntrustedHashTransactionInput(!C&&A,v,g,C,!!p&&!h,d).then((function(){return(0,o.doIf)(!C,(function(){return(0,o.doIf)(void 0!==t,(function(){return l.provideOutputFullChangePath(t)})).then((function(){return l.hashOutputFull(L,d)}))}))})).then((function(){return l.signTransaction(r[c],i,s,p,d)})).then((function(e){T.push(e),N.inputs[c].script=w,A&&(A=!1)}))}))})).then((function(){for(var r=0;r3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,s=this,u=arguments.length>5&&void 0!==arguments[5]&&arguments[5],c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1,l=Buffer.alloc(0),d=Buffer.alloc(0),p=Buffer.alloc(4);p.writeUInt32LE(c,0);var h=[],v=[],g=[],m=!0,E=!1,y={inputs:[],version:p},C=u?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),w=Buffer.from(t,"hex");return(0,o.foreach)(e,(function(e){return(0,o.doIf)(!E,(function(){return C(e[1],e[0]).then((function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:f,0),h.push({trustedInput:!1,value:u?Buffer.from(r,"hex"):Buffer.from(r,"hex").slice(4,40),sequence:t})}))})).then((function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&v.push(r[t])}))})).then((function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:f,0),y.inputs.push({script:l,prevout:d,sequence:t})}})).then((function(){return(0,o.doIf)(u,(function(){return s.startUntrustedHashTransactionInput(!0,y,h,!0).then((function(){return s.hashOutputFull(w)}))}))})).then((function(){return(0,o.foreach)(e,(function(t,c){var f=e[c].length>=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):v[c].script,d=Object.assign({},y),p=u?[h[c]]:h;return u?d.inputs=[n({},d.inputs[c],{script:f})]:d.inputs[c].script=f,s.startUntrustedHashTransactionInput(!u&&m,d,p,u).then((function(){return(0,o.doIf)(!u,(function(){return s.hashOutputFull(w)}))})).then((function(){return s.signTransaction(r[c],a,i).then((function(e){g.push(u?e.toString("hex"):e.slice(0,e.length-1).toString("hex")),y.inputs[c].script=l,m&&(m=!1)}))}))}))})).then((function(){return g}))}},{key:"compressPublicKey",value:function(e){var r=0!=(1&e[64])?3:2,t=Buffer.alloc(1);return t[0]=r,Buffer.concat([t,e.slice(1,33)])}},{key:"createVarint",value:function(e){if(e<253){var r=Buffer.alloc(1);return r[0]=e,r}if(e<=65535){var t=Buffer.alloc(3);return t[0]=253,t[1]=255&e,t[2]=e>>8&255,t}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&e,n[2]=e>>8&255,n[3]=e>>16&255,n[4]=e>>24&255,n}},{key:"splitTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],a=[],i=[],s=!1,u=0,c=Buffer.alloc(0),l=Buffer.alloc(0),f=Buffer.alloc(0),d=Buffer.alloc(0),p=o.includes("decred"),h=Buffer.from(e,"hex"),v=h.slice(u,u+4),g=v.equals(Buffer.from([3,0,0,128]))||v.equals(Buffer.from([4,0,0,128]));u+=4,!t&&r&&0===h[u]&&0!==h[u+1]&&(u+=2,s=!0),t&&(c=h.slice(u,4+u),u+=4),g&&(f=h.slice(u,4+u),u+=4);var m=this.getVarint(h,u),E=m[0];u+=m[1];for(var y=0;y3&&void 0!==arguments[3]?arguments[3]:[],a=o.includes("decred"),i=o.includes("bech32"),s=Buffer.alloc(0),u=void 0!==e.witness&&!r;e.inputs.forEach((function(e){s=a||i?Buffer.concat([s,e.prevout,Buffer.from([0]),e.sequence]):Buffer.concat([s,e.prevout,n.createVarint(e.script.length),e.script,e.sequence])}));var c=this.serializeTransactionOutputs(e);return void 0!==e.outputs&&void 0!==e.locktime&&(c=Buffer.concat([c,u&&e.witness||Buffer.alloc(0),e.locktime,e.nExpiryHeight||Buffer.alloc(0),e.extraData||Buffer.alloc(0)])),Buffer.concat([e.version,t||Buffer.alloc(0),e.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),this.createVarint(e.inputs.length),s,c])}},{key:"displayTransactionDebug",value:function(e){console.log("version "+e.version.toString("hex")),e.inputs.forEach((function(e,r){var t=e.prevout.toString("hex"),n=e.script.toString("hex"),o=e.sequence.toString("hex");console.log("input "+r+" prevout "+t+" script "+n+" sequence "+o)})),(e.outputs||[]).forEach((function(e,r){var t=e.amount.toString("hex"),n=e.script.toString("hex");console.log("output "+r+" amount "+t+" script "+n)})),void 0!==e.locktime&&console.log("locktime "+e.locktime.toString("hex"))}}]),e}();r.default=d})),u=t(s),c=Object.freeze({default:u,__moduleExports:s});function l(){}function f(){f.init.call(this)}function d(e){return void 0===e._maxListeners?f.defaultMaxListeners:e._maxListeners}function p(e,r,t){if(r)e.call(t);else for(var n=e.length,o=w(e,n),a=0;a0&&i.length>o){i.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=r,u.count=i.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else i=a[r]=t,++e._eventsCount;return e}function y(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function C(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function w(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}l.prototype=Object.create(null),f.EventEmitter=f,f.usingDomains=!1,f.prototype.domain=void 0,f.prototype._events=void 0,f.prototype._maxListeners=void 0,f.defaultMaxListeners=10,f.init=function(){this.domain=null,f.usingDomains&&a.active&&a.Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new l,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},f.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},f.prototype.getMaxListeners=function(){return d(this)},f.prototype.emit=function(e){var r,t,n,o,a,i,s,u="error"===e;if(i=this._events)u=u&&null==i.error;else if(!u)return!1;if(s=this.domain,u){if(r=arguments[1],!s){if(r instanceof Error)throw r;var c=new Error('Uncaught, unspecified "error" event. ('+r+")");throw c.context=r,c}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=s,r.domainThrown=!1,s.emit("error",r),!1}if(!(t=i[e]))return!1;var l="function"==typeof t;switch(n=arguments.length){case 1:p(t,l,this);break;case 2:h(t,l,this,arguments[1]);break;case 3:v(t,l,this,arguments[1],arguments[2]);break;case 4:g(t,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),a=1;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new l,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var I=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var i=JSON.parse(r.message);i.message&&i.name&&(r=i)}catch(e){}var s=void 0;if("string"==typeof r.name){var u=r.name,c=o[u];if(c)s=c(r);else{var l="Error"===u?Error:n[u];l||(console.warn("deserializing an unknown class '"+u+"'"),l=a(u)),s=Object.create(l.prototype);try{for(var f in r)r.hasOwnProperty(f)&&(s[f]=r[f])}catch(e){}}}else s=new Error(r.message);return!s.stack&&Error.captureStackTrace&&Error.captureStackTrace(s,e),s}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?i(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e};function i(e,r){var n={};r.push(e);var o=!0,a=!1,s=void 0;try{for(var u,c=Object.keys(e)[Symbol.iterator]();!(o=(u=c.next()).done);o=!0){var l=u.value,f=e[l];"function"!=typeof f&&(f&&"object"===(void 0===f?"undefined":t(f))?-1!==r.indexOf(e[l])?n[l]="[Circular]":n[l]=i(e[l],r.slice(0)):n[l]=f)}}catch(e){a=!0,s=e}finally{try{!o&&c.return&&c.return()}finally{if(a)throw s}}return"string"==typeof e.name&&(n.name=e.name),"string"==typeof e.message&&(n.message=e.message),"string"==typeof e.stack&&(n.stack=e.stack),n}}));t(I);I.addCustomErrorDeserializer,I.createCustomErrorClass,I.deserializeError,I.serializeError;var b=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=I.serializeError,r.deserializeError=I.deserializeError,r.createCustomErrorClass=I.createCustomErrorClass,r.addCustomErrorDeserializer=I.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,I.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,I.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,I.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,I.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,I.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,I.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,I.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,I.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,I.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,I.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,I.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,I.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,I.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,I.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,I.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,I.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,I.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,I.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,I.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,I.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,I.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,I.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,I.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,I.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,I.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,I.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,I.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,I.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,I.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,I.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,I.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,I.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,I.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,I.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,I.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,I.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,I.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,I.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,I.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,I.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,I.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,I.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,I.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,I.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,I.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,I.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,I.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,I.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,I.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,I.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,I.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,I.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,I.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,I.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,I.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,I.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,I.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,I.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,I.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,I.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,I.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,I.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,I.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,I.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,I.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,I.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,I.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,I.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,I.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,I.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,I.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,I.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,I.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,I.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,I.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,I.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,I.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,I.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,I.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,I.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,I.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,I.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,I.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,I.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,I.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,I.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,I.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,I.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,I.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,I.addCustomErrorDeserializer)("TransportError",(function(e){return new t(e.message,e.id)}));var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find((function(r){return n[r]===e}))||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,I.addCustomErrorDeserializer)("TransportStatusError",(function(e){return new a(e.statusCode)}))}));t(b);b.StatusCodes,b.DBNotReset,b.DBWrongPassword,b.NoDBPathGiven,b.FirmwareOrAppUpdateRequired,b.LedgerAPI5xx,b.LedgerAPI4xx,b.GenuineCheckFailed,b.PairingFailed,b.SyncError,b.FeeTooHigh,b.FeeRequired,b.FeeNotLoaded,b.CantScanQRCode,b.ETHAddressNonEIP,b.WrongAppForCurrency,b.WrongDeviceForAccount,b.WebsocketConnectionFailed,b.WebsocketConnectionError,b.DeviceShouldStayInApp,b.TransportWebUSBGestureRequired,b.TransportInterfaceNotAvailable,b.TransportOpenUserCancelled,b.UserRefusedOnDevice,b.UserRefusedAllowManager,b.UserRefusedFirmwareUpdate,b.UserRefusedAddress,b.UserRefusedDeviceNameChange,b.UpdateYourApp,b.UnavailableTezosOriginatedAccountSend,b.UnavailableTezosOriginatedAccountReceive,b.RecipientRequired,b.MCUNotGenuineToDashboard,b.UnexpectedBootloader,b.TimeoutTagged,b.RecommendUndelegation,b.RecommendSubAccountsToEmpty,b.PasswordIncorrectError,b.PasswordsDontMatchError,b.GasLessThanEstimate,b.NotSupportedLegacyAddress,b.NotEnoughGas,b.NoAccessToCamera,b.NotEnoughBalanceBecauseDestinationNotCreated,b.NotEnoughSpendableBalance,b.NotEnoughBalanceInParentAccount,b.NotEnoughBalanceToDelegate,b.NotEnoughBalance,b.NoAddressesFound,b.NetworkDown,b.ManagerUninstallBTCDep,b.ManagerNotEnoughSpaceError,b.ManagerFirmwareNotEnoughSpaceError,b.ManagerDeviceLockedError,b.ManagerAppDepUninstallRequired,b.ManagerAppDepInstallRequired,b.ManagerAppRelyOnBTCError,b.ManagerAppAlreadyInstalledError,b.LedgerAPINotAvailable,b.LedgerAPIErrorWithMessage,b.LedgerAPIError,b.UnknownMCU,b.LatestMCUInstalledError,b.InvalidAddressBecauseDestinationIsAlsoSource,b.InvalidAddress,b.InvalidXRPTag,b.HardResetFail,b.FeeEstimationFailed,b.EthAppPleaseEnableContractData,b.EnpointConfigError,b.DisconnectedDeviceDuringOperation,b.DisconnectedDevice,b.DeviceSocketNoBulkStatus,b.DeviceSocketFail,b.DeviceNameInvalid,b.DeviceHalted,b.DeviceInOSUExpected,b.DeviceOnDashboardUnexpected,b.DeviceOnDashboardExpected,b.DeviceNotGenuineError,b.DeviceGenuineSocketEarlyClose,b.DeviceAppVerifyNotSupported,b.CurrencyNotSupported,b.CashAddrNotSupported,b.CantOpenDevice,b.BtcUnmatchedApp,b.BluetoothRequired,b.AmountRequired,b.AccountNotSupported,b.AccountNameRequiredError,b.addCustomErrorDeserializer,b.createCustomErrorClass,b.deserializeError,b.serializeError,b.TransportError,b.getAltStatusMessage,b.TransportStatusError;var B=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[b.StatusCodes.OK];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(u.length>=256)){e.next=2;break}throw new b.TransportError("data.length exceed 256 bytes limit. Got: "+u.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([u.length]),u]));case 4:if(i=e.sent,s=i.readUInt16BE(i.length-2),c.some((function(e){return e===s}))){e.next=8;break}throw new b.TransportStatusError(s);case 8:return e.abrupt("return",i);case 9:case"end":return e.stop()}}),e,n)}))),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=i(regeneratorRuntime.mark((function e(r){var t,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new b.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise((function(e){t=e})),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}}),e,n,[[5,,10,14]])}))),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise((function(n,o){var a=!1,i=e.listen({next:function(t){a=!0,i&&i.unsubscribe(),s&&clearTimeout(s),e.open(t.descriptor,r).then(n,o)},error:function(e){s&&clearTimeout(s),o(e)},complete:function(){s&&clearTimeout(s),a||o(new b.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),s=t?setTimeout((function(){i.unsubscribe(),o(new b.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))}),t):null}))}}]),e}();s.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",s.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=s}));t(B);B.getAltStatusMessage,B.StatusCodes,B.TransportStatusError,B.TransportError;var D=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),i=r-5,s=Math.ceil(a.length/i);a=Buffer.concat([a,Buffer.alloc(s*i-a.length+1).fill(0)]);for(var u=[],c=0;ci&&(a=a.slice(0,i)),{data:a,dataLength:i,sequence:s}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}}));t(D);var T=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find((function(e){return e.productIdMM===t}))},r.identifyProductName=function(e){var r=o[e];return a.find((function(e){return e.id===r}))},[]),s={};for(var u in n){var c=n[u],l=c.bluetoothSpec;if(l)for(var f=0;f0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)});function s(e){return function(){var r=e.apply(this,arguments);return new Promise((function(e,t){return function n(o,a){try{var i=r[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then((function(e){n("next",e)}),(function(e){n("throw",e)}));e(s)}("next")}))}}var u=[{vendorId:T.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}}));t(A);A.isSupported,A.getFirstLedgerDevice,A.getLedgerDevices,A.requestLedgerDevice;var x=n((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),i=(0,o.default)(n,a),s=i.makeBlocks(r),u=0;case 5:if(!(u "+s[u].toString("hex")),t.next=9,e.device.transferOut(3,s[u]);case 9:u++,t.next=5;break;case 12:c=void 0,l=void 0;case 14:if(c=i.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:f=t.sent,d=Buffer.from(f.data.buffer),(0,S.log)("hid-frame","<= "+d.toString("hex")),l=i.reduceResponse(l,d),t.next=14;break;case 23:return(0,S.log)("apdu","<= "+c.toString("hex")),t.abrupt("return",c);case 25:case"end":return t.stop()}}),t,e)})))).catch((function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new b.DisconnectedDeviceDuringOperation(r.message);throw r}))}};r.default=s})),N=t(x),U=Object.freeze({default:N,__moduleExports:x});e.Btc=c,e.TransportWebUSB=U,Object.defineProperty(e,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; -window.TransportWebUSB = NewLedger.TransportWebUSB.default; -window.TransportU2F = NewLedger.TransportU2F.default; -window.Log = NewLedger.Log.default; -window.createHash = NewLedger.createHash.default; +window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 774b840e58fc4cbf04737ef49507829bbee33496 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 18:45:41 +1100 Subject: [PATCH 02/78] new ledger.js --- js/ledger.js | 12088 +------------------------------------------------ 1 file changed, 2 insertions(+), 12086 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index a33a2f0a..c4cd5781 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,12091 +2,7 @@ window.global = window; window.Buffer = buffer.Buffer; -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.NewLedger = {}))); -}(this, (function (exports) { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var runtime_1 = createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - - }( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports - )); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); - } - }); - - var utils = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.defer = defer; - exports.splitPath = splitPath; - exports.eachSeries = eachSeries; - exports.foreach = foreach; - exports.doIf = doIf; - exports.asyncWhile = asyncWhile; - function defer() { - var resolve = void 0, - reject = void 0; - var promise = new Promise(function (success, failure) { - resolve = success; - reject = failure; - }); - if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy - return { promise: promise, resolve: resolve, reject: reject }; - } - - // TODO use bip32-path library - /******************************************************************************** - * Ledger Node JS API - * (c) 2016-2017 Ledger - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ********************************************************************************/ - - - function splitPath(path) { - var result = []; - var components = path.split("/"); - components.forEach(function (element) { - var number = parseInt(element, 10); - if (isNaN(number)) { - return; // FIXME shouldn't it throws instead? - } - if (element.length > 1 && element[element.length - 1] === "'") { - number += 0x80000000; - } - result.push(number); - }); - return result; - } - - // TODO use async await - - function eachSeries(arr, fun) { - return arr.reduce(function (p, e) { - return p.then(function () { - return fun(e); - }); - }, Promise.resolve()); - } - - function foreach(arr, callback) { - function iterate(index, array, result) { - if (index >= array.length) { - return result; - } else return callback(array[index], index).then(function (res) { - result.push(res); - return iterate(index + 1, array, result); - }); - } - return Promise.resolve().then(function () { - return iterate(0, arr, []); - }); - } - - function doIf(condition, callback) { - return Promise.resolve().then(function () { - if (condition) { - return callback(); - } - }); - } - - function asyncWhile(predicate, callback) { - function iterate(result) { - if (!predicate()) { - return result; - } else { - return callback().then(function (res) { - result.push(res); - return iterate(result); - }); - } - } - return Promise.resolve([]).then(iterate); - } - - var isLedgerDevice = exports.isLedgerDevice = function isLedgerDevice(device) { - return device.vendorId === 0x2581 && device.productId === 0x3b7c || device.vendorId === 0x2c97; - }; - - }); - - unwrapExports(utils); - var utils_1 = utils.defer; - var utils_2 = utils.splitPath; - var utils_3 = utils.eachSeries; - var utils_4 = utils.foreach; - var utils_5 = utils.doIf; - var utils_6 = utils.asyncWhile; - var utils_7 = utils.isLedgerDevice; - - var require$$0 = {}; - - var createHash = require$$0.createHash; - - var Btc_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - // TODO future refactoring - // - drop utils.js & refactoring with async/await style - // - try to avoid every place we do hex<>Buffer conversion. also accept Buffer as func parameters (could accept both a string or a Buffer in the API) - // - there are redundant code across apps (see Eth vs Btc). we might want to factorize it somewhere. also each app apdu call should be abstracted it out as an api - - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - /** - * address format is one of legacy | p2sh | bech32 - */ - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2 - }; - - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - - var Btc = function () { - function Btc(transport) { - var scrambleKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "BTC"; - - _classCallCheck(this, Btc); - - this.transport = transport; - transport.decorateAppAPIMethods(this, ["getWalletPublicKey", "signP2SHTransaction", "signMessageNew", "createPaymentTransactionNew"], scrambleKey); - } - - _createClass(Btc, [{ - key: "hashPublicKey", - value: function hashPublicKey(buffer) { - return window.createHash("rmd160").update(window.createHash("sha256").update(buffer).digest()).digest(); - } - }, { - key: "getWalletPublicKey_private", - value: function getWalletPublicKey_private(path) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var _verify$format$option = _extends({ - verify: false, - format: "legacy" - }, options), - verify = _verify$format$option.verify, - format = _verify$format$option.format; - - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - var paths = (0, utils.splitPath)(path); - var p1 = verify ? 1 : 0; - var p2 = addressFormatMap[format]; - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x40, p1, p2, buffer).then(function (response) { - var publicKeyLength = response[0]; - var addressLength = response[1 + publicKeyLength]; - var publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - var bitcoinAddress = response.slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength).toString("ascii"); - var chainCode = response.slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32).toString("hex"); - return { publicKey: publicKey, bitcoinAddress: bitcoinAddress, chainCode: chainCode }; - }); - } - - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - - }, { - key: "getWalletPublicKey", - value: function getWalletPublicKey(path, opts) { - var options = void 0; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - format: arguments[2] ? "p2sh" : "legacy" - }; - } else { - options = opts || {}; - } - return this.getWalletPublicKey_private(path, options); - } - }, { - key: "getTrustedInputRaw", - value: function getTrustedInputRaw(transactionData, indexLookup) { - var data = void 0; - var firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - var prefix = Buffer.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer.concat([prefix, transactionData], transactionData.length + 4); - } else { - data = transactionData; - } - return this.transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data).then(function (trustedInput) { - return trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - }); - } - }, { - key: "getTrustedInput", - value: function getTrustedInput(indexLookup, transaction) { - var _this = this; - - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var inputs = transaction.inputs, - outputs = transaction.outputs, - locktime = transaction.locktime; - - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var processScriptBlocks = function processScriptBlocks(script, sequence) { - var scriptBlocks = []; - var offset = 0; - while (offset !== script.length) { - var blockSize = script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), sequence])); - } - offset += blockSize; - } - - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(sequence); - } - - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this.getTrustedInputRaw(scriptBlock); - }); - }; - - var processWholeScriptBlock = function processWholeScriptBlock(block) { - return _this.getTrustedInputRaw(block); - }; - - var processInputs = function processInputs() { - return (0, utils.eachSeries)(inputs, function (input) { - var treeField = isDecred ? input.tree || Buffer.from([0x00]) : Buffer.alloc(0); - var data = Buffer.concat([input.prevout, treeField, isXST ? Buffer.from([0x00]) : _this.createVarint(input.script.length)]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return isDecred ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) : isXST ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence); - }); - }).then(function () { - var data = _this.createVarint(outputs.length); - return _this.getTrustedInputRaw(data); - }); - }; - - var processOutputs = function processOutputs() { - return (0, utils.eachSeries)(outputs, function (output) { - var data = output.amount; - data = Buffer.concat([data, isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), //Version script - _this.createVarint(output.script.length), output.script]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("output"); - }); - }).then(function () { - //Add expiry height for decred - var finalData = isDecred ? Buffer.concat([locktime, Buffer.from([0x00, 0x00, 0x00, 0x00])]) : locktime; - return _this.getTrustedInputRaw(finalData); - }); - }; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), this.createVarint(inputs.length)]); - return this.getTrustedInputRaw(data, indexLookup).then(processInputs).then(processOutputs); - } - }, { - key: "getTrustedInputBIP143", - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(indexLookup, transaction) { - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var isDecred, sha, hash, data, outputs, locktime; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (transaction) { - _context.next = 2; - break; - } - - throw new Error("getTrustedInputBIP143: missing tx"); - - case 2: - isDecred = additionals.includes("decred"); - - if (!isDecred) { - _context.next = 5; - break; - } - - throw new Error("Decred does not implement BIP143"); - - case 5: - sha = window.createHash("sha256"); - - sha.update(this.serializeTransaction(transaction, true)); - hash = sha.digest(); - - sha = window.createHash("sha256"); - sha.update(hash); - hash = sha.digest(); - data = Buffer.alloc(4); - - data.writeUInt32LE(indexLookup, 0); - outputs = transaction.outputs, locktime = transaction.locktime; - - if (!(!outputs || !locktime)) { - _context.next = 16; - break; - } - - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - - case 16: - if (outputs[indexLookup]) { - _context.next = 18; - break; - } - - throw new Error("getTrustedInputBIP143: wrong index"); - - case 18: - hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); - _context.next = 21; - return hash.toString("hex"); - - case 21: - return _context.abrupt("return", _context.sent); - - case 22: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function getTrustedInputBIP143(_x4, _x5) { - return _ref.apply(this, arguments); - } - - return getTrustedInputBIP143; - }() - }, { - key: "getVarint", - value: function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [(data[offset + 4] << 24) + (data[offset + 3] << 16) + (data[offset + 2] << 8) + data[offset + 1], 5]; - } - - throw new Error("getVarint called with unexpected parameters"); - } - }, { - key: "startUntrustedHashTransactionInputRaw", - value: function startUntrustedHashTransactionInputRaw(newTransaction, firstRound, transactionData) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var p2 = bip143 ? additionals.includes("sapling") ? 0x05 : overwinter ? 0x04 : 0x02 : 0x00; - return this.transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - }, { - key: "startUntrustedHashTransactionInput", - value: function startUntrustedHashTransactionInput(newTransaction, transaction, inputs) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - - var _this2 = this; - - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), this.createVarint(transaction.inputs.length)]); - return this.startUntrustedHashTransactionInputRaw(newTransaction, true, data, bip143, overwinter, additionals).then(function () { - var i = 0; - var isDecred = additionals.includes("decred"); - return (0, utils.eachSeries)(transaction.inputs, function (input) { - var prefix = void 0; - if (bip143) { - prefix = Buffer.from([0x02]); - } else { - if (inputs[i].trustedInput) { - prefix = Buffer.from([0x01, inputs[i].value.length]); - } else { - prefix = Buffer.from([0x00]); - } - } - data = Buffer.concat([prefix, inputs[i].value, isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), _this2.createVarint(input.script.length)]); - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, data, bip143, overwinter, additionals).then(function () { - var scriptBlocks = []; - var offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } else { - while (offset !== input.script.length) { - var blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([input.script.slice(offset, offset + blockSize), input.sequence])); - } - offset += blockSize; - } - } - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, scriptBlock, bip143, overwinter, additionals); - }).then(function () { - i++; - }); - }); - }); - }); - } - }, { - key: "provideOutputFullChangePath", - value: function provideOutputFullChangePath(path) { - var paths = (0, utils.splitPath)(path); - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - }, { - key: "hashOutputFull", - value: function hashOutputFull(outputScript) { - var _this3 = this; - - var additionals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - var offset = 0; - var p1 = 0x80; - var isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return this.transport.send(0xe0, 0x4a, p1, 0x00, outputScript); - } - return (0, utils.asyncWhile)(function () { - return offset < outputScript.length; - }, function () { - var blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length ? outputScript.length - offset : MAX_SCRIPT_BLOCK; - var p1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - var data = outputScript.slice(offset, offset + blockSize); - - return _this3.transport.send(0xe0, 0x4a, p1, 0x00, data).then(function () { - offset += blockSize; - }); - }); - } - }, { - key: "signTransaction", - value: function signTransaction(path) { - var lockTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SIGHASH_ALL; - var expiryHeight = arguments[3]; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var isDecred = additionals.includes("decred"); - var paths = (0, utils.splitPath)(path); - var offset = 0; - var pathsBuffer = Buffer.alloc(paths.length * 4); - paths.forEach(function (element) { - pathsBuffer.writeUInt32BE(element, offset); - offset += 4; - }); - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred ? Buffer.concat([Buffer.from([paths.length]), pathsBuffer, lockTimeBuffer, expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), Buffer.from([sigHashType])]) : Buffer.concat([Buffer.from([paths.length]), pathsBuffer, Buffer.from([0x00]), lockTimeBuffer, Buffer.from([sigHashType])]); - if (expiryHeight && !isDecred) { - buffer = Buffer.concat([buffer, expiryHeight]); - } - return this.transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - - }, { - key: "signMessageNew", - value: function signMessageNew(path, messageHex) { - var _this4 = this; - - var paths = (0, utils.splitPath)(path); - var message = new Buffer(messageHex, "hex"); - var offset = 0; - var toSend = []; - - var _loop = function _loop() { - var maxChunkSize = offset === 0 ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 : MAX_SCRIPT_BLOCK; - var chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - var buffer = new Buffer(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - toSend.push(buffer); - offset += chunkSize; - }; - - while (offset !== message.length) { - _loop(); - } - return (0, utils.foreach)(toSend, function (data, i) { - return _this4.transport.send(0xe0, 0x4e, 0x00, i === 0 ? 0x01 : 0x80, data); - }).then(function () { - return _this4.transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00])).then(function (response) { - var v = response[0] - 0x30; - var r = response.slice(4, 4 + response[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - var offset = 4 + response[3] + 2; - var s = response.slice(offset, offset + response[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return { v: v, r: r, s: s }; - }); - }); - } - - /** - * To sign a transaction involving standard (P2PKH) inputs, call createPaymentTransactionNew with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @return the signed transaction ready to be broadcast - * @example - btc.createPaymentTransactionNew( - [ [tx1, 1] ], - ["0'/0/0"], - undefined, - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(res => ...); - */ - - }, { - key: "createPaymentTransactionNew", - value: function createPaymentTransactionNew(inputs, associatedKeysets, changePath, outputScriptHex) { - var lockTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SIGHASH_ALL; - var segwit = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; - var initialTimestamp = arguments[7]; - - var _this5 = this; - - var additionals = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; - var expiryHeight = arguments[9]; - - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var hasTimestamp = initialTimestamp !== undefined; - var startTime = Date.now(); - var sapling = additionals.includes("sapling"); - var bech32 = segwit && additionals.includes("bech32"); - var useBip143 = segwit || !!additionals && (additionals.includes("abc") || additionals.includes("gold") || additionals.includes("bip143")) || !!expiryHeight && !isDecred; - // Inputs are provided as arrays of [transaction, output_index, optional redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST ? defaultVersion.writeUInt32LE(2, 0) : defaultVersion.writeUInt32LE(1, 0); // Default version to 2 for XST not to have timestamp - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var publicKeys = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer.alloc(0) - }; - var getTrustedInputCall = useBip143 ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0], additionals).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer.from(trustedInput, "hex"), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }).then(function () { - if (!!expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); - } else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - }); - }).then(function () { - for (var i = 0; i < inputs.length; i++) { - var _sequence = Buffer.alloc(4); - _sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence - }); - } - }).then(function () { - return (0, utils.doIf)(!resuming, function () { - return ( - // Collect public keys - (0, utils.foreach)(inputs, function (input, i) { - return _this5.getWalletPublicKey_private(associatedKeysets[i]); - }).then(function (result) { - for (var index = 0; index < result.length; index++) { - publicKeys.push(_this5.compressPublicKey(Buffer.from(result[index].publicKey, "hex"))); - } - }) - ); - }); - }).then(function () { - if (hasTimestamp) { - targetTransaction.timestamp = Buffer.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - }).then(function () { - return (0, utils.doIf)(useBip143, function () { - return ( - // Do the first run with all inputs - _this5.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals).then(function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript); - }); - }) - ); - }); - }).then(function () { - return (0, utils.doIf)(!!expiryHeight && !isDecred, function () { - return ( - // FIXME: I think we should always pass lockTime here. - _this5.signTransaction("", lockTime, SIGHASH_ALL, expiryHeight) - ); - }); - }).then(function () { - return ( - // Do the second run with the individual transaction - (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : !segwit ? regularOutputs[i].script : Buffer.concat([Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), _this5.hashPublicKey(publicKeys[i]), Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])]); - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this5.startUntrustedHashTransactionInput(!useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals).then(function () { - return (0, utils.doIf)(!useBip143, function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript, additionals); - }); - }); - }).then(function () { - return _this5.signTransaction(associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals); - }).then(function (signature) { - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }) - ); - }).then(function () { - // Populate the final input scripts - for (var _i = 0; _i < inputs.length; _i++) { - if (segwit) { - targetTransaction.witness = Buffer.alloc(0); - if (!bech32) { - targetTransaction.inputs[_i].script = Buffer.concat([Buffer.from("160014", "hex"), _this5.hashPublicKey(publicKeys[_i])]); - } - } else { - var signatureSize = Buffer.alloc(1); - var keySize = Buffer.alloc(1); - signatureSize[0] = signatures[_i].length; - keySize[0] = publicKeys[_i].length; - targetTransaction.inputs[_i].script = Buffer.concat([signatureSize, signatures[_i], keySize, publicKeys[_i]]); - } - var offset = useBip143 ? 0 : 4; - targetTransaction.inputs[_i].prevout = trustedInputs[_i].value.slice(offset, offset + 0x24); - } - - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - - var result = Buffer.concat([_this5.serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript]); - - if (segwit && !isDecred) { - var witness = Buffer.alloc(0); - for (var i = 0; i < inputs.length; i++) { - var tmpScriptData = Buffer.concat([Buffer.from("02", "hex"), Buffer.from([signatures[i].length]), signatures[i], Buffer.from([publicKeys[i].length]), publicKeys[i]]); - witness = Buffer.concat([witness, tmpScriptData]); - } - result = Buffer.concat([result, witness]); - } - - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer.concat([result, lockTimeBuffer]); - - if (expiryHeight) { - result = Buffer.concat([result, targetTransaction.nExpiryHeight || Buffer.alloc(0), targetTransaction.extraData || Buffer.alloc(0)]); - } - - if (isDecred) { - var decredWitness = Buffer.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness = Buffer.concat([decredWitness, Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Buffer.from([0x00, 0x00, 0x00, 0x00]), //Block height - Buffer.from([0xff, 0xff, 0xff, 0xff]), //Block index - Buffer.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script]); - }); - - result = Buffer.concat([result, decredWitness]); - } - - return result.toString("hex"); - }); - } - - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction( - [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - ["0'/0/0"], - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(result => ...); - */ - - }, { - key: "signP2SHTransaction", - value: function signP2SHTransaction(inputs, associatedKeysets, outputScriptHex) { - var lockTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SIGHASH_ALL; - var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; - - var _this6 = this; - - var transactionVersion = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_VERSION; - var timeStamp = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; - - // Inputs are provided as arrays of [transaction, output_index, redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - var defaultTime = Buffer.alloc(4); - defaultTime.writeUInt32LE(timeStamp, 0); - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion - }; - - if (timeStamp > 0) { - targetTransaction.timestamp = defaultTime; - } - var getTrustedInputCall = segwit ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0]).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit ? Buffer.from(trustedInput, "hex") : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }); - }).then(function () { - // Pre-build the target transaction - for (var i = 0; i < inputs.length; i++) { - var _sequence2 = Buffer.alloc(4); - _sequence2.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence2 - }); - } - }).then(function () { - return (0, utils.doIf)(segwit, function () { - return ( - // Do the first run with all inputs - _this6.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true).then(function () { - return _this6.hashOutputFull(outputScript); - }) - ); - }); - }).then(function () { - return (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : regularOutputs[i].script; - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this6.startUntrustedHashTransactionInput(!segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit).then(function () { - return (0, utils.doIf)(!segwit, function () { - return _this6.hashOutputFull(outputScript); - }); - }).then(function () { - return _this6.signTransaction(associatedKeysets[i], lockTime, sigHashType).then(function (signature) { - signatures.push(signature.toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }); - }); - }).then(function () { - return signatures; - }); - } - }, { - key: "compressPublicKey", - value: function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer.alloc(1); - prefixBuffer[0] = prefix; - return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - }, { - key: "createVarint", - value: function createVarint(value) { - if (value < 0xfd) { - var _buffer = Buffer.alloc(1); - _buffer[0] = value; - return _buffer; - } - if (value <= 0xffff) { - var _buffer2 = Buffer.alloc(3); - _buffer2[0] = 0xfd; - _buffer2[1] = value & 0xff; - _buffer2[2] = value >> 8 & 0xff; - return _buffer2; - } - var buffer = Buffer.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = value >> 8 & 0xff; - buffer[3] = value >> 16 & 0xff; - buffer[4] = value >> 24 & 0xff; - return buffer; - } - - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - - }, { - key: "splitTransaction", - value: function splitTransaction(transactionHex) { - var isSegwitSupported = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var hasTimestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var hasExtraData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer.alloc(0); - var nExpiryHeight = Buffer.alloc(0); - var nVersionGroupId = Buffer.alloc(0); - var extraData = Buffer.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && isSegwitSupported && transaction[offset] === 0 && transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = this.getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var _prevout = transaction.slice(offset, offset + 36); - offset += 36; - var _script = Buffer.alloc(0); - var _tree = Buffer.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - _script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } else { - //Tree field - _tree = transaction.slice(offset, offset + 1); - offset += 1; - } - - var _sequence3 = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ prevout: _prevout, script: _script, sequence: _sequence3, tree: _tree }); - } - varint = this.getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var _i2 = 0; _i2 < numberOutputs; _i2++) { - var _amount = transaction.slice(offset, offset + 8); - offset += 8; - - if (isDecred) { - //Script version - offset += 2; - } - - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script2 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ amount: _amount, script: _script2 }); - } - var witnessScript = void 0, - locktime = void 0; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - - //Get witnesses for Decred - if (isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var _i3 = 0; _i3 < numberInputs; _i3++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script3 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[_i3].script = _script3; - } - } - - return { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - - }, { - key: "serializeTransactionOutputs", - value: function serializeTransactionOutputs(_ref2) { - var _this7 = this; - - var outputs = _ref2.outputs; - - var outputBuffer = Buffer.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, this.createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer.concat([outputBuffer, output.amount, _this7.createVarint(output.script.length), output.script]); - }); - } - return outputBuffer; - } - - /** - */ - - }, { - key: "serializeTransaction", - value: function serializeTransaction(transaction, skipWitness, timestamp) { - var _this8 = this; - - var additionals = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; - - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = isDecred || isBech32 ? Buffer.concat([inputBuffer, input.prevout, Buffer.from([0x00]), //tree - input.sequence]) : Buffer.concat([inputBuffer, input.prevout, _this8.createVarint(input.script.length), input.script, input.sequence]); - }); - - var outputBuffer = this.serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, useWitness && transaction.witness || Buffer.alloc(0), transaction.locktime, transaction.nExpiryHeight || Buffer.alloc(0), transaction.extraData || Buffer.alloc(0)]); - } - - return Buffer.concat([transaction.version, timestamp ? timestamp : Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), this.createVarint(transaction.inputs.length), inputBuffer, outputBuffer]); - } - - /** - */ - - }, { - key: "displayTransactionDebug", - value: function displayTransactionDebug(transaction) { - console.log("version " + transaction.version.toString("hex")); - transaction.inputs.forEach(function (input, i) { - var prevout = input.prevout.toString("hex"); - var script = input.script.toString("hex"); - var sequence = input.sequence.toString("hex"); - console.log("input " + i + " prevout " + prevout + " script " + script + " sequence " + sequence); - }); - (transaction.outputs || []).forEach(function (output, i) { - var amount = output.amount.toString("hex"); - var script = output.script.toString("hex"); - console.log("output " + i + " amount " + amount + " script " + script); - }); - if (typeof transaction.locktime !== "undefined") { - console.log("locktime " + transaction.locktime.toString("hex")); - } - } - }]); - - return Btc; - }(); - - /** - */ - - - exports.default = Btc; - - /** - */ - - - /** - */ - - }); - - var Btc = unwrapExports(Btc_1); - - var Btc$1 = /*#__PURE__*/Object.freeze({ - default: Btc, - __moduleExports: Btc_1 - }); - - var domain; - - // This constructor is used to store event handlers. Instantiating this is - // faster than explicitly calling `Object.create(null)` to get a "clean" empty - // object (tested with v8 v4.9). - function EventHandlers() {} - EventHandlers.prototype = Object.create(null); - - function EventEmitter() { - EventEmitter.init.call(this); - } - - // nodejs oddity - // require('events') === require('events').EventEmitter - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.usingDomains = false; - - EventEmitter.prototype.domain = undefined; - EventEmitter.prototype._events = undefined; - 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. - EventEmitter.defaultMaxListeners = 10; - - EventEmitter.init = function() { - this.domain = null; - if (EventEmitter.usingDomains) { - // if there is an active domain, then attach to it. - if (domain.active && !(this instanceof domain.Domain)) { - this.domain = domain.active; - } - } - - if (!this._events || this._events === Object.getPrototypeOf(this)._events) { - this._events = new EventHandlers(); - 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 || isNaN(n)) - throw new TypeError('"n" argument must be a positive number'); - 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); - }; - - // These standalone emit* functions are used to optimize calling of event - // handlers for fast cases because emit() itself often has a variable number of - // arguments and can be deoptimized because of that. These functions always have - // the same number of arguments and thus do not get deoptimized, so the code - // inside them can execute faster. - function emitNone(handler, isFn, self) { - if (isFn) - handler.call(self); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self); - } - } - function emitOne(handler, isFn, self, arg1) { - if (isFn) - handler.call(self, arg1); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1); - } - } - function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) - handler.call(self, arg1, arg2); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2); - } - } - function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) - handler.call(self, arg1, arg2, arg3); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2, arg3); - } - } - - function emitMany(handler, isFn, self, args) { - if (isFn) - handler.apply(self, args); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].apply(self, args); - } - } - - EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events, domain; - var needDomainExit = false; - var doError = (type === 'error'); - - events = this._events; - if (events) - doError = (doError && events.error == null); - else if (!doError) - return false; - - domain = this.domain; - - // If there is no 'error' event listener then throw. - if (doError) { - er = arguments[1]; - if (domain) { - if (!er) - er = new Error('Uncaught, unspecified "error" event'); - er.domainEmitter = this; - er.domain = domain; - er.domainThrown = false; - domain.emit('error', er); - } else if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - return false; - } - - handler = events[type]; - - if (!handler) - return false; - - var isFn = typeof handler === 'function'; - len = arguments.length; - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - default: - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - emitMany(handler, isFn, this, args); - } - - if (needDomainExit) - domain.exit(); - - return true; - }; - - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = target._events; - if (!events) { - events = target._events = new EventHandlers(); - 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) { - 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) { - // 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]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } - - // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + type + ' listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - emitWarning(w); - } - } - } - - return target; - } - function emitWarning(e) { - typeof console.warn === 'function' ? console.warn(e) : console.log(e); - } - 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 _onceWrap(target, type, listener) { - var fired = false; - function g() { - target.removeListener(type, g); - if (!fired) { - fired = true; - listener.apply(target, arguments); - } - } - g.listener = listener; - return g; - } - - EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - - EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = this._events; - if (!events) - return this; - - list = events[type]; - if (!list) - return this; - - if (list === listener || (list.listener && list.listener === listener)) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - 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; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list[0] = undefined; - if (--this._eventsCount === 0) { - this._events = new EventHandlers(); - return this; - } else { - delete events[type]; - } - } else { - spliceOne(list, position); - } - - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events; - - events = this._events; - if (!events) - return this; - - // not listening for removeListener, no need to emit - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = new EventHandlers(); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - for (var i = 0, key; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = new EventHandlers(); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - do { - this.removeListener(type, listeners[listeners.length - 1]); - } while (listeners[0]); - } - - return this; - }; - - EventEmitter.prototype.listeners = function listeners(type) { - var evlistener; - var ret; - var events = this._events; - - if (!events) - ret = []; - else { - evlistener = events[type]; - if (!evlistener) - ret = []; - else if (typeof evlistener === 'function') - ret = [evlistener.listener || evlistener]; - else - ret = unwrapListeners(evlistener); - } - - return ret; - }; - - 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) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; - } - - EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; - }; - - // About 1.5x faster than the two-arg version of Array#splice(). - function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; - list.pop(); - } - - function arrayClone(arr, i) { - var copy = new Array(i); - while (i--) - copy[i] = arr[i]; - return copy; - } - - 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; - } - - var helpers = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = exports.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = exports.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - }); - - unwrapExports(helpers); - var helpers_1 = helpers.addCustomErrorDeserializer; - var helpers_2 = helpers.createCustomErrorClass; - var helpers_3 = helpers.deserializeError; - var helpers_4 = helpers.serializeError; - - var lib = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughGas = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; - exports.TransportError = TransportError; - exports.getAltStatusMessage = getAltStatusMessage; - exports.TransportStatusError = TransportStatusError; - - - - exports.serializeError = helpers.serializeError; - exports.deserializeError = helpers.deserializeError; - exports.createCustomErrorClass = helpers.createCustomErrorClass; - exports.addCustomErrorDeserializer = helpers.addCustomErrorDeserializer; - var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers.createCustomErrorClass)("AccountNameRequired"); - var BluetoothRequired = exports.BluetoothRequired = (0, helpers.createCustomErrorClass)("BluetoothRequired"); - var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers.createCustomErrorClass)("BtcUnmatchedApp"); - var CantOpenDevice = exports.CantOpenDevice = (0, helpers.createCustomErrorClass)("CantOpenDevice"); - var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers.createCustomErrorClass)("CashAddrNotSupported"); - var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers.createCustomErrorClass)("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers.createCustomErrorClass)("DeviceNotGenuine"); - var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); - var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers.createCustomErrorClass)("DeviceInOSUExpected"); - var DeviceHalted = exports.DeviceHalted = (0, helpers.createCustomErrorClass)("DeviceHalted"); - var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers.createCustomErrorClass)("DeviceNameInvalid"); - var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers.createCustomErrorClass)("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers.createCustomErrorClass)("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = exports.EnpointConfigError = (0, helpers.createCustomErrorClass)("EnpointConfig"); - var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers.createCustomErrorClass)("FeeEstimationFailed"); - var HardResetFail = exports.HardResetFail = (0, helpers.createCustomErrorClass)("HardResetFail"); - var InvalidAddress = exports.InvalidAddress = (0, helpers.createCustomErrorClass)("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers.createCustomErrorClass)("LatestMCUInstalledError"); - var UnknownMCU = exports.UnknownMCU = (0, helpers.createCustomErrorClass)("UnknownMCU"); - var LedgerAPIError = exports.LedgerAPIError = (0, helpers.createCustomErrorClass)("LedgerAPIError"); - var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers.createCustomErrorClass)("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); - var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers.createCustomErrorClass)("ManagerDeviceLocked"); - var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); - var NetworkDown = exports.NetworkDown = (0, helpers.createCustomErrorClass)("NetworkDown"); - var NoAddressesFound = exports.NoAddressesFound = (0, helpers.createCustomErrorClass)("NoAddressesFound"); - var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers.createCustomErrorClass)("NotEnoughBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - var NotEnoughGas = exports.NotEnoughGas = (0, helpers.createCustomErrorClass)("NotEnoughGas"); - var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers.createCustomErrorClass)("PasswordsDontMatch"); - var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers.createCustomErrorClass)("PasswordIncorrect"); - var TimeoutTagged = exports.TimeoutTagged = (0, helpers.createCustomErrorClass)("TimeoutTagged"); - var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers.createCustomErrorClass)("UnexpectedBootloader"); - var UpdateYourApp = exports.UpdateYourApp = (0, helpers.createCustomErrorClass)("UpdateYourApp"); - var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); - var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers.createCustomErrorClass)("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers.createCustomErrorClass)("UserRefusedAllowManager"); - var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers.createCustomErrorClass)("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); - var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers.createCustomErrorClass)("DeviceShouldStayInApp"); - var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers.createCustomErrorClass)("WebsocketConnectionError"); - var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers.createCustomErrorClass)("WebsocketConnectionFailed"); - var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers.createCustomErrorClass)("WrongDeviceForAccount"); - var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers.createCustomErrorClass)("ETHAddressNonEIP"); - var CantScanQRCode = exports.CantScanQRCode = (0, helpers.createCustomErrorClass)("CantScanQRCode"); - var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers.createCustomErrorClass)("FeeNotLoaded"); - var FeeRequired = exports.FeeRequired = (0, helpers.createCustomErrorClass)("FeeRequired"); - var SyncError = exports.SyncError = (0, helpers.createCustomErrorClass)("SyncError"); - var PairingFailed = exports.PairingFailed = (0, helpers.createCustomErrorClass)("PairingFailed"); - var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers.createCustomErrorClass)("GenuineCheckFailed"); - var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers.createCustomErrorClass)("LedgerAPI4xx"); - var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers.createCustomErrorClass)("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers.createCustomErrorClass)("NoDBPathGiven"); - var DBWrongPassword = exports.DBWrongPassword = (0, helpers.createCustomErrorClass)("DBWrongPassword"); - var DBNotReset = exports.DBNotReset = (0, helpers.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = exports.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - }); - - unwrapExports(lib); - var lib_1 = lib.StatusCodes; - var lib_2 = lib.DBNotReset; - var lib_3 = lib.DBWrongPassword; - var lib_4 = lib.NoDBPathGiven; - var lib_5 = lib.FirmwareOrAppUpdateRequired; - var lib_6 = lib.LedgerAPI5xx; - var lib_7 = lib.LedgerAPI4xx; - var lib_8 = lib.GenuineCheckFailed; - var lib_9 = lib.PairingFailed; - var lib_10 = lib.SyncError; - var lib_11 = lib.FeeRequired; - var lib_12 = lib.FeeNotLoaded; - var lib_13 = lib.CantScanQRCode; - var lib_14 = lib.ETHAddressNonEIP; - var lib_15 = lib.WrongDeviceForAccount; - var lib_16 = lib.WebsocketConnectionFailed; - var lib_17 = lib.WebsocketConnectionError; - var lib_18 = lib.DeviceShouldStayInApp; - var lib_19 = lib.TransportInterfaceNotAvailable; - var lib_20 = lib.TransportOpenUserCancelled; - var lib_21 = lib.UserRefusedOnDevice; - var lib_22 = lib.UserRefusedAllowManager; - var lib_23 = lib.UserRefusedFirmwareUpdate; - var lib_24 = lib.UserRefusedAddress; - var lib_25 = lib.UserRefusedDeviceNameChange; - var lib_26 = lib.UpdateYourApp; - var lib_27 = lib.UnexpectedBootloader; - var lib_28 = lib.TimeoutTagged; - var lib_29 = lib.PasswordIncorrectError; - var lib_30 = lib.PasswordsDontMatchError; - var lib_31 = lib.NotEnoughGas; - var lib_32 = lib.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_33 = lib.NotEnoughBalance; - var lib_34 = lib.NoAddressesFound; - var lib_35 = lib.NetworkDown; - var lib_36 = lib.ManagerUninstallBTCDep; - var lib_37 = lib.ManagerNotEnoughSpaceError; - var lib_38 = lib.ManagerDeviceLockedError; - var lib_39 = lib.ManagerAppRelyOnBTCError; - var lib_40 = lib.ManagerAppAlreadyInstalledError; - var lib_41 = lib.LedgerAPINotAvailable; - var lib_42 = lib.LedgerAPIErrorWithMessage; - var lib_43 = lib.LedgerAPIError; - var lib_44 = lib.UnknownMCU; - var lib_45 = lib.LatestMCUInstalledError; - var lib_46 = lib.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_47 = lib.InvalidAddress; - var lib_48 = lib.HardResetFail; - var lib_49 = lib.FeeEstimationFailed; - var lib_50 = lib.EthAppPleaseEnableContractData; - var lib_51 = lib.EnpointConfigError; - var lib_52 = lib.DisconnectedDeviceDuringOperation; - var lib_53 = lib.DisconnectedDevice; - var lib_54 = lib.DeviceSocketNoBulkStatus; - var lib_55 = lib.DeviceSocketFail; - var lib_56 = lib.DeviceNameInvalid; - var lib_57 = lib.DeviceHalted; - var lib_58 = lib.DeviceInOSUExpected; - var lib_59 = lib.DeviceOnDashboardExpected; - var lib_60 = lib.DeviceNotGenuineError; - var lib_61 = lib.DeviceGenuineSocketEarlyClose; - var lib_62 = lib.DeviceAppVerifyNotSupported; - var lib_63 = lib.CurrencyNotSupported; - var lib_64 = lib.CashAddrNotSupported; - var lib_65 = lib.CantOpenDevice; - var lib_66 = lib.BtcUnmatchedApp; - var lib_67 = lib.BluetoothRequired; - var lib_68 = lib.AccountNameRequiredError; - var lib_69 = lib.addCustomErrorDeserializer; - var lib_70 = lib.createCustomErrorClass; - var lib_71 = lib.deserializeError; - var lib_72 = lib.serializeError; - var lib_73 = lib.TransportError; - var lib_74 = lib.getAltStatusMessage; - var lib_75 = lib.TransportStatusError; - - var Transport_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _events3 = _interopRequireDefault(EventEmitter); - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - exports.TransportError = lib.TransportError; - exports.TransportStatusError = lib.TransportStatusError; - exports.StatusCodes = lib.StatusCodes; - exports.getAltStatusMessage = lib.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new lib.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new lib.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new lib.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new lib.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new lib.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new lib.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; - - }); - - unwrapExports(Transport_1); - var Transport_2 = Transport_1.getAltStatusMessage; - var Transport_3 = Transport_1.StatusCodes; - var Transport_4 = Transport_1.TransportStatusError; - var Transport_5 = Transport_1.TransportError; - - var hidFraming = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - - var Tag = 0x05; - - function asUInt16BE(value) { - var b = Buffer.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - - var initialAcc = { - data: Buffer.alloc(0), - dataLength: 0, - sequence: 0 - }; - - /** - * - */ - var createHIDframing = function createHIDframing(channel, packetSize) { - return { - makeBlocks: function makeBlocks(apdu) { - var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer.concat([data, // fill data with padding - Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); - - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function reduceResponse(acc, chunk) { - var _ref = acc || initialAcc, - data = _ref.data, - dataLength = _ref.dataLength, - sequence = _ref.sequence; - - if (chunk.readUInt16BE(0) !== channel) { - throw new lib.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new lib.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new lib.TransportError("Invalid sequence", "InvalidSequence"); - } - - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - - exports.default = createHIDframing; - - }); - - unwrapExports(hidFraming); - - var lib$1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - /** - * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) - * - ** Model - * Ledger Nano S : 0x10 - * Ledger Blue : 0x00 - * Ledger Nano X : 0x40 - * - ** Interface support bitfield - * Generic HID : 0x01 - * Keyboard HID : 0x02 - * U2F : 0x04 - * CCID : 0x08 - * WebUSB : 0x10 - */ - - var IIGenericHID = exports.IIGenericHID = 0x01; - var IIKeyboardHID = exports.IIKeyboardHID = 0x02; - var IIU2F = exports.IIU2F = 0x04; - var IICCID = exports.IICCID = 0x08; - var IIWebUSB = exports.IIWebUSB = 0x10; - - var devices = { - blue: { - id: "blue", - productName: "Ledger Blue", - productIdMM: 0, - legacyUsbProductId: 0x0000, - usbOnly: true - }, - nanoS: { - id: "nanoS", - productName: "Ledger Nano S", - productIdMM: 1, - legacyUsbProductId: 0x0001, - usbOnly: true - }, - nanoX: { - id: "nanoX", - productName: "Ledger Nano X", - productIdMM: 4, - legacyUsbProductId: 0x0004, - usbOnly: false, - bluetoothSpec: [{ - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" - }, { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572" - }] - } - }; - - // $FlowFixMe - var devicesList = Object.values(devices); - - /** - * - */ - var ledgerUSBVendorId = exports.ledgerUSBVendorId = 0x2c97; - - /** - * - */ - var getDeviceModel = exports.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; - - /** - * - */ - var identifyUSBProductId = exports.identifyUSBProductId = function identifyUSBProductId(usbProductId) { - var legacy = devicesList.find(function (d) { - return d.legacyUsbProductId === usbProductId; - }); - if (legacy) return legacy; - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { - return d.productIdMM === mm; - }); - return deviceModel; - }; - - var bluetoothServices = []; - var serviceUuidToInfos = {}; - - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; - - if (_bluetoothSpec) { - for (var i = 0; i < _bluetoothSpec.length; i++) { - var spec = _bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); - } - } - } - - /** - * - */ - var getBluetoothServiceUuids = exports.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - var getInfosForServiceUuid = exports.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; - - /** - * - */ - - - /** - * - */ - - - /** - * - */ - - }); - - unwrapExports(lib$1); - var lib_1$1 = lib$1.IIGenericHID; - var lib_2$1 = lib$1.IIKeyboardHID; - var lib_3$1 = lib$1.IIU2F; - var lib_4$1 = lib$1.IICCID; - var lib_5$1 = lib$1.IIWebUSB; - var lib_6$1 = lib$1.ledgerUSBVendorId; - var lib_7$1 = lib$1.getDeviceModel; - var lib_8$1 = lib$1.identifyUSBProductId; - var lib_9$1 = lib$1.getBluetoothServiceUuids; - var lib_10$1 = lib$1.getInfosForServiceUuid; - - var lib$2 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - /** - * A Log object - */ - var id = 0; - var subscribers = []; - - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = exports.log = function log(type, message, data) { - var obj = { type: type, id: String(++id), date: new Date() }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = exports.listen = function listen(cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } - - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; - - }); - - var index$2 = unwrapExports(lib$2); - var lib_1$2 = lib$2.log; - var lib_2$2 = lib$2.listen; - - var index$3 = /*#__PURE__*/Object.freeze({ - default: index$2, - __moduleExports: lib$2, - log: lib_1$2, - listen: lib_2$2 - }); - - var webusb = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.isSupported = exports.getFirstLedgerDevice = exports.getLedgerDevices = exports.requestLedgerDevice = undefined; - - var requestLedgerDevice = exports.requestLedgerDevice = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var device; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return navigator.usb.requestDevice({ filters: ledgerDevices }); - - case 2: - device = _context.sent; - return _context.abrupt("return", device); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function requestLedgerDevice() { - return _ref.apply(this, arguments); - }; - }(); - - var getLedgerDevices = exports.getLedgerDevices = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var devices; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return navigator.usb.getDevices(); - - case 2: - devices = _context2.sent; - return _context2.abrupt("return", devices.filter(function (d) { - return d.vendorId === lib$1.ledgerUSBVendorId; - })); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function getLedgerDevices() { - return _ref2.apply(this, arguments); - }; - }(); - - var getFirstLedgerDevice = exports.getFirstLedgerDevice = function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var existingDevices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getLedgerDevices(); - - case 2: - existingDevices = _context3.sent; - - if (!(existingDevices.length > 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", existingDevices[0]); - - case 5: - return _context3.abrupt("return", requestLedgerDevice()); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); - - - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - var ledgerDevices = [{ vendorId: lib$1.ledgerUSBVendorId }]; - - var isSupported = exports.isSupported = function isSupported() { - return Promise.resolve( - // $FlowFixMe - !!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; - - }); - - unwrapExports(webusb); - var webusb_1 = webusb.isSupported; - var webusb_2 = webusb.getFirstLedgerDevice; - var webusb_3 = webusb.getLedgerDevices; - var webusb_4 = webusb.requestLedgerDevice; - - var TransportWebUSB_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _hwTransport2 = _interopRequireDefault(Transport_1); - - - - var _hidFraming2 = _interopRequireDefault(hidFraming); - - - - - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var configurationValue = 1; - var interfaceNumber = 2; - var endpointNumber = 3; - - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ - - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); - - function TransportWebUSB(device) { - _classCallCheck(this, TransportWebUSB); - - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); - - _initialiseProps.call(_this); - - _this.device = device; - _this.deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - return _this; - } - - /** - * Check if WebUSB transport is supported. - */ - - - /** - * List the WebUSB devices that was previously authorized by the user. - */ - - - /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! - */ - - - _createClass(TransportWebUSB, [{ - key: "close", - - - /** - * Release the transport device - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.exchangeBusyPromise; - - case 2: - _context.next = 4; - return this.device.releaseInterface(interfaceNumber); - - case 4: - _context.next = 6; - return this.device.reset(); - - case 6: - _context.next = 8; - return this.device.close(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _ref.apply(this, arguments); - } - - return close; - }() - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey() {} - }], [{ - key: "request", - - - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var device; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return (0, webusb.requestLedgerDevice)(); - - case 2: - device = _context2.sent; - return _context2.abrupt("return", TransportWebUSB.open(device)); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function request() { - return _ref2.apply(this, arguments); - } - - return request; - }() - - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ - - }, { - key: "openConnected", - value: function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var devices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return (0, webusb.getLedgerDevices)(); - - case 2: - devices = _context3.sent; - - if (!(devices.length === 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", null); - - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function openConnected() { - return _ref3.apply(this, arguments); - } - - return openConnected; - }() - - /** - * Create a Ledger transport with a USBDevice - */ - - }, { - key: "open", - value: function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { - var transport, onDisconnect; - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return device.open(); - - case 2: - if (!(device.configuration === null)) { - _context4.next = 5; - break; - } - - _context4.next = 5; - return device.selectConfiguration(configurationValue); - - case 5: - _context4.next = 7; - return device.reset(); - - case 7: - _context4.prev = 7; - _context4.next = 10; - return device.claimInterface(interfaceNumber); - - case 10: - _context4.next = 17; - break; - - case 12: - _context4.prev = 12; - _context4.t0 = _context4["catch"](7); - _context4.next = 16; - return device.close(); - - case 16: - throw new lib.TransportInterfaceNotAvailable(_context4.t0.message); - - case 17: - transport = new TransportWebUSB(device); - - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new lib.DisconnectedDevice()); - } - }; - // $FlowFixMe - - - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); - - case 21: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[7, 12]]); - })); - - function open(_x) { - return _ref4.apply(this, arguments); - } - - return open; - }() - }]); - - return TransportWebUSB; - }(_hwTransport2.default); - - TransportWebUSB.isSupported = webusb.isSupported; - TransportWebUSB.list = webusb.getLedgerDevices; - - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - (0, webusb.getFirstLedgerDevice)().then(function (device) { - if (!unsubscribed) { - var deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); - observer.complete(); - } - }, function (error) { - observer.error(new lib.TransportOpenUserCancelled(error.message)); - }); - function unsubscribe() { - unsubscribed = true; - } - return { unsubscribe: unsubscribe }; - }; - - var _initialiseProps = function _initialiseProps() { - var _this2 = this; - - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; - - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; - - this.exchange = function (apdu) { - return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - channel = _this2.channel, packetSize = _this2.packetSize; - - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); - - framing = (0, _hidFraming2.default)(channel, packetSize); - - // Write... - - blocks = framing.makeBlocks(apdu); - i = 0; - - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } - - (0, lib$2.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); - - case 9: - i++; - _context5.next = 5; - break; - - case 12: - - // Read... - result = void 0; - acc = void 0; - - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } - - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); - - case 17: - r = _context5.sent; - buffer = Buffer.from(r.data.buffer); - - (0, lib$2.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; - - case 23: - - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); - - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5, _this2); - }))).catch(function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this2._emitDisconnect(e); - throw new lib.DisconnectedDeviceDuringOperation(e.message); - } - throw e; - }); - }; - }; - - exports.default = TransportWebUSB; - - }); - - var TransportWebUSB = unwrapExports(TransportWebUSB_1); - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ - default: TransportWebUSB, - __moduleExports: TransportWebUSB_1 - }); - - // Copyright 2014 Google Inc. All rights reserved - - /** Namespace for the U2F api. - * @type {Object} - */ - var u2f = u2f || {}; - - var googleU2fApi = u2f; // Adaptation for u2f-api package - - /** - * The U2F extension id - * @type {string} - * @const - */ - u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; - - /** - * Message types for messsages to/from the extension - * @const - * @enum {string} - */ - u2f.MessageTypes = { - 'U2F_REGISTER_REQUEST': 'u2f_register_request', - 'U2F_SIGN_REQUEST': 'u2f_sign_request', - 'U2F_REGISTER_RESPONSE': 'u2f_register_response', - 'U2F_SIGN_RESPONSE': 'u2f_sign_response' - }; - - /** - * Response status codes - * @const - * @enum {number} - */ - u2f.ErrorCodes = { - 'OK': 0, - 'OTHER_ERROR': 1, - 'BAD_REQUEST': 2, - 'CONFIGURATION_UNSUPPORTED': 3, - 'DEVICE_INELIGIBLE': 4, - 'TIMEOUT': 5 - }; - - - // Low level MessagePort API support - - /** - * Call MessagePort disconnect - */ - u2f.disconnect = function() { - if (u2f.port_ && u2f.port_.port_) { - u2f.port_.port_.disconnect(); - u2f.port_ = null; - } - }; - - /** - * Sets up a MessagePort to the U2F extension using the - * available mechanisms. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - */ - u2f.getMessagePort = function(callback) { - if (typeof chrome != 'undefined' && chrome.runtime) { - // The actual message here does not matter, but we need to get a reply - // for the callback to run. Thus, send an empty signature request - // in order to get a failure response. - var msg = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: [] - }; - chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { - if (!chrome.runtime.lastError) { - // We are on a whitelisted origin and can talk directly - // with the extension. - u2f.getChromeRuntimePort_(callback); - } else { - // chrome.runtime was available, but we couldn't message - // the extension directly, use iframe - u2f.getIframePort_(callback); - } - }); - } else { - // chrome.runtime was not available at all, which is normal - // when this origin doesn't have access to any extensions. - u2f.getIframePort_(callback); - } - }; - - /** - * Connects directly to the extension via chrome.runtime.connect - * @param {function(u2f.WrappedChromeRuntimePort_)} callback - * @private - */ - u2f.getChromeRuntimePort_ = function(callback) { - var port = chrome.runtime.connect(u2f.EXTENSION_ID, - {'includeTlsChannelId': true}); - setTimeout(function() { - callback(null, new u2f.WrappedChromeRuntimePort_(port)); - }, 0); - }; - - /** - * A wrapper for chrome.runtime.Port that is compatible with MessagePort. - * @param {Port} port - * @constructor - * @private - */ - u2f.WrappedChromeRuntimePort_ = function(port) { - this.port_ = port; - }; - - /** - * Posts a message on the underlying channel. - * @param {Object} message - */ - u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { - this.port_.postMessage(message); - }; - - /** - * Emulates the HTML 5 addEventListener interface. Works only for the - * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. - * @param {string} eventName - * @param {function({data: Object})} handler - */ - u2f.WrappedChromeRuntimePort_.prototype.addEventListener = - function(eventName, handler) { - var name = eventName.toLowerCase(); - if (name == 'message' || name == 'onmessage') { - this.port_.onMessage.addListener(function(message) { - // Emulate a minimal MessageEvent object - handler({'data': message}); - }); - } else { - console.error('WrappedChromeRuntimePort only supports onMessage'); - } - }; - - /** - * Sets up an embedded trampoline iframe, sourced from the extension. - * @param {function(MessagePort)} callback - * @private - */ - u2f.getIframePort_ = function(callback) { - // Create the iframe - var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; - var iframe = document.createElement('iframe'); - iframe.src = iframeOrigin + '/u2f-comms.html'; - iframe.setAttribute('style', 'display:none'); - document.body.appendChild(iframe); - - var hasCalledBack = false; - - var channel = new MessageChannel(); - var ready = function(message) { - if (message.data == 'ready') { - channel.port1.removeEventListener('message', ready); - if (!hasCalledBack) - { - hasCalledBack = true; - callback(null, channel.port1); - } - } else { - console.error('First event on iframe port was not "ready"'); - } - }; - channel.port1.addEventListener('message', ready); - channel.port1.start(); - - iframe.addEventListener('load', function() { - // Deliver the port to the iframe and initialize - iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); - }); - - // Give this 200ms to initialize, after that, we treat this method as failed - setTimeout(function() { - if (!hasCalledBack) - { - hasCalledBack = true; - callback(new Error("IFrame extension not supported")); - } - }, 200); - }; - - - // High-level JS API - - /** - * Default extension response timeout in seconds. - * @const - */ - u2f.EXTENSION_TIMEOUT_SEC = 30; - - /** - * A singleton instance for a MessagePort to the extension. - * @type {MessagePort|u2f.WrappedChromeRuntimePort_} - * @private - */ - u2f.port_ = null; - - /** - * Callbacks waiting for a port - * @type {Array.} - * @private - */ - u2f.waitingForPort_ = []; - - /** - * A counter for requestIds. - * @type {number} - * @private - */ - u2f.reqCounter_ = 0; - - /** - * A map from requestIds to client callbacks - * @type {Object.} - * @private - */ - u2f.callbackMap_ = {}; - - /** - * Creates or retrieves the MessagePort singleton to use. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - * @private - */ - u2f.getPortSingleton_ = function(callback) { - if (u2f.port_) { - callback(null, u2f.port_); - } else { - if (u2f.waitingForPort_.length == 0) { - u2f.getMessagePort(function(err, port) { - if (!err) { - u2f.port_ = port; - u2f.port_.addEventListener('message', - /** @type {function(Event)} */ (u2f.responseHandler_)); - } - - // Careful, here be async callbacks. Maybe. - while (u2f.waitingForPort_.length) - u2f.waitingForPort_.shift()(err, port); - }); - } - u2f.waitingForPort_.push(callback); - } - }; - - /** - * Handles response messages from the extension. - * @param {MessageEvent.} message - * @private - */ - u2f.responseHandler_ = function(message) { - var response = message.data; - var reqId = response['requestId']; - if (!reqId || !u2f.callbackMap_[reqId]) { - console.error('Unknown or missing requestId in response.'); - return; - } - var cb = u2f.callbackMap_[reqId]; - delete u2f.callbackMap_[reqId]; - cb(null, response['responseData']); - }; - - /** - * Calls the callback with true or false as first and only argument - * @param {Function} callback - */ - u2f.isSupported = function(callback) { - u2f.getPortSingleton_(function(err, port) { - callback(!err); - }); - }; - - /** - * Dispatches an array of sign requests to available U2F tokens. - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.SignResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: signRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - /** - * Dispatches register requests to available U2F tokens. An array of sign - * requests identifies already registered tokens. - * @param {Array.} registerRequests - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.RegisterResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.register = function(registerRequests, signRequests, - callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_REGISTER_REQUEST, - signRequests: signRequests, - registerRequests: registerRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - var u2fApi = API; - - - - // Feature detection (yes really) - var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; - var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) - && !navigator.userAgent.match( /Chrome\// ); - var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); - - var _backend = null; - function getBackend( Promise ) - { - if ( !_backend ) - _backend = new Promise( function( resolve, reject ) - { - function notSupported( ) - { - // Note; {native: true} means *not* using Google's hack - resolve( { u2f: null, native: true } ); - } - - if ( !isBrowser ) - return notSupported( ); - - if ( isSafari ) - // Safari doesn't support U2F, and the Safari-FIDO-U2F - // extension lacks full support (Multi-facet apps), so we - // block it until proper support. - return notSupported( ); - - var hasNativeSupport = - ( typeof window.u2f !== 'undefined' ) && - ( typeof window.u2f.sign === 'function' ); - - if ( hasNativeSupport ) - resolve( { u2f: window.u2f, native: true } ); - - if ( isEDGE ) - // We don't want to check for Google's extension hack on EDGE - // as it'll cause trouble (popups, etc) - return notSupported( ); - - if ( location.protocol === 'http:' ) - // U2F isn't supported over http, only https - return notSupported( ); - - if ( typeof MessageChannel === 'undefined' ) - // Unsupported browser, the chrome hack would throw - return notSupported( ); - - // Test for google extension support - googleU2fApi.isSupported( function( ok ) - { - if ( ok ) - resolve( { u2f: googleU2fApi, native: false } ); - else - notSupported( ); - } ); - } ); - - return _backend; - } - - function API( Promise ) - { - return { - isSupported : isSupported.bind( Promise ), - ensureSupport : ensureSupport.bind( Promise ), - register : register.bind( Promise ), - sign : sign.bind( Promise ), - ErrorCodes : API.ErrorCodes, - ErrorNames : API.ErrorNames - }; - } - - API.ErrorCodes = { - CANCELLED: -1, - OK: 0, - OTHER_ERROR: 1, - BAD_REQUEST: 2, - CONFIGURATION_UNSUPPORTED: 3, - DEVICE_INELIGIBLE: 4, - TIMEOUT: 5 - }; - API.ErrorNames = { - "-1": "CANCELLED", - "0": "OK", - "1": "OTHER_ERROR", - "2": "BAD_REQUEST", - "3": "CONFIGURATION_UNSUPPORTED", - "4": "DEVICE_INELIGIBLE", - "5": "TIMEOUT" - }; - - function makeError( msg, err ) - { - var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR - var type = API.ErrorNames[ '' + code ]; - var error = new Error( msg ); - error.metaData = { - type: type, - code: code - }; - return error; - } - - function deferPromise( Promise, promise ) - { - var ret = { }; - ret.promise = new Promise( function( resolve, reject ) { - ret.resolve = resolve; - ret.reject = reject; - promise.then( resolve, reject ); - } ); - /** - * Reject request promise and disconnect port if 'disconnect' flag is true - * @param {string} msg - * @param {boolean} disconnect - */ - ret.promise.cancel = function( msg, disconnect ) - { - getBackend( Promise ) - .then( function( backend ) - { - if ( disconnect && !backend.native ) - backend.u2f.disconnect( ); - - ret.reject( makeError( msg, { errorCode: -1 } ) ); - } ); - }; - return ret; - } - - function isSupported( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( function( backend ) - { - return !!backend.u2f; - } ); - } - - function _ensureSupport( backend ) - { - if ( !backend.u2f ) - { - if ( location.protocol === 'http:' ) - throw new Error( "U2F isn't supported over http, only https" ); - throw new Error( "U2F not supported" ); - } - } - - function ensureSupport( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( _ensureSupport ); - } - - function register( registerRequests, signRequests /* = null */, timeout ) - { - var Promise = this; - - if ( !Array.isArray( registerRequests ) ) - registerRequests = [ registerRequests ]; - - if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) - { - timeout = signRequests; - signRequests = null; - } - - if ( !signRequests ) - signRequests = [ ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = registerRequests[ 0 ].appId; - - u2f.register( - appId, registerRequests, signRequests, cbNative, timeout ); - } - else - { - u2f.register( - registerRequests, signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function sign( signRequests, timeout ) - { - var Promise = this; - - if ( !Array.isArray( signRequests ) ) - signRequests = [ signRequests ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = signRequests[ 0 ].appId; - var challenge = signRequests[ 0 ].challenge; - - u2f.sign( appId, challenge, signRequests, cbNative, timeout ); - } - else - { - u2f.sign( signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function makeDefault( func ) - { - API[ func ] = function( ) - { - if ( !commonjsGlobal.Promise ) - // This is very unlikely to ever happen, since browsers - // supporting U2F will most likely support Promises. - throw new Error( "The platform doesn't natively support promises" ); - - var args = [ ].slice.call( arguments ); - return API( commonjsGlobal.Promise )[ func ].apply( null, args ); - }; - } - - // Provide default functions using the built-in Promise if available. - makeDefault( 'isSupported' ); - makeDefault( 'ensureSupport' ); - makeDefault( 'register' ); - makeDefault( 'sign' ); - - var u2fApi$1 = u2fApi; - - var helpers$2 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = exports.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = exports.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - }); - - unwrapExports(helpers$2); - var helpers_1$1 = helpers$2.addCustomErrorDeserializer; - var helpers_2$1 = helpers$2.createCustomErrorClass; - var helpers_3$1 = helpers$2.deserializeError; - var helpers_4$1 = helpers$2.serializeError; - - var lib$3 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughGas = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; - exports.TransportError = TransportError; - exports.getAltStatusMessage = getAltStatusMessage; - exports.TransportStatusError = TransportStatusError; - - - - exports.serializeError = helpers$2.serializeError; - exports.deserializeError = helpers$2.deserializeError; - exports.createCustomErrorClass = helpers$2.createCustomErrorClass; - exports.addCustomErrorDeserializer = helpers$2.addCustomErrorDeserializer; - var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers$2.createCustomErrorClass)("AccountNameRequired"); - var BluetoothRequired = exports.BluetoothRequired = (0, helpers$2.createCustomErrorClass)("BluetoothRequired"); - var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers$2.createCustomErrorClass)("BtcUnmatchedApp"); - var CantOpenDevice = exports.CantOpenDevice = (0, helpers$2.createCustomErrorClass)("CantOpenDevice"); - var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers$2.createCustomErrorClass)("CashAddrNotSupported"); - var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers$2.createCustomErrorClass)("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers$2.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers$2.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers$2.createCustomErrorClass)("DeviceNotGenuine"); - var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers$2.createCustomErrorClass)("DeviceOnDashboardExpected"); - var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers$2.createCustomErrorClass)("DeviceInOSUExpected"); - var DeviceHalted = exports.DeviceHalted = (0, helpers$2.createCustomErrorClass)("DeviceHalted"); - var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers$2.createCustomErrorClass)("DeviceNameInvalid"); - var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers$2.createCustomErrorClass)("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers$2.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers$2.createCustomErrorClass)("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers$2.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = exports.EnpointConfigError = (0, helpers$2.createCustomErrorClass)("EnpointConfig"); - var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers$2.createCustomErrorClass)("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers$2.createCustomErrorClass)("FeeEstimationFailed"); - var HardResetFail = exports.HardResetFail = (0, helpers$2.createCustomErrorClass)("HardResetFail"); - var InvalidAddress = exports.InvalidAddress = (0, helpers$2.createCustomErrorClass)("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers$2.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers$2.createCustomErrorClass)("LatestMCUInstalledError"); - var UnknownMCU = exports.UnknownMCU = (0, helpers$2.createCustomErrorClass)("UnknownMCU"); - var LedgerAPIError = exports.LedgerAPIError = (0, helpers$2.createCustomErrorClass)("LedgerAPIError"); - var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers$2.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers$2.createCustomErrorClass)("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers$2.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers$2.createCustomErrorClass)("ManagerAppRelyOnBTC"); - var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers$2.createCustomErrorClass)("ManagerDeviceLocked"); - var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers$2.createCustomErrorClass)("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers$2.createCustomErrorClass)("ManagerUninstallBTCDep"); - var NetworkDown = exports.NetworkDown = (0, helpers$2.createCustomErrorClass)("NetworkDown"); - var NoAddressesFound = exports.NoAddressesFound = (0, helpers$2.createCustomErrorClass)("NoAddressesFound"); - var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers$2.createCustomErrorClass)("NotEnoughBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers$2.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - var NotEnoughGas = exports.NotEnoughGas = (0, helpers$2.createCustomErrorClass)("NotEnoughGas"); - var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers$2.createCustomErrorClass)("PasswordsDontMatch"); - var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers$2.createCustomErrorClass)("PasswordIncorrect"); - var TimeoutTagged = exports.TimeoutTagged = (0, helpers$2.createCustomErrorClass)("TimeoutTagged"); - var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers$2.createCustomErrorClass)("UnexpectedBootloader"); - var UpdateYourApp = exports.UpdateYourApp = (0, helpers$2.createCustomErrorClass)("UpdateYourApp"); - var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers$2.createCustomErrorClass)("UserRefusedDeviceNameChange"); - var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers$2.createCustomErrorClass)("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers$2.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers$2.createCustomErrorClass)("UserRefusedAllowManager"); - var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers$2.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers$2.createCustomErrorClass)("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers$2.createCustomErrorClass)("TransportInterfaceNotAvailable"); - var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers$2.createCustomErrorClass)("DeviceShouldStayInApp"); - var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers$2.createCustomErrorClass)("WebsocketConnectionError"); - var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers$2.createCustomErrorClass)("WebsocketConnectionFailed"); - var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers$2.createCustomErrorClass)("WrongDeviceForAccount"); - var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers$2.createCustomErrorClass)("ETHAddressNonEIP"); - var CantScanQRCode = exports.CantScanQRCode = (0, helpers$2.createCustomErrorClass)("CantScanQRCode"); - var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers$2.createCustomErrorClass)("FeeNotLoaded"); - var FeeRequired = exports.FeeRequired = (0, helpers$2.createCustomErrorClass)("FeeRequired"); - var SyncError = exports.SyncError = (0, helpers$2.createCustomErrorClass)("SyncError"); - var PairingFailed = exports.PairingFailed = (0, helpers$2.createCustomErrorClass)("PairingFailed"); - var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers$2.createCustomErrorClass)("GenuineCheckFailed"); - var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers$2.createCustomErrorClass)("LedgerAPI4xx"); - var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers$2.createCustomErrorClass)("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers$2.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers$2.createCustomErrorClass)("NoDBPathGiven"); - var DBWrongPassword = exports.DBWrongPassword = (0, helpers$2.createCustomErrorClass)("DBWrongPassword"); - var DBNotReset = exports.DBNotReset = (0, helpers$2.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, helpers$2.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = exports.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, helpers$2.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - }); - - unwrapExports(lib$3); - var lib_1$3 = lib$3.StatusCodes; - var lib_2$3 = lib$3.DBNotReset; - var lib_3$2 = lib$3.DBWrongPassword; - var lib_4$2 = lib$3.NoDBPathGiven; - var lib_5$2 = lib$3.FirmwareOrAppUpdateRequired; - var lib_6$2 = lib$3.LedgerAPI5xx; - var lib_7$2 = lib$3.LedgerAPI4xx; - var lib_8$2 = lib$3.GenuineCheckFailed; - var lib_9$2 = lib$3.PairingFailed; - var lib_10$2 = lib$3.SyncError; - var lib_11$1 = lib$3.FeeRequired; - var lib_12$1 = lib$3.FeeNotLoaded; - var lib_13$1 = lib$3.CantScanQRCode; - var lib_14$1 = lib$3.ETHAddressNonEIP; - var lib_15$1 = lib$3.WrongDeviceForAccount; - var lib_16$1 = lib$3.WebsocketConnectionFailed; - var lib_17$1 = lib$3.WebsocketConnectionError; - var lib_18$1 = lib$3.DeviceShouldStayInApp; - var lib_19$1 = lib$3.TransportInterfaceNotAvailable; - var lib_20$1 = lib$3.TransportOpenUserCancelled; - var lib_21$1 = lib$3.UserRefusedOnDevice; - var lib_22$1 = lib$3.UserRefusedAllowManager; - var lib_23$1 = lib$3.UserRefusedFirmwareUpdate; - var lib_24$1 = lib$3.UserRefusedAddress; - var lib_25$1 = lib$3.UserRefusedDeviceNameChange; - var lib_26$1 = lib$3.UpdateYourApp; - var lib_27$1 = lib$3.UnexpectedBootloader; - var lib_28$1 = lib$3.TimeoutTagged; - var lib_29$1 = lib$3.PasswordIncorrectError; - var lib_30$1 = lib$3.PasswordsDontMatchError; - var lib_31$1 = lib$3.NotEnoughGas; - var lib_32$1 = lib$3.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_33$1 = lib$3.NotEnoughBalance; - var lib_34$1 = lib$3.NoAddressesFound; - var lib_35$1 = lib$3.NetworkDown; - var lib_36$1 = lib$3.ManagerUninstallBTCDep; - var lib_37$1 = lib$3.ManagerNotEnoughSpaceError; - var lib_38$1 = lib$3.ManagerDeviceLockedError; - var lib_39$1 = lib$3.ManagerAppRelyOnBTCError; - var lib_40$1 = lib$3.ManagerAppAlreadyInstalledError; - var lib_41$1 = lib$3.LedgerAPINotAvailable; - var lib_42$1 = lib$3.LedgerAPIErrorWithMessage; - var lib_43$1 = lib$3.LedgerAPIError; - var lib_44$1 = lib$3.UnknownMCU; - var lib_45$1 = lib$3.LatestMCUInstalledError; - var lib_46$1 = lib$3.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_47$1 = lib$3.InvalidAddress; - var lib_48$1 = lib$3.HardResetFail; - var lib_49$1 = lib$3.FeeEstimationFailed; - var lib_50$1 = lib$3.EthAppPleaseEnableContractData; - var lib_51$1 = lib$3.EnpointConfigError; - var lib_52$1 = lib$3.DisconnectedDeviceDuringOperation; - var lib_53$1 = lib$3.DisconnectedDevice; - var lib_54$1 = lib$3.DeviceSocketNoBulkStatus; - var lib_55$1 = lib$3.DeviceSocketFail; - var lib_56$1 = lib$3.DeviceNameInvalid; - var lib_57$1 = lib$3.DeviceHalted; - var lib_58$1 = lib$3.DeviceInOSUExpected; - var lib_59$1 = lib$3.DeviceOnDashboardExpected; - var lib_60$1 = lib$3.DeviceNotGenuineError; - var lib_61$1 = lib$3.DeviceGenuineSocketEarlyClose; - var lib_62$1 = lib$3.DeviceAppVerifyNotSupported; - var lib_63$1 = lib$3.CurrencyNotSupported; - var lib_64$1 = lib$3.CashAddrNotSupported; - var lib_65$1 = lib$3.CantOpenDevice; - var lib_66$1 = lib$3.BtcUnmatchedApp; - var lib_67$1 = lib$3.BluetoothRequired; - var lib_68$1 = lib$3.AccountNameRequiredError; - var lib_69$1 = lib$3.addCustomErrorDeserializer; - var lib_70$1 = lib$3.createCustomErrorClass; - var lib_71$1 = lib$3.deserializeError; - var lib_72$1 = lib$3.serializeError; - var lib_73$1 = lib$3.TransportError; - var lib_74$1 = lib$3.getAltStatusMessage; - var lib_75$1 = lib$3.TransportStatusError; - - var Transport_1$1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _events3 = _interopRequireDefault(EventEmitter); - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - exports.TransportError = lib$3.TransportError; - exports.TransportStatusError = lib$3.TransportStatusError; - exports.StatusCodes = lib$3.StatusCodes; - exports.getAltStatusMessage = lib$3.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib$3.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new lib$3.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new lib$3.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new lib$3.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new lib$3.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new lib$3.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new lib$3.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; - - }); - - unwrapExports(Transport_1$1); - var Transport_2$1 = Transport_1$1.getAltStatusMessage; - var Transport_3$1 = Transport_1$1.StatusCodes; - var Transport_4$1 = Transport_1$1.TransportStatusError; - var Transport_5$1 = Transport_1$1.TransportError; - - var TransportU2F_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - - - var _hwTransport2 = _interopRequireDefault(Transport_1$1); - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - function wrapU2FTransportError(originalError, message, id) { - var err = new lib$3.TransportError(message, id); - // $FlowFixMe - err.originalError = originalError; - return err; - } - - function wrapApdu(apdu, key) { - var result = Buffer.alloc(apdu.length); - for (var i = 0; i < apdu.length; i++) { - result[i] = apdu[i] ^ key[i % key.length]; - } - return result; - } - - // Convert from normal to web-safe, strip trailing "="s - var webSafe64 = function webSafe64(base64) { - return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); - }; - - // Convert from web-safe to normal, add trailing "="s - var normal64 = function normal64(base64) { - return base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); - }; - - function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { - var keyHandle = wrapApdu(apdu, scrambleKey); - var challenge = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); - var signRequest = { - version: "U2F_V2", - keyHandle: webSafe64(keyHandle.toString("base64")), - challenge: webSafe64(challenge.toString("base64")), - appId: location.origin - }; - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); - return (0, u2fApi$1.sign)(signRequest, timeoutMillis / 1000).then(function (response) { - var signatureData = response.signatureData; - - if (typeof signatureData === "string") { - var data = Buffer.from(normal64(signatureData), "base64"); - var result = void 0; - if (!unwrap) { - result = data; - } else { - result = data.slice(5); - } - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return result; - } else { - throw response; - } - }); - } - - var transportInstances = []; - - function emitDisconnect() { - transportInstances.forEach(function (t) { - return t.emit("disconnect"); - }); - transportInstances = []; - } - - function isTimeoutU2FError(u2fError) { - return u2fError.metaData.code === 5; - } - - /** - * U2F web Transport implementation - * @example - * import TransportU2F from "@ledgerhq/hw-transport-u2f"; - * ... - * TransportU2F.create().then(transport => ...) - */ - - var TransportU2F = function (_Transport) { - _inherits(TransportU2F, _Transport); - - _createClass(TransportU2F, null, [{ - key: "open", - - - /** - * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) - */ - - - /* - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_) { - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", new TransportU2F()); - - case 1: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function open(_x) { - return _ref.apply(this, arguments); - } - - return open; - }() - - /* - */ - - }]); - - function TransportU2F() { - _classCallCheck(this, TransportU2F); - - var _this = _possibleConstructorReturn(this, (TransportU2F.__proto__ || Object.getPrototypeOf(TransportU2F)).call(this)); - - _this.unwrap = true; - - transportInstances.push(_this); - return _this; - } - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - - _createClass(TransportU2F, [{ - key: "exchange", - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(apdu) { - var isU2FError; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.prev = 0; - _context2.next = 3; - return attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); - - case 3: - return _context2.abrupt("return", _context2.sent); - - case 6: - _context2.prev = 6; - _context2.t0 = _context2["catch"](0); - isU2FError = _typeof(_context2.t0.metaData) === "object"; - - if (!isU2FError) { - _context2.next = 14; - break; - } - - if (isTimeoutU2FError(_context2.t0)) { - emitDisconnect(); - } - // the wrapping make error more usable and "printable" to the end user. - throw wrapU2FTransportError(_context2.t0, "Failed to sign with Ledger device: U2F " + _context2.t0.metaData.type, "U2F_" + _context2.t0.metaData.code); - - case 14: - throw _context2.t0; - - case 15: - case "end": - return _context2.stop(); - } - } - }, _callee2, this, [[0, 6]]); - })); - - function exchange(_x3) { - return _ref2.apply(this, arguments); - } - - return exchange; - }() - - /** - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer.from(scrambleKey, "ascii"); - } - - /** - */ - - }, { - key: "setUnwrap", - value: function setUnwrap(unwrap) { - this.unwrap = unwrap; - } - }, { - key: "close", - value: function close() { - // u2f have no way to clean things up - return Promise.resolve(); - } - }]); - - return TransportU2F; - }(_hwTransport2.default); - - TransportU2F.isSupported = u2fApi$1.isSupported; - - TransportU2F.list = function () { - return ( - // this transport is not discoverable but we are going to guess if it is here with isSupported() - (0, u2fApi$1.isSupported)().then(function (supported) { - return supported ? [null] : []; - }) - ); - }; - - TransportU2F.listen = function (observer) { - var unsubscribed = false; - (0, u2fApi$1.isSupported)().then(function (supported) { - if (unsubscribed) return; - if (supported) { - observer.next({ type: "add", descriptor: null }); - observer.complete(); - } else { - observer.error(new lib$3.TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); - } - }); - return { - unsubscribe: function unsubscribe() { - unsubscribed = true; - } - }; - }; - - exports.default = TransportU2F; - - }); - - var TransportU2F = unwrapExports(TransportU2F_1); - - var TransportU2F$1 = /*#__PURE__*/Object.freeze({ - default: TransportU2F, - __moduleExports: TransportU2F_1 - }); - - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop() {} - - var on = noop; - var addListener = noop; - var once = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; - - function binding(name) { - throw new Error('process.binding is not supported'); - } - - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - - var process = { - nextTick: nextTick, - title: title, - browser: browser, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - var inherits; - if (typeof Object.create === 'function'){ - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$1 = inherits; - - // Copyright Joyent, Inc. and other Node contributors. - var formatRegExp = /%[sdj%]/g; - function format(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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - 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 debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, 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 - _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); - } - - // 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 !== 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 length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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()`. - function isArray(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - - function isNull(arg) { - return arg === null; - } - - function isNullOrUndefined(arg) { - return arg == null; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isString(arg) { - return typeof arg === 'string'; - } - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - - function isBuffer(maybeBuf) { - return Buffer.isBuffer(maybeBuf); - } - - 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 - function log() { - console.log('%s - %s', timestamp(), format.apply(null, arguments)); - } - - function _extend(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 require$$0$1 = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray, - inspect: inspect, - deprecate: deprecate, - format: format, - debuglog: debuglog - } - - var inherits_browser = createCommonjsModule(function (module) { - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, 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) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - }); - - var inherits$2 = createCommonjsModule(function (module) { - try { - var util = require$$0$1; - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; - } catch (e) { - module.exports = inherits_browser; - } - }); - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } - - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - 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]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') - } - - function read (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) - } - - function write (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; - } - - var toString = {}.toString; - - var isArray$1 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use 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+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$1.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : true; - - /* - * Export kMaxLength after typed array support is determined. - */ - var _kMaxLength = kMaxLength(); - - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } - - return that - } - - /** - * 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$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer$1.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr - }; - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, 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$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - var actual = that.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') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that - } - - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray$1(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; - } - return Buffer$1.alloc(+length) - } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var 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$1.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$1.concat = function concat (list, length) { - if (!isArray$1(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer$1.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - 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 utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer$1.byteLength = byteLength; - - function slowToString (encoding, start, end) { - var 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 coersion 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; - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$1.prototype._isBuffer = true; - - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this - }; - - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this - }; - - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var 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$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; - - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 - }; - - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' - }; - - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - 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 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var 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 (isNaN(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$1.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(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 (Buffer$1.TYPED_ARRAY_SUPPORT && - 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) { - var indexSize = 1; - var arrLength = arr.length; - var 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$$1 (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read$$1(arr, i) === read$$1(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--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read$$1(arr, i + j) !== read$$1(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(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 latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, 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$1.prototype.write = function write$$1 (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; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var 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'; - - var 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': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(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$1.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 fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var 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 - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray (codePoints) { - var 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". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res - } - - Buffer$1.prototype.slice = function slice (start, end) { - var 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; - - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - 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$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val - }; - - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val - }; - - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; - - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var 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$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var 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$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(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$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var 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$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var 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$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.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; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - 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) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - 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('sourceStart out of bounds') - 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; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.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 (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // 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; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).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 stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var 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) { - var byteArray = []; - for (var 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) { - var c, hi, lo; - var byteArray = []; - for (var 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 toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } - - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } - - var buffer = /*#__PURE__*/Object.freeze({ - INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, - kMaxLength: _kMaxLength, - Buffer: Buffer$1, - SlowBuffer: SlowBuffer, - isBuffer: isBuffer$1 - }); - - var safeBuffer = createCommonjsModule(function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - - 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) - } - - // 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) - }; - }); - var safeBuffer_1 = safeBuffer.Buffer; - - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer$1.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer$1.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - // Copyright Joyent, Inc. and other Node contributors. - var isBufferEncoding = Buffer$1.isEncoding - || function(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 assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } - - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - function StringDecoder(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$1(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - } - - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; - }; - - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; - - StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; - }; - - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } - - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } - - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - - var stringDecoder = /*#__PURE__*/Object.freeze({ - StringDecoder: StringDecoder - }); - - Readable.ReadableState = ReadableState; - - var debug = debuglog('stream'); - inherits$1(Readable, EventEmitter); - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount$1 (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState(options, stream) { - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options && typeof options.read === 'function') this._read = options.read; - - EventEmitter.call(this); - } - - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); - }; - - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; - - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } - - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); - } - - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } - - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; - - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } - - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } - - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; - }; - - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } - - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } - - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); - } - } - - function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); - } - - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } - } - - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; - } - - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false); - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; - }; - - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } - - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } - } - - function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} - } - - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; - }; - - // exposed for testing purposes only. - Readable._fromList = fromList; - - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; - } - - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; - } - - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } - - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } - - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } - - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } - - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } - - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$1(Writable, EventEmitter); - - function nop() {} - - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } - - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable(options) { - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - } - - EventEmitter.call(this); - } - - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; - - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } - - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; - } - - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } - - return ret; - }; - - Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; - }; - - Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$1.from(chunk, encoding); - } - return chunk; - } - - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } - - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } - - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } - - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; - - Writable.prototype._writev = null; - - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; - } - - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } - - inherits$1(Duplex, Readable); - - var keys = Object.keys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); - } - - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - // a transform stream is a readable/writable stream where you do - inherits$1(Transform, Duplex); - - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } - - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) stream.push(data); - - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); - } - - Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; - - Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; - - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - function done(stream, er) { - if (er) return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); - } - - inherits$1(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); - } - - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - inherits$1(Stream, EventEmitter); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform; - Stream.PassThrough = PassThrough; - - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; - - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - - function Stream() { - EventEmitter.call(this); - } - - Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; - - var Buffer$2 = safeBuffer.Buffer; - var Transform$1 = Stream.Transform; - - - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$2.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } - - function HashBase (blockSize) { - Transform$1.call(this); - - this._block = Buffer$2.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; - - this._finalized = false; - } - - inherits$2(HashBase, Transform$1); - - HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$2.isBuffer(data)) data = Buffer$2.from(data, encoding); - - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } - - return this - }; - - HashBase.prototype._update = function () { - throw new Error('_update is not implemented') - }; - - HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); - - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; - - return digest - }; - - HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; - - var hashBase = HashBase; - - var Buffer$3 = safeBuffer.Buffer; - - var ARRAY16 = new Array(16); - - function MD5 () { - hashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } - - inherits$2(MD5, hashBase); - - MD5.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; - - MD5.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$3.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; - - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } - - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } - - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } - - function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } - - var md5_js = MD5; - - var Buffer$4 = buffer.Buffer; - - - - var ARRAY16$1 = new Array(16); - - var zl = [ - 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 zr = [ - 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 sl = [ - 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 sr = [ - 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 - ]; - - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - - function RIPEMD160 () { - hashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } - - inherits$2(RIPEMD160, hashBase); - - RIPEMD160.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; - - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; - - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } - - al = el; - el = dl; - dl = rotl$1(cl, 10); - cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; - } - - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer$$1 = Buffer$4.alloc ? Buffer$4.alloc(20) : new Buffer$4(20); - buffer$$1.writeInt32LE(this._a, 0); - buffer$$1.writeInt32LE(this._b, 4); - buffer$$1.writeInt32LE(this._c, 8); - buffer$$1.writeInt32LE(this._d, 12); - buffer$$1.writeInt32LE(this._e, 16); - return buffer$$1 - }; - - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } - - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } - - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } - - var ripemd160 = RIPEMD160; - - var Buffer$5 = safeBuffer.Buffer; - - // prototype class for hash functions - function Hash (blockSize, finalSize) { - this._block = Buffer$5.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } - - Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$5.from(data, enc); - } - - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); - } - } - - this._len += length; - return this - }; - - Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); - - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } - - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; - - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } - - this._update(this._block); - var hash = this._hash(); - - return enc ? hash.toString(enc) : hash - }; - - Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; - - var hash = Hash; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - - - - var Buffer$6 = safeBuffer.Buffer; - - var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W = new Array(80); - - function Sha () { - this.init(); - this._w = W; - - hash.call(this, 64, 56); - } - - inherits$2(Sha, hash); - - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } - - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - - - - var Buffer$7 = safeBuffer.Buffer; - - var K$1 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$1 = new Array(80); - - function Sha1 () { - this.init(); - this._w = W$1; - - hash.call(this, 64, 56); - } - - inherits$2(Sha1, hash); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } - - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } - - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$1[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha1 = Sha1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - - - var Buffer$8 = safeBuffer.Buffer; - - var K$2 = [ - 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 W$2 = new Array(64); - - function Sha256 () { - this.init(); - - this._w = W$2; // new Array(64) - - hash.call(this, 64, 56); - } - - inherits$2(Sha256, hash); - - Sha256.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this - }; - - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } - - function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } - - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } - - Sha256.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0(a) + maj(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); - - return H - }; - - var sha256 = Sha256; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - - - - var Buffer$9 = safeBuffer.Buffer; - - var W$3 = new Array(64); - - function Sha224 () { - this.init(); - - this._w = W$3; // new Array(64) - - hash.call(this, 64, 56); - } - - inherits$2(Sha224, sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this - }; - - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - - return H - }; - - var sha224 = Sha224; - - var Buffer$10 = safeBuffer.Buffer; - - var K$3 = [ - 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 W$4 = new Array(160); - - function Sha512 () { - this.init(); - this._w = W$4; - - hash.call(this, 128, 112); - } - - inherits$2(Sha512, hash); - - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; - - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - - return this - }; - - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0$1 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } - - function sigma1$1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } - - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } - - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } - - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } - - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } - - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } - - Sha512.prototype._update = function (M) { - var W = this._w; - - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; - - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - - W[i] = Wih; - W[i + 1] = Wil; - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj$1(ah, bh, ch); - var majl = maj$1(al, bl, cl); - - var sigma0h = sigma0$1(ah, al); - var sigma0l = sigma0$1(al, ah); - var sigma1h = sigma1$1(eh, el); - var sigma1l = sigma1$1(el, eh); - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$3[j]; - var Kil = K$3[j + 1]; - - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function () { - var H = Buffer$10.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; - - var sha512 = Sha512; - - var Buffer$11 = safeBuffer.Buffer; - - var W$5 = new Array(160); - - function Sha384 () { - this.init(); - this._w = W$5; - - hash.call(this, 128, 112); - } - - inherits$2(Sha384, sha512); - - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; - - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - - return this - }; - - Sha384.prototype._hash = function () { - var H = Buffer$11.allocUnsafe(48); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; - - var sha_js = createCommonjsModule(function (module) { - var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); - - var Algorithm = exports[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() - }; - - exports.sha = sha; - exports.sha1 = sha1; - exports.sha224 = sha224; - exports.sha256 = sha256; - exports.sha384 = sha384; - exports.sha512 = sha512; - }); - - var Buffer$12 = safeBuffer.Buffer; - var Transform$2 = Stream.Transform; - var StringDecoder$1 = stringDecoder.StringDecoder; - - - function CipherBase (hashMode) { - Transform$2.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$2(CipherBase, Transform$2); - - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$12.from(data, inputEnc); - } - - var outData = this._update(data); - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - - return outData - }; - - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; - - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; - - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; - - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer$12.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder$1(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; - - var cipherBase = CipherBase; - - function Hash$1 (hash) { - cipherBase.call(this, 'digest'); - - this._hash = hash; - } - - inherits$2(Hash$1, cipherBase); - - Hash$1.prototype._update = function (data) { - this._hash.update(data); - }; - - Hash$1.prototype._final = function () { - return this._hash.digest() - }; - - var browser$1 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new md5_js() - if (alg === 'rmd160' || alg === 'ripemd160') return new ripemd160() - - return new Hash$1(sha_js(alg)) - }; - - var browser$2 = /*#__PURE__*/Object.freeze({ - default: browser$1, - __moduleExports: browser$1 - }); - - exports.Btc = Btc$1; - exports.TransportWebUSB = TransportWebUSB$1; - exports.TransportU2F = TransportU2F$1; - exports.Log = index$3; - exports.createHash = browser$2; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@ledgerhq/hw-app-btc")):"function"==typeof define&&define.amd?define(["exports","@ledgerhq/hw-app-btc"],r):r(e.NewLedger={},e.hwAppBtc)}(this,(function(e,r){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,r){return e(r={exports:{}},r.exports),r.exports}var a;o((function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.asyncIterator||"@@asyncIterator",i=o.toStringTag||"@@toStringTag";function c(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{c({},"")}catch(e){c=function(e,r,t){return e[r]=t}}function u(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),s=new T(n||[]);return a._invoke=function(e,r,t){var n=d;return function(o,a){if(n===f)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return _()}for(t.method=o,t.arg=a;;){var s=t.delegate;if(s){var i=I(s,t);if(i){if(i===v)continue;return i}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===d)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=f;var c=l(e,r,t);if("normal"===c.type){if(n=t.done?h:p,c.arg===v)continue;return{value:c.arg,done:t.done}}"throw"===c.type&&(n=h,t.method="throw",t.arg=c.arg)}}}(e,t,s),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d="suspendedStart",p="suspendedYield",f="executing",h="completed",v={};function g(){}function m(){}function E(){}var C={};c(C,a,(function(){return this}));var y=Object.getPrototypeOf,w=y&&y(y(L([])));w&&w!==t&&n.call(w,a)&&(C=w);var b=E.prototype=g.prototype=Object.create(C);function D(e){["next","throw","return"].forEach((function(r){c(e,r,(function(e){return this._invoke(r,e)}))}))}function A(e,r){function t(o,a,s,i){var c=l(e[o],e,a);if("throw"!==c.type){var u=c.arg,d=u.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(e){t("next",e,s,i)}),(function(e){t("throw",e,s,i)})):r.resolve(d).then((function(e){u.value=e,s(u)}),(function(e){return t("throw",e,s,i)}))}i(c.arg)}var o;this._invoke=function(e,n){function a(){return new r((function(r,o){t(e,n,r,o)}))}return o=o?o.then(a,a):a()}}function I(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,I(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function S(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function N(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function L(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,s=function t(){for(;++o=0;--a){var s=this.tryEntries[a],i=s.completion;if("root"===s.tryLoc)return o("end");if(s.tryLoc<=this.prev){var c=n.call(s,"catchLoc"),u=n.call(s,"finallyLoc");if(c&&u){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),N(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;N(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:L(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}));function s(){}function i(){i.init.call(this)}function c(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function u(e,r,t){if(r)e.call(t);else for(var n=e.length,o=m(e,n),a=0;a0&&i.length>o){i.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=r,l.count=i.length,u=l,"function"==typeof console.warn?console.warn(u):console.log(u)}}else i=a[r]=t,++e._eventsCount;return e}function v(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function g(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function m(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}s.prototype=Object.create(null),i.EventEmitter=i,i.usingDomains=!1,i.prototype.domain=void 0,i.prototype._events=void 0,i.prototype._maxListeners=void 0,i.defaultMaxListeners=10,i.init=function(){this.domain=null,i.usingDomains&&a.active&&a.Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(e){var r,t,n,o,a,s,i,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(i=this.domain,c){if(r=arguments[1],!i){if(r instanceof Error)throw r;var h=new Error('Uncaught, unspecified "error" event. ('+r+")");throw h.context=r,h}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=i,r.domainThrown=!1,i.emit("error",r),!1}if(!(t=s[e]))return!1;var v="function"==typeof t;switch(n=arguments.length){case 1:u(t,v,this);break;case 2:l(t,v,this,arguments[1]);break;case 3:d(t,v,this,arguments[1],arguments[2]);break;case 4:p(t,v,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),a=1;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var E=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var s=JSON.parse(r.message);s.message&&s.name&&(r=s)}catch(e){}var i=void 0;if("string"==typeof r.name){var c=r.name,u=o[c];if(u)i=u(r);else{var l="Error"===c?Error:n[c];l||(console.warn("deserializing an unknown class '"+c+"'"),l=a(c)),i=Object.create(l.prototype);try{for(var d in r)r.hasOwnProperty(d)&&(i[d]=r[d])}catch(e){}}}else i=new Error(r.message);return!i.stack&&Error.captureStackTrace&&Error.captureStackTrace(i,e),i}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?s(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e};function s(e,r){var n={};r.push(e);var o=!0,a=!1,i=void 0;try{for(var c,u=Object.keys(e)[Symbol.iterator]();!(o=(c=u.next()).done);o=!0){var l=c.value,d=e[l];"function"!=typeof d&&(d&&"object"===(void 0===d?"undefined":t(d))?-1!==r.indexOf(e[l])?n[l]="[Circular]":n[l]=s(e[l],r.slice(0)):n[l]=d)}}catch(e){a=!0,i=e}finally{try{!o&&u.return&&u.return()}finally{if(a)throw i}}return"string"==typeof e.name&&(n.name=e.name),"string"==typeof e.message&&(n.message=e.message),"string"==typeof e.stack&&(n.stack=e.stack),n}}));n(E);E.addCustomErrorDeserializer,E.createCustomErrorClass,E.deserializeError,E.serializeError;var C=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=E.serializeError,r.deserializeError=E.deserializeError,r.createCustomErrorClass=E.createCustomErrorClass,r.addCustomErrorDeserializer=E.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,E.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,E.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,E.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,E.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,E.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,E.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,E.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,E.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,E.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,E.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,E.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,E.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,E.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,E.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,E.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,E.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,E.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,E.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,E.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,E.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,E.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,E.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,E.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,E.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,E.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,E.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,E.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,E.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,E.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,E.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,E.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,E.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,E.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,E.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,E.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,E.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,E.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,E.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,E.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,E.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,E.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,E.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,E.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,E.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,E.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,E.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,E.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,E.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,E.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,E.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,E.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,E.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,E.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,E.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,E.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,E.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,E.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,E.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,E.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,E.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,E.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,E.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,E.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,E.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,E.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,E.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,E.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,E.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,E.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,E.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,E.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,E.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,E.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,E.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,E.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,E.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,E.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,E.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,E.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,E.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,E.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,E.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,E.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportError",(function(e){return new t(e.message,e.id)}));var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find((function(r){return n[r]===e}))||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportStatusError",(function(e){return new a(e.statusCode)}))}));n(C);C.StatusCodes,C.DBNotReset,C.DBWrongPassword,C.NoDBPathGiven,C.FirmwareOrAppUpdateRequired,C.LedgerAPI5xx,C.LedgerAPI4xx,C.GenuineCheckFailed,C.PairingFailed,C.SyncError,C.FeeTooHigh,C.FeeRequired,C.FeeNotLoaded,C.CantScanQRCode,C.ETHAddressNonEIP,C.WrongAppForCurrency,C.WrongDeviceForAccount,C.WebsocketConnectionFailed,C.WebsocketConnectionError,C.DeviceShouldStayInApp,C.TransportWebUSBGestureRequired,C.TransportInterfaceNotAvailable,C.TransportOpenUserCancelled,C.UserRefusedOnDevice,C.UserRefusedAllowManager,C.UserRefusedFirmwareUpdate,C.UserRefusedAddress,C.UserRefusedDeviceNameChange,C.UpdateYourApp,C.UnavailableTezosOriginatedAccountSend,C.UnavailableTezosOriginatedAccountReceive,C.RecipientRequired,C.MCUNotGenuineToDashboard,C.UnexpectedBootloader,C.TimeoutTagged,C.RecommendUndelegation,C.RecommendSubAccountsToEmpty,C.PasswordIncorrectError,C.PasswordsDontMatchError,C.GasLessThanEstimate,C.NotSupportedLegacyAddress,C.NotEnoughGas,C.NoAccessToCamera,C.NotEnoughBalanceBecauseDestinationNotCreated,C.NotEnoughSpendableBalance,C.NotEnoughBalanceInParentAccount,C.NotEnoughBalanceToDelegate,C.NotEnoughBalance,C.NoAddressesFound,C.NetworkDown,C.ManagerUninstallBTCDep,C.ManagerNotEnoughSpaceError,C.ManagerFirmwareNotEnoughSpaceError,C.ManagerDeviceLockedError,C.ManagerAppDepUninstallRequired,C.ManagerAppDepInstallRequired,C.ManagerAppRelyOnBTCError,C.ManagerAppAlreadyInstalledError,C.LedgerAPINotAvailable,C.LedgerAPIErrorWithMessage,C.LedgerAPIError,C.UnknownMCU,C.LatestMCUInstalledError,C.InvalidAddressBecauseDestinationIsAlsoSource,C.InvalidAddress,C.InvalidXRPTag,C.HardResetFail,C.FeeEstimationFailed,C.EthAppPleaseEnableContractData,C.EnpointConfigError,C.DisconnectedDeviceDuringOperation,C.DisconnectedDevice,C.DeviceSocketNoBulkStatus,C.DeviceSocketFail,C.DeviceNameInvalid,C.DeviceHalted,C.DeviceInOSUExpected,C.DeviceOnDashboardUnexpected,C.DeviceOnDashboardExpected,C.DeviceNotGenuineError,C.DeviceGenuineSocketEarlyClose,C.DeviceAppVerifyNotSupported,C.CurrencyNotSupported,C.CashAddrNotSupported,C.CantOpenDevice,C.BtcUnmatchedApp,C.BluetoothRequired,C.AmountRequired,C.AccountNotSupported,C.AccountNameRequiredError,C.addCustomErrorDeserializer,C.createCustomErrorClass,C.deserializeError,C.serializeError,C.TransportError,C.getAltStatusMessage,C.TransportStatusError;var y=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[C.StatusCodes.OK];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(c.length>=256)){e.next=2;break}throw new C.TransportError("data.length exceed 256 bytes limit. Got: "+c.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([c.length]),c]));case 4:if(s=e.sent,i=s.readUInt16BE(s.length-2),u.some((function(e){return e===i}))){e.next=8;break}throw new C.TransportStatusError(i);case 8:return e.abrupt("return",s);case 9:case"end":return e.stop()}}),e,n)}))),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=s(regeneratorRuntime.mark((function e(r){var t,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new C.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise((function(e){t=e})),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}}),e,n,[[5,,10,14]])}))),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise((function(n,o){var a=!1,s=e.listen({next:function(t){a=!0,s&&s.unsubscribe(),i&&clearTimeout(i),e.open(t.descriptor,r).then(n,o)},error:function(e){i&&clearTimeout(i),o(e)},complete:function(){i&&clearTimeout(i),a||o(new C.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),i=t?setTimeout((function(){s.unsubscribe(),o(new C.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))}),t):null}))}}]),e}();c.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",c.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=c}));n(y);y.getAltStatusMessage,y.StatusCodes,y.TransportStatusError,y.TransportError;var w=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),s=r-5,i=Math.ceil(a.length/s);a=Buffer.concat([a,Buffer.alloc(i*s-a.length+1).fill(0)]);for(var c=[],u=0;us&&(a=a.slice(0,s)),{data:a,dataLength:s,sequence:i}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}}));n(w);var b=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find((function(e){return e.productIdMM===t}))},r.identifyProductName=function(e){var r=o[e];return a.find((function(e){return e.id===r}))},[]),i={};for(var c in n){var u=n[c],l=u.bluetoothSpec;if(l)for(var d=0;d0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)});function i(e){return function(){var r=e.apply(this,arguments);return new Promise((function(e,t){return function n(o,a){try{var s=r[o](a),i=s.value}catch(e){return void t(e)}if(!s.done)return Promise.resolve(i).then((function(e){n("next",e)}),(function(e){n("throw",e)}));e(i)}("next")}))}}var c=[{vendorId:b.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}}));n(A);A.isSupported,A.getFirstLedgerDevice,A.getLedgerDevices,A.requestLedgerDevice;var I=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),s=(0,o.default)(n,a),i=s.makeBlocks(r),c=0;case 5:if(!(c "+i[c].toString("hex")),t.next=9,e.device.transferOut(3,i[c]);case 9:c++,t.next=5;break;case 12:u=void 0,l=void 0;case 14:if(u=s.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:d=t.sent,p=Buffer.from(d.data.buffer),(0,D.log)("hid-frame","<= "+p.toString("hex")),l=s.reduceResponse(l,p),t.next=14;break;case 23:return(0,D.log)("apdu","<= "+u.toString("hex")),t.abrupt("return",u);case 25:case"end":return t.stop()}}),t,e)})))).catch((function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new C.DisconnectedDeviceDuringOperation(r.message);throw r}))}};r.default=i})),S=n(I),N=Object.freeze({default:S,__moduleExports:I});e.Btc=r,e.TransportWebUSB=N,Object.defineProperty(e,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; -window.TransportWebUSB = NewLedger.TransportWebUSB.default; -window.TransportU2F = NewLedger.TransportU2F.default; -window.Log = NewLedger.Log.default; -window.createHash = NewLedger.createHash.default; +window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 7491e47e0da7c459291ed9231c667a24b3ac6bda Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 19:04:01 +1100 Subject: [PATCH 03/78] temporary bypass --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index c08dade8..ca271e12 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -729,7 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],!isPeercoin,isPeercoin),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],!isPeercoin,!isPeercoin),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From 12e9664677d2b0569fdd5cb582cce2f4741f6676 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 20:20:52 +1100 Subject: [PATCH 04/78] one more export --- js/ledger.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index c4cd5781..863b1b4a 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,7 +2,7 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@ledgerhq/hw-app-btc")):"function"==typeof define&&define.amd?define(["exports","@ledgerhq/hw-app-btc"],r):r(e.NewLedger={},e.hwAppBtc)}(this,(function(e,r){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,r){return e(r={exports:{}},r.exports),r.exports}var a;o((function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.asyncIterator||"@@asyncIterator",i=o.toStringTag||"@@toStringTag";function c(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{c({},"")}catch(e){c=function(e,r,t){return e[r]=t}}function u(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),s=new T(n||[]);return a._invoke=function(e,r,t){var n=d;return function(o,a){if(n===f)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return _()}for(t.method=o,t.arg=a;;){var s=t.delegate;if(s){var i=I(s,t);if(i){if(i===v)continue;return i}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===d)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=f;var c=l(e,r,t);if("normal"===c.type){if(n=t.done?h:p,c.arg===v)continue;return{value:c.arg,done:t.done}}"throw"===c.type&&(n=h,t.method="throw",t.arg=c.arg)}}}(e,t,s),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d="suspendedStart",p="suspendedYield",f="executing",h="completed",v={};function g(){}function m(){}function E(){}var C={};c(C,a,(function(){return this}));var y=Object.getPrototypeOf,w=y&&y(y(L([])));w&&w!==t&&n.call(w,a)&&(C=w);var b=E.prototype=g.prototype=Object.create(C);function D(e){["next","throw","return"].forEach((function(r){c(e,r,(function(e){return this._invoke(r,e)}))}))}function A(e,r){function t(o,a,s,i){var c=l(e[o],e,a);if("throw"!==c.type){var u=c.arg,d=u.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(e){t("next",e,s,i)}),(function(e){t("throw",e,s,i)})):r.resolve(d).then((function(e){u.value=e,s(u)}),(function(e){return t("throw",e,s,i)}))}i(c.arg)}var o;this._invoke=function(e,n){function a(){return new r((function(r,o){t(e,n,r,o)}))}return o=o?o.then(a,a):a()}}function I(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,I(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function S(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function N(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function L(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,s=function t(){for(;++o=0;--a){var s=this.tryEntries[a],i=s.completion;if("root"===s.tryLoc)return o("end");if(s.tryLoc<=this.prev){var c=n.call(s,"catchLoc"),u=n.call(s,"finallyLoc");if(c&&u){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),N(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;N(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:L(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}));function s(){}function i(){i.init.call(this)}function c(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function u(e,r,t){if(r)e.call(t);else for(var n=e.length,o=m(e,n),a=0;a0&&i.length>o){i.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=r,l.count=i.length,u=l,"function"==typeof console.warn?console.warn(u):console.log(u)}}else i=a[r]=t,++e._eventsCount;return e}function v(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function g(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function m(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}s.prototype=Object.create(null),i.EventEmitter=i,i.usingDomains=!1,i.prototype.domain=void 0,i.prototype._events=void 0,i.prototype._maxListeners=void 0,i.defaultMaxListeners=10,i.init=function(){this.domain=null,i.usingDomains&&a.active&&a.Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(e){var r,t,n,o,a,s,i,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(i=this.domain,c){if(r=arguments[1],!i){if(r instanceof Error)throw r;var h=new Error('Uncaught, unspecified "error" event. ('+r+")");throw h.context=r,h}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=i,r.domainThrown=!1,i.emit("error",r),!1}if(!(t=s[e]))return!1;var v="function"==typeof t;switch(n=arguments.length){case 1:u(t,v,this);break;case 2:l(t,v,this,arguments[1]);break;case 3:d(t,v,this,arguments[1],arguments[2]);break;case 4:p(t,v,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),a=1;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var E=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var s=JSON.parse(r.message);s.message&&s.name&&(r=s)}catch(e){}var i=void 0;if("string"==typeof r.name){var c=r.name,u=o[c];if(u)i=u(r);else{var l="Error"===c?Error:n[c];l||(console.warn("deserializing an unknown class '"+c+"'"),l=a(c)),i=Object.create(l.prototype);try{for(var d in r)r.hasOwnProperty(d)&&(i[d]=r[d])}catch(e){}}}else i=new Error(r.message);return!i.stack&&Error.captureStackTrace&&Error.captureStackTrace(i,e),i}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?s(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e};function s(e,r){var n={};r.push(e);var o=!0,a=!1,i=void 0;try{for(var c,u=Object.keys(e)[Symbol.iterator]();!(o=(c=u.next()).done);o=!0){var l=c.value,d=e[l];"function"!=typeof d&&(d&&"object"===(void 0===d?"undefined":t(d))?-1!==r.indexOf(e[l])?n[l]="[Circular]":n[l]=s(e[l],r.slice(0)):n[l]=d)}}catch(e){a=!0,i=e}finally{try{!o&&u.return&&u.return()}finally{if(a)throw i}}return"string"==typeof e.name&&(n.name=e.name),"string"==typeof e.message&&(n.message=e.message),"string"==typeof e.stack&&(n.stack=e.stack),n}}));n(E);E.addCustomErrorDeserializer,E.createCustomErrorClass,E.deserializeError,E.serializeError;var C=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=E.serializeError,r.deserializeError=E.deserializeError,r.createCustomErrorClass=E.createCustomErrorClass,r.addCustomErrorDeserializer=E.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,E.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,E.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,E.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,E.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,E.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,E.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,E.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,E.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,E.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,E.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,E.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,E.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,E.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,E.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,E.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,E.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,E.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,E.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,E.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,E.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,E.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,E.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,E.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,E.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,E.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,E.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,E.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,E.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,E.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,E.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,E.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,E.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,E.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,E.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,E.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,E.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,E.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,E.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,E.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,E.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,E.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,E.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,E.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,E.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,E.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,E.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,E.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,E.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,E.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,E.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,E.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,E.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,E.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,E.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,E.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,E.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,E.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,E.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,E.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,E.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,E.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,E.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,E.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,E.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,E.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,E.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,E.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,E.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,E.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,E.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,E.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,E.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,E.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,E.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,E.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,E.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,E.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,E.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,E.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,E.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,E.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,E.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,E.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportError",(function(e){return new t(e.message,e.id)}));var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find((function(r){return n[r]===e}))||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportStatusError",(function(e){return new a(e.statusCode)}))}));n(C);C.StatusCodes,C.DBNotReset,C.DBWrongPassword,C.NoDBPathGiven,C.FirmwareOrAppUpdateRequired,C.LedgerAPI5xx,C.LedgerAPI4xx,C.GenuineCheckFailed,C.PairingFailed,C.SyncError,C.FeeTooHigh,C.FeeRequired,C.FeeNotLoaded,C.CantScanQRCode,C.ETHAddressNonEIP,C.WrongAppForCurrency,C.WrongDeviceForAccount,C.WebsocketConnectionFailed,C.WebsocketConnectionError,C.DeviceShouldStayInApp,C.TransportWebUSBGestureRequired,C.TransportInterfaceNotAvailable,C.TransportOpenUserCancelled,C.UserRefusedOnDevice,C.UserRefusedAllowManager,C.UserRefusedFirmwareUpdate,C.UserRefusedAddress,C.UserRefusedDeviceNameChange,C.UpdateYourApp,C.UnavailableTezosOriginatedAccountSend,C.UnavailableTezosOriginatedAccountReceive,C.RecipientRequired,C.MCUNotGenuineToDashboard,C.UnexpectedBootloader,C.TimeoutTagged,C.RecommendUndelegation,C.RecommendSubAccountsToEmpty,C.PasswordIncorrectError,C.PasswordsDontMatchError,C.GasLessThanEstimate,C.NotSupportedLegacyAddress,C.NotEnoughGas,C.NoAccessToCamera,C.NotEnoughBalanceBecauseDestinationNotCreated,C.NotEnoughSpendableBalance,C.NotEnoughBalanceInParentAccount,C.NotEnoughBalanceToDelegate,C.NotEnoughBalance,C.NoAddressesFound,C.NetworkDown,C.ManagerUninstallBTCDep,C.ManagerNotEnoughSpaceError,C.ManagerFirmwareNotEnoughSpaceError,C.ManagerDeviceLockedError,C.ManagerAppDepUninstallRequired,C.ManagerAppDepInstallRequired,C.ManagerAppRelyOnBTCError,C.ManagerAppAlreadyInstalledError,C.LedgerAPINotAvailable,C.LedgerAPIErrorWithMessage,C.LedgerAPIError,C.UnknownMCU,C.LatestMCUInstalledError,C.InvalidAddressBecauseDestinationIsAlsoSource,C.InvalidAddress,C.InvalidXRPTag,C.HardResetFail,C.FeeEstimationFailed,C.EthAppPleaseEnableContractData,C.EnpointConfigError,C.DisconnectedDeviceDuringOperation,C.DisconnectedDevice,C.DeviceSocketNoBulkStatus,C.DeviceSocketFail,C.DeviceNameInvalid,C.DeviceHalted,C.DeviceInOSUExpected,C.DeviceOnDashboardUnexpected,C.DeviceOnDashboardExpected,C.DeviceNotGenuineError,C.DeviceGenuineSocketEarlyClose,C.DeviceAppVerifyNotSupported,C.CurrencyNotSupported,C.CashAddrNotSupported,C.CantOpenDevice,C.BtcUnmatchedApp,C.BluetoothRequired,C.AmountRequired,C.AccountNotSupported,C.AccountNameRequiredError,C.addCustomErrorDeserializer,C.createCustomErrorClass,C.deserializeError,C.serializeError,C.TransportError,C.getAltStatusMessage,C.TransportStatusError;var y=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[C.StatusCodes.OK];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(c.length>=256)){e.next=2;break}throw new C.TransportError("data.length exceed 256 bytes limit. Got: "+c.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([c.length]),c]));case 4:if(s=e.sent,i=s.readUInt16BE(s.length-2),u.some((function(e){return e===i}))){e.next=8;break}throw new C.TransportStatusError(i);case 8:return e.abrupt("return",s);case 9:case"end":return e.stop()}}),e,n)}))),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=s(regeneratorRuntime.mark((function e(r){var t,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new C.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise((function(e){t=e})),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}}),e,n,[[5,,10,14]])}))),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise((function(n,o){var a=!1,s=e.listen({next:function(t){a=!0,s&&s.unsubscribe(),i&&clearTimeout(i),e.open(t.descriptor,r).then(n,o)},error:function(e){i&&clearTimeout(i),o(e)},complete:function(){i&&clearTimeout(i),a||o(new C.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),i=t?setTimeout((function(){s.unsubscribe(),o(new C.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))}),t):null}))}}]),e}();c.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",c.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=c}));n(y);y.getAltStatusMessage,y.StatusCodes,y.TransportStatusError,y.TransportError;var w=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),s=r-5,i=Math.ceil(a.length/s);a=Buffer.concat([a,Buffer.alloc(i*s-a.length+1).fill(0)]);for(var c=[],u=0;us&&(a=a.slice(0,s)),{data:a,dataLength:s,sequence:i}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}}));n(w);var b=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find((function(e){return e.productIdMM===t}))},r.identifyProductName=function(e){var r=o[e];return a.find((function(e){return e.id===r}))},[]),i={};for(var c in n){var u=n[c],l=u.bluetoothSpec;if(l)for(var d=0;d0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)});function i(e){return function(){var r=e.apply(this,arguments);return new Promise((function(e,t){return function n(o,a){try{var s=r[o](a),i=s.value}catch(e){return void t(e)}if(!s.done)return Promise.resolve(i).then((function(e){n("next",e)}),(function(e){n("throw",e)}));e(i)}("next")}))}}var c=[{vendorId:b.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}}));n(A);A.isSupported,A.getFirstLedgerDevice,A.getLedgerDevices,A.requestLedgerDevice;var I=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),s=(0,o.default)(n,a),i=s.makeBlocks(r),c=0;case 5:if(!(c "+i[c].toString("hex")),t.next=9,e.device.transferOut(3,i[c]);case 9:c++,t.next=5;break;case 12:u=void 0,l=void 0;case 14:if(u=s.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:d=t.sent,p=Buffer.from(d.data.buffer),(0,D.log)("hid-frame","<= "+p.toString("hex")),l=s.reduceResponse(l,p),t.next=14;break;case 23:return(0,D.log)("apdu","<= "+u.toString("hex")),t.abrupt("return",u);case 25:case"end":return t.stop()}}),t,e)})))).catch((function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new C.DisconnectedDeviceDuringOperation(r.message);throw r}))}};r.default=i})),S=n(I),N=Object.freeze({default:S,__moduleExports:I});e.Btc=r,e.TransportWebUSB=N,Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@backpacker69/hw-app-btc")):"function"==typeof define&&define.amd?define(["exports","@backpacker69/hw-app-btc"],r):r(e.NewLedger={},e.hwAppBtc)}(this,(function(e,r){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,r){return e(r={exports:{}},r.exports),r.exports}var a;o((function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.asyncIterator||"@@asyncIterator",i=o.toStringTag||"@@toStringTag";function c(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{c({},"")}catch(e){c=function(e,r,t){return e[r]=t}}function u(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),s=new T(n||[]);return a._invoke=function(e,r,t){var n=d;return function(o,a){if(n===f)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return _()}for(t.method=o,t.arg=a;;){var s=t.delegate;if(s){var i=I(s,t);if(i){if(i===v)continue;return i}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===d)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=f;var c=l(e,r,t);if("normal"===c.type){if(n=t.done?h:p,c.arg===v)continue;return{value:c.arg,done:t.done}}"throw"===c.type&&(n=h,t.method="throw",t.arg=c.arg)}}}(e,t,s),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d="suspendedStart",p="suspendedYield",f="executing",h="completed",v={};function g(){}function m(){}function E(){}var C={};c(C,a,(function(){return this}));var y=Object.getPrototypeOf,w=y&&y(y(L([])));w&&w!==t&&n.call(w,a)&&(C=w);var b=E.prototype=g.prototype=Object.create(C);function D(e){["next","throw","return"].forEach((function(r){c(e,r,(function(e){return this._invoke(r,e)}))}))}function A(e,r){function t(o,a,s,i){var c=l(e[o],e,a);if("throw"!==c.type){var u=c.arg,d=u.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(e){t("next",e,s,i)}),(function(e){t("throw",e,s,i)})):r.resolve(d).then((function(e){u.value=e,s(u)}),(function(e){return t("throw",e,s,i)}))}i(c.arg)}var o;this._invoke=function(e,n){function a(){return new r((function(r,o){t(e,n,r,o)}))}return o=o?o.then(a,a):a()}}function I(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,I(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function S(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function N(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function L(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,s=function t(){for(;++o=0;--a){var s=this.tryEntries[a],i=s.completion;if("root"===s.tryLoc)return o("end");if(s.tryLoc<=this.prev){var c=n.call(s,"catchLoc"),u=n.call(s,"finallyLoc");if(c&&u){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),N(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;N(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:L(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}));function s(){}function i(){i.init.call(this)}function c(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function u(e,r,t){if(r)e.call(t);else for(var n=e.length,o=m(e,n),a=0;a0&&i.length>o){i.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=r,l.count=i.length,u=l,"function"==typeof console.warn?console.warn(u):console.log(u)}}else i=a[r]=t,++e._eventsCount;return e}function v(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function g(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function m(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}s.prototype=Object.create(null),i.EventEmitter=i,i.usingDomains=!1,i.prototype.domain=void 0,i.prototype._events=void 0,i.prototype._maxListeners=void 0,i.defaultMaxListeners=10,i.init=function(){this.domain=null,i.usingDomains&&a.active&&a.Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(e){var r,t,n,o,a,s,i,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(i=this.domain,c){if(r=arguments[1],!i){if(r instanceof Error)throw r;var h=new Error('Uncaught, unspecified "error" event. ('+r+")");throw h.context=r,h}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=i,r.domainThrown=!1,i.emit("error",r),!1}if(!(t=s[e]))return!1;var v="function"==typeof t;switch(n=arguments.length){case 1:u(t,v,this);break;case 2:l(t,v,this,arguments[1]);break;case 3:d(t,v,this,arguments[1],arguments[2]);break;case 4:p(t,v,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),a=1;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var E=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var s=JSON.parse(r.message);s.message&&s.name&&(r=s)}catch(e){}var i=void 0;if("string"==typeof r.name){var c=r.name,u=o[c];if(u)i=u(r);else{var l="Error"===c?Error:n[c];l||(console.warn("deserializing an unknown class '"+c+"'"),l=a(c)),i=Object.create(l.prototype);try{for(var d in r)r.hasOwnProperty(d)&&(i[d]=r[d])}catch(e){}}}else i=new Error(r.message);return!i.stack&&Error.captureStackTrace&&Error.captureStackTrace(i,e),i}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?s(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e};function s(e,r){var n={};r.push(e);var o=!0,a=!1,i=void 0;try{for(var c,u=Object.keys(e)[Symbol.iterator]();!(o=(c=u.next()).done);o=!0){var l=c.value,d=e[l];"function"!=typeof d&&(d&&"object"===(void 0===d?"undefined":t(d))?-1!==r.indexOf(e[l])?n[l]="[Circular]":n[l]=s(e[l],r.slice(0)):n[l]=d)}}catch(e){a=!0,i=e}finally{try{!o&&u.return&&u.return()}finally{if(a)throw i}}return"string"==typeof e.name&&(n.name=e.name),"string"==typeof e.message&&(n.message=e.message),"string"==typeof e.stack&&(n.stack=e.stack),n}}));n(E);E.addCustomErrorDeserializer,E.createCustomErrorClass,E.deserializeError,E.serializeError;var C=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=E.serializeError,r.deserializeError=E.deserializeError,r.createCustomErrorClass=E.createCustomErrorClass,r.addCustomErrorDeserializer=E.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,E.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,E.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,E.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,E.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,E.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,E.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,E.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,E.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,E.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,E.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,E.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,E.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,E.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,E.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,E.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,E.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,E.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,E.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,E.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,E.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,E.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,E.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,E.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,E.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,E.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,E.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,E.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,E.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,E.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,E.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,E.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,E.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,E.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,E.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,E.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,E.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,E.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,E.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,E.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,E.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,E.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,E.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,E.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,E.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,E.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,E.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,E.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,E.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,E.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,E.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,E.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,E.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,E.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,E.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,E.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,E.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,E.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,E.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,E.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,E.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,E.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,E.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,E.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,E.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,E.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,E.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,E.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,E.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,E.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,E.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,E.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,E.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,E.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,E.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,E.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,E.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,E.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,E.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,E.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,E.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,E.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,E.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,E.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportError",(function(e){return new t(e.message,e.id)}));var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find((function(r){return n[r]===e}))||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportStatusError",(function(e){return new a(e.statusCode)}))}));n(C);C.StatusCodes,C.DBNotReset,C.DBWrongPassword,C.NoDBPathGiven,C.FirmwareOrAppUpdateRequired,C.LedgerAPI5xx,C.LedgerAPI4xx,C.GenuineCheckFailed,C.PairingFailed,C.SyncError,C.FeeTooHigh,C.FeeRequired,C.FeeNotLoaded,C.CantScanQRCode,C.ETHAddressNonEIP,C.WrongAppForCurrency,C.WrongDeviceForAccount,C.WebsocketConnectionFailed,C.WebsocketConnectionError,C.DeviceShouldStayInApp,C.TransportWebUSBGestureRequired,C.TransportInterfaceNotAvailable,C.TransportOpenUserCancelled,C.UserRefusedOnDevice,C.UserRefusedAllowManager,C.UserRefusedFirmwareUpdate,C.UserRefusedAddress,C.UserRefusedDeviceNameChange,C.UpdateYourApp,C.UnavailableTezosOriginatedAccountSend,C.UnavailableTezosOriginatedAccountReceive,C.RecipientRequired,C.MCUNotGenuineToDashboard,C.UnexpectedBootloader,C.TimeoutTagged,C.RecommendUndelegation,C.RecommendSubAccountsToEmpty,C.PasswordIncorrectError,C.PasswordsDontMatchError,C.GasLessThanEstimate,C.NotSupportedLegacyAddress,C.NotEnoughGas,C.NoAccessToCamera,C.NotEnoughBalanceBecauseDestinationNotCreated,C.NotEnoughSpendableBalance,C.NotEnoughBalanceInParentAccount,C.NotEnoughBalanceToDelegate,C.NotEnoughBalance,C.NoAddressesFound,C.NetworkDown,C.ManagerUninstallBTCDep,C.ManagerNotEnoughSpaceError,C.ManagerFirmwareNotEnoughSpaceError,C.ManagerDeviceLockedError,C.ManagerAppDepUninstallRequired,C.ManagerAppDepInstallRequired,C.ManagerAppRelyOnBTCError,C.ManagerAppAlreadyInstalledError,C.LedgerAPINotAvailable,C.LedgerAPIErrorWithMessage,C.LedgerAPIError,C.UnknownMCU,C.LatestMCUInstalledError,C.InvalidAddressBecauseDestinationIsAlsoSource,C.InvalidAddress,C.InvalidXRPTag,C.HardResetFail,C.FeeEstimationFailed,C.EthAppPleaseEnableContractData,C.EnpointConfigError,C.DisconnectedDeviceDuringOperation,C.DisconnectedDevice,C.DeviceSocketNoBulkStatus,C.DeviceSocketFail,C.DeviceNameInvalid,C.DeviceHalted,C.DeviceInOSUExpected,C.DeviceOnDashboardUnexpected,C.DeviceOnDashboardExpected,C.DeviceNotGenuineError,C.DeviceGenuineSocketEarlyClose,C.DeviceAppVerifyNotSupported,C.CurrencyNotSupported,C.CashAddrNotSupported,C.CantOpenDevice,C.BtcUnmatchedApp,C.BluetoothRequired,C.AmountRequired,C.AccountNotSupported,C.AccountNameRequiredError,C.addCustomErrorDeserializer,C.createCustomErrorClass,C.deserializeError,C.serializeError,C.TransportError,C.getAltStatusMessage,C.TransportStatusError;var y=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[C.StatusCodes.OK];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(c.length>=256)){e.next=2;break}throw new C.TransportError("data.length exceed 256 bytes limit. Got: "+c.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([c.length]),c]));case 4:if(s=e.sent,i=s.readUInt16BE(s.length-2),u.some((function(e){return e===i}))){e.next=8;break}throw new C.TransportStatusError(i);case 8:return e.abrupt("return",s);case 9:case"end":return e.stop()}}),e,n)}))),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=s(regeneratorRuntime.mark((function e(r){var t,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new C.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise((function(e){t=e})),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}}),e,n,[[5,,10,14]])}))),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise((function(n,o){var a=!1,s=e.listen({next:function(t){a=!0,s&&s.unsubscribe(),i&&clearTimeout(i),e.open(t.descriptor,r).then(n,o)},error:function(e){i&&clearTimeout(i),o(e)},complete:function(){i&&clearTimeout(i),a||o(new C.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),i=t?setTimeout((function(){s.unsubscribe(),o(new C.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))}),t):null}))}}]),e}();c.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",c.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=c}));n(y);y.getAltStatusMessage,y.StatusCodes,y.TransportStatusError,y.TransportError;var w=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),s=r-5,i=Math.ceil(a.length/s);a=Buffer.concat([a,Buffer.alloc(i*s-a.length+1).fill(0)]);for(var c=[],u=0;us&&(a=a.slice(0,s)),{data:a,dataLength:s,sequence:i}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}}));n(w);var b=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find((function(e){return e.productIdMM===t}))},r.identifyProductName=function(e){var r=o[e];return a.find((function(e){return e.id===r}))},[]),i={};for(var c in n){var u=n[c],l=u.bluetoothSpec;if(l)for(var d=0;d0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)});function i(e){return function(){var r=e.apply(this,arguments);return new Promise((function(e,t){return function n(o,a){try{var s=r[o](a),i=s.value}catch(e){return void t(e)}if(!s.done)return Promise.resolve(i).then((function(e){n("next",e)}),(function(e){n("throw",e)}));e(i)}("next")}))}}var c=[{vendorId:b.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}}));n(A);A.isSupported,A.getFirstLedgerDevice,A.getLedgerDevices,A.requestLedgerDevice;var I=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),s=(0,o.default)(n,a),i=s.makeBlocks(r),c=0;case 5:if(!(c "+i[c].toString("hex")),t.next=9,e.device.transferOut(3,i[c]);case 9:c++,t.next=5;break;case 12:u=void 0,l=void 0;case 14:if(u=s.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:d=t.sent,p=Buffer.from(d.data.buffer),(0,D.log)("hid-frame","<= "+p.toString("hex")),l=s.reduceResponse(l,p),t.next=14;break;case 23:return(0,D.log)("apdu","<= "+u.toString("hex")),t.abrupt("return",u);case 25:case"end":return t.stop()}}),t,e)})))).catch((function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new C.DisconnectedDeviceDuringOperation(r.message);throw r}))}};r.default=i})),S=n(I),N=Object.freeze({default:S,__moduleExports:I});e.Btc=r,e.TransportWebUSB=N,Object.defineProperty(e,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 9410561ddb26460300883373dbffdf5b3aa37bef Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 20:37:17 +1100 Subject: [PATCH 05/78] extra export --- js/ledger.js | 4177 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 4176 insertions(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index 863b1b4a..b06dba2e 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,7 +2,4182 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@backpacker69/hw-app-btc")):"function"==typeof define&&define.amd?define(["exports","@backpacker69/hw-app-btc"],r):r(e.NewLedger={},e.hwAppBtc)}(this,(function(e,r){"use strict";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,r){return e(r={exports:{}},r.exports),r.exports}var a;o((function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.asyncIterator||"@@asyncIterator",i=o.toStringTag||"@@toStringTag";function c(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{c({},"")}catch(e){c=function(e,r,t){return e[r]=t}}function u(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),s=new T(n||[]);return a._invoke=function(e,r,t){var n=d;return function(o,a){if(n===f)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return _()}for(t.method=o,t.arg=a;;){var s=t.delegate;if(s){var i=I(s,t);if(i){if(i===v)continue;return i}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===d)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=f;var c=l(e,r,t);if("normal"===c.type){if(n=t.done?h:p,c.arg===v)continue;return{value:c.arg,done:t.done}}"throw"===c.type&&(n=h,t.method="throw",t.arg=c.arg)}}}(e,t,s),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var d="suspendedStart",p="suspendedYield",f="executing",h="completed",v={};function g(){}function m(){}function E(){}var C={};c(C,a,(function(){return this}));var y=Object.getPrototypeOf,w=y&&y(y(L([])));w&&w!==t&&n.call(w,a)&&(C=w);var b=E.prototype=g.prototype=Object.create(C);function D(e){["next","throw","return"].forEach((function(r){c(e,r,(function(e){return this._invoke(r,e)}))}))}function A(e,r){function t(o,a,s,i){var c=l(e[o],e,a);if("throw"!==c.type){var u=c.arg,d=u.value;return d&&"object"==typeof d&&n.call(d,"__await")?r.resolve(d.__await).then((function(e){t("next",e,s,i)}),(function(e){t("throw",e,s,i)})):r.resolve(d).then((function(e){u.value=e,s(u)}),(function(e){return t("throw",e,s,i)}))}i(c.arg)}var o;this._invoke=function(e,n){function a(){return new r((function(r,o){t(e,n,r,o)}))}return o=o?o.then(a,a):a()}}function I(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,I(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function S(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function N(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function T(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function L(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,s=function t(){for(;++o=0;--a){var s=this.tryEntries[a],i=s.completion;if("root"===s.tryLoc)return o("end");if(s.tryLoc<=this.prev){var c=n.call(s,"catchLoc"),u=n.call(s,"finallyLoc");if(c&&u){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),N(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;N(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:L(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}));function s(){}function i(){i.init.call(this)}function c(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function u(e,r,t){if(r)e.call(t);else for(var n=e.length,o=m(e,n),a=0;a0&&i.length>o){i.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=r,l.count=i.length,u=l,"function"==typeof console.warn?console.warn(u):console.log(u)}}else i=a[r]=t,++e._eventsCount;return e}function v(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function g(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function m(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}s.prototype=Object.create(null),i.EventEmitter=i,i.usingDomains=!1,i.prototype.domain=void 0,i.prototype._events=void 0,i.prototype._maxListeners=void 0,i.defaultMaxListeners=10,i.init=function(){this.domain=null,i.usingDomains&&a.active&&a.Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(e){var r,t,n,o,a,s,i,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(i=this.domain,c){if(r=arguments[1],!i){if(r instanceof Error)throw r;var h=new Error('Uncaught, unspecified "error" event. ('+r+")");throw h.context=r,h}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=i,r.domainThrown=!1,i.emit("error",r),!1}if(!(t=s[e]))return!1;var v="function"==typeof t;switch(n=arguments.length){case 1:u(t,v,this);break;case 2:l(t,v,this,arguments[1]);break;case 3:d(t,v,this,arguments[1],arguments[2]);break;case 4:p(t,v,this,arguments[1],arguments[2],arguments[3]);break;default:for(o=new Array(n-1),a=1;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var E=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var s=JSON.parse(r.message);s.message&&s.name&&(r=s)}catch(e){}var i=void 0;if("string"==typeof r.name){var c=r.name,u=o[c];if(u)i=u(r);else{var l="Error"===c?Error:n[c];l||(console.warn("deserializing an unknown class '"+c+"'"),l=a(c)),i=Object.create(l.prototype);try{for(var d in r)r.hasOwnProperty(d)&&(i[d]=r[d])}catch(e){}}}else i=new Error(r.message);return!i.stack&&Error.captureStackTrace&&Error.captureStackTrace(i,e),i}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?s(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e};function s(e,r){var n={};r.push(e);var o=!0,a=!1,i=void 0;try{for(var c,u=Object.keys(e)[Symbol.iterator]();!(o=(c=u.next()).done);o=!0){var l=c.value,d=e[l];"function"!=typeof d&&(d&&"object"===(void 0===d?"undefined":t(d))?-1!==r.indexOf(e[l])?n[l]="[Circular]":n[l]=s(e[l],r.slice(0)):n[l]=d)}}catch(e){a=!0,i=e}finally{try{!o&&u.return&&u.return()}finally{if(a)throw i}}return"string"==typeof e.name&&(n.name=e.name),"string"==typeof e.message&&(n.message=e.message),"string"==typeof e.stack&&(n.stack=e.stack),n}}));n(E);E.addCustomErrorDeserializer,E.createCustomErrorClass,E.deserializeError,E.serializeError;var C=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=E.serializeError,r.deserializeError=E.deserializeError,r.createCustomErrorClass=E.createCustomErrorClass,r.addCustomErrorDeserializer=E.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,E.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,E.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,E.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,E.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,E.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,E.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,E.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,E.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,E.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,E.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,E.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,E.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,E.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,E.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,E.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,E.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,E.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,E.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,E.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,E.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,E.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,E.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,E.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,E.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,E.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,E.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,E.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,E.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,E.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,E.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,E.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,E.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,E.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,E.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,E.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,E.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,E.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,E.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,E.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,E.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,E.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,E.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,E.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,E.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,E.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,E.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,E.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,E.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,E.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,E.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,E.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,E.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,E.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,E.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,E.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,E.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,E.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,E.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,E.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,E.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,E.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,E.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,E.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,E.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,E.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,E.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,E.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,E.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,E.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,E.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,E.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,E.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,E.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,E.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,E.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,E.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,E.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,E.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,E.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,E.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,E.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,E.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,E.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,E.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,E.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,E.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportError",(function(e){return new t(e.message,e.id)}));var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find((function(r){return n[r]===e}))||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,E.addCustomErrorDeserializer)("TransportStatusError",(function(e){return new a(e.statusCode)}))}));n(C);C.StatusCodes,C.DBNotReset,C.DBWrongPassword,C.NoDBPathGiven,C.FirmwareOrAppUpdateRequired,C.LedgerAPI5xx,C.LedgerAPI4xx,C.GenuineCheckFailed,C.PairingFailed,C.SyncError,C.FeeTooHigh,C.FeeRequired,C.FeeNotLoaded,C.CantScanQRCode,C.ETHAddressNonEIP,C.WrongAppForCurrency,C.WrongDeviceForAccount,C.WebsocketConnectionFailed,C.WebsocketConnectionError,C.DeviceShouldStayInApp,C.TransportWebUSBGestureRequired,C.TransportInterfaceNotAvailable,C.TransportOpenUserCancelled,C.UserRefusedOnDevice,C.UserRefusedAllowManager,C.UserRefusedFirmwareUpdate,C.UserRefusedAddress,C.UserRefusedDeviceNameChange,C.UpdateYourApp,C.UnavailableTezosOriginatedAccountSend,C.UnavailableTezosOriginatedAccountReceive,C.RecipientRequired,C.MCUNotGenuineToDashboard,C.UnexpectedBootloader,C.TimeoutTagged,C.RecommendUndelegation,C.RecommendSubAccountsToEmpty,C.PasswordIncorrectError,C.PasswordsDontMatchError,C.GasLessThanEstimate,C.NotSupportedLegacyAddress,C.NotEnoughGas,C.NoAccessToCamera,C.NotEnoughBalanceBecauseDestinationNotCreated,C.NotEnoughSpendableBalance,C.NotEnoughBalanceInParentAccount,C.NotEnoughBalanceToDelegate,C.NotEnoughBalance,C.NoAddressesFound,C.NetworkDown,C.ManagerUninstallBTCDep,C.ManagerNotEnoughSpaceError,C.ManagerFirmwareNotEnoughSpaceError,C.ManagerDeviceLockedError,C.ManagerAppDepUninstallRequired,C.ManagerAppDepInstallRequired,C.ManagerAppRelyOnBTCError,C.ManagerAppAlreadyInstalledError,C.LedgerAPINotAvailable,C.LedgerAPIErrorWithMessage,C.LedgerAPIError,C.UnknownMCU,C.LatestMCUInstalledError,C.InvalidAddressBecauseDestinationIsAlsoSource,C.InvalidAddress,C.InvalidXRPTag,C.HardResetFail,C.FeeEstimationFailed,C.EthAppPleaseEnableContractData,C.EnpointConfigError,C.DisconnectedDeviceDuringOperation,C.DisconnectedDevice,C.DeviceSocketNoBulkStatus,C.DeviceSocketFail,C.DeviceNameInvalid,C.DeviceHalted,C.DeviceInOSUExpected,C.DeviceOnDashboardUnexpected,C.DeviceOnDashboardExpected,C.DeviceNotGenuineError,C.DeviceGenuineSocketEarlyClose,C.DeviceAppVerifyNotSupported,C.CurrencyNotSupported,C.CashAddrNotSupported,C.CantOpenDevice,C.BtcUnmatchedApp,C.BluetoothRequired,C.AmountRequired,C.AccountNotSupported,C.AccountNameRequiredError,C.addCustomErrorDeserializer,C.createCustomErrorClass,C.deserializeError,C.serializeError,C.TransportError,C.getAltStatusMessage,C.TransportStatusError;var y=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),u=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[C.StatusCodes.OK];return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(c.length>=256)){e.next=2;break}throw new C.TransportError("data.length exceed 256 bytes limit. Got: "+c.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([c.length]),c]));case 4:if(s=e.sent,i=s.readUInt16BE(s.length-2),u.some((function(e){return e===i}))){e.next=8;break}throw new C.TransportStatusError(i);case 8:return e.abrupt("return",s);case 9:case"end":return e.stop()}}),e,n)}))),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=s(regeneratorRuntime.mark((function e(r){var t,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new C.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise((function(e){t=e})),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}}),e,n,[[5,,10,14]])}))),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise((function(n,o){var a=!1,s=e.listen({next:function(t){a=!0,s&&s.unsubscribe(),i&&clearTimeout(i),e.open(t.descriptor,r).then(n,o)},error:function(e){i&&clearTimeout(i),o(e)},complete:function(){i&&clearTimeout(i),a||o(new C.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),i=t?setTimeout((function(){s.unsubscribe(),o(new C.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))}),t):null}))}}]),e}();c.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",c.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=c}));n(y);y.getAltStatusMessage,y.StatusCodes,y.TransportStatusError,y.TransportError;var w=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),s=r-5,i=Math.ceil(a.length/s);a=Buffer.concat([a,Buffer.alloc(i*s-a.length+1).fill(0)]);for(var c=[],u=0;us&&(a=a.slice(0,s)),{data:a,dataLength:s,sequence:i}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}}));n(w);var b=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find((function(e){return e.productIdMM===t}))},r.identifyProductName=function(e){var r=o[e];return a.find((function(e){return e.id===r}))},[]),i={};for(var c in n){var u=n[c],l=u.bluetoothSpec;if(l)for(var d=0;d0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)});function i(e){return function(){var r=e.apply(this,arguments);return new Promise((function(e,t){return function n(o,a){try{var s=r[o](a),i=s.value}catch(e){return void t(e)}if(!s.done)return Promise.resolve(i).then((function(e){n("next",e)}),(function(e){n("throw",e)}));e(i)}("next")}))}}var c=[{vendorId:b.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}}));n(A);A.isSupported,A.getFirstLedgerDevice,A.getLedgerDevices,A.requestLedgerDevice;var I=o((function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),s=(0,o.default)(n,a),i=s.makeBlocks(r),c=0;case 5:if(!(c "+i[c].toString("hex")),t.next=9,e.device.transferOut(3,i[c]);case 9:c++,t.next=5;break;case 12:u=void 0,l=void 0;case 14:if(u=s.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:d=t.sent,p=Buffer.from(d.data.buffer),(0,D.log)("hid-frame","<= "+p.toString("hex")),l=s.reduceResponse(l,p),t.next=14;break;case 23:return(0,D.log)("apdu","<= "+u.toString("hex")),t.abrupt("return",u);case 25:case"end":return t.stop()}}),t,e)})))).catch((function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new C.DisconnectedDeviceDuringOperation(r.message);throw r}))}};r.default=i})),S=n(I),N=Object.freeze({default:S,__moduleExports:I});e.Btc=r,e.TransportWebUSB=N,Object.defineProperty(e,"__esModule",{value:!0})})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.NewLedger = {}))); +}(this, (function (exports) { 'use strict'; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var runtime_1 = createCommonjsModule(function (module) { + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports + )); + + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + Function("r", "regeneratorRuntime = r")(runtime); + } + }); + + var utils = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.defer = defer; + exports.splitPath = splitPath; + exports.eachSeries = eachSeries; + exports.foreach = foreach; + exports.doIf = doIf; + exports.asyncWhile = asyncWhile; + function defer() { + var resolve = void 0, + reject = void 0; + var promise = new Promise(function (success, failure) { + resolve = success; + reject = failure; + }); + if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy + return { promise: promise, resolve: resolve, reject: reject }; + } + + // TODO use bip32-path library + /******************************************************************************** + * Ledger Node JS API + * (c) 2016-2017 Ledger + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ********************************************************************************/ + + + function splitPath(path) { + var result = []; + var components = path.split("/"); + components.forEach(function (element) { + var number = parseInt(element, 10); + if (isNaN(number)) { + return; // FIXME shouldn't it throws instead? + } + if (element.length > 1 && element[element.length - 1] === "'") { + number += 0x80000000; + } + result.push(number); + }); + return result; + } + + // TODO use async await + + function eachSeries(arr, fun) { + return arr.reduce(function (p, e) { + return p.then(function () { + return fun(e); + }); + }, Promise.resolve()); + } + + function foreach(arr, callback) { + function iterate(index, array, result) { + if (index >= array.length) { + return result; + } else return callback(array[index], index).then(function (res) { + result.push(res); + return iterate(index + 1, array, result); + }); + } + return Promise.resolve().then(function () { + return iterate(0, arr, []); + }); + } + + function doIf(condition, callback) { + return Promise.resolve().then(function () { + if (condition) { + return callback(); + } + }); + } + + function asyncWhile(predicate, callback) { + function iterate(result) { + if (!predicate()) { + return result; + } else { + return callback().then(function (res) { + result.push(res); + return iterate(result); + }); + } + } + return Promise.resolve([]).then(iterate); + } + + var isLedgerDevice = exports.isLedgerDevice = function isLedgerDevice(device) { + return device.vendorId === 0x2581 && device.productId === 0x3b7c || device.vendorId === 0x2c97; + }; + + }); + + unwrapExports(utils); + var utils_1 = utils.defer; + var utils_2 = utils.splitPath; + var utils_3 = utils.eachSeries; + var utils_4 = utils.foreach; + var utils_5 = utils.doIf; + var utils_6 = utils.asyncWhile; + var utils_7 = utils.isLedgerDevice; + + var require$$0 = {}; + + var createHash = require$$0.createHash; + + var Btc_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + // TODO future refactoring + // - drop utils.js & refactoring with async/await style + // - try to avoid every place we do hex<>Buffer conversion. also accept Buffer as func parameters (could accept both a string or a Buffer in the API) + // - there are redundant code across apps (see Eth vs Btc). we might want to factorize it somewhere. also each app apdu call should be abstracted it out as an api + + + + + + + var _createHash2 = _interopRequireDefault(createHash); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + /** + * address format is one of legacy | p2sh | bech32 + */ + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2 + }; + + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + + var Btc = function () { + function Btc(transport) { + var scrambleKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "BTC"; + + _classCallCheck(this, Btc); + + this.transport = transport; + transport.decorateAppAPIMethods(this, ["getWalletPublicKey", "signP2SHTransaction", "signMessageNew", "createPaymentTransactionNew"], scrambleKey); + } + + _createClass(Btc, [{ + key: "hashPublicKey", + value: function hashPublicKey(buffer) { + return (0, _createHash2.default)("rmd160").update((0, _createHash2.default)("sha256").update(buffer).digest()).digest(); + } + }, { + key: "getWalletPublicKey_private", + value: function getWalletPublicKey_private(path) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var _verify$format$option = _extends({ + verify: false, + format: "legacy" + }, options), + verify = _verify$format$option.verify, + format = _verify$format$option.format; + + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + var paths = (0, utils.splitPath)(path); + var p1 = verify ? 1 : 0; + var p2 = addressFormatMap[format]; + var buffer = Buffer.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return this.transport.send(0xe0, 0x40, p1, p2, buffer).then(function (response) { + var publicKeyLength = response[0]; + var addressLength = response[1 + publicKeyLength]; + var publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + var bitcoinAddress = response.slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength).toString("ascii"); + var chainCode = response.slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32).toString("hex"); + return { publicKey: publicKey, bitcoinAddress: bitcoinAddress, chainCode: chainCode }; + }); + } + + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + + }, { + key: "getWalletPublicKey", + value: function getWalletPublicKey(path, opts) { + var options = void 0; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + format: arguments[2] ? "p2sh" : "legacy" + }; + } else { + options = opts || {}; + } + return this.getWalletPublicKey_private(path, options); + } + }, { + key: "getTrustedInputRaw", + value: function getTrustedInputRaw(transactionData, indexLookup) { + var data = void 0; + var firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + var prefix = Buffer.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer.concat([prefix, transactionData], transactionData.length + 4); + } else { + data = transactionData; + } + return this.transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data).then(function (trustedInput) { + return trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + }); + } + }, { + key: "getTrustedInput", + value: function getTrustedInput(indexLookup, transaction) { + var _this = this; + + var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var inputs = transaction.inputs, + outputs = transaction.outputs, + locktime = transaction.locktime; + + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + var isDecred = additionals.includes("decred"); + var processScriptBlocks = function processScriptBlocks(script, sequence) { + var scriptBlocks = []; + var offset = 0; + while (offset !== script.length) { + var blockSize = script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } else { + scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), sequence])); + } + offset += blockSize; + } + + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(sequence); + } + + return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { + return _this.getTrustedInputRaw(scriptBlock); + }); + }; + + var processWholeScriptBlock = function processWholeScriptBlock(script, sequence) { + return _this.getTrustedInputRaw(Buffer.concat([script, sequence])); + }; + + var processInputs = function processInputs() { + return (0, utils.eachSeries)(inputs, function (input) { + var treeField = isDecred ? input.tree || Buffer.from([0x00]) : Buffer.alloc(0); + var data = Buffer.concat([input.prevout, treeField, _this.createVarint(input.script.length)]); + return _this.getTrustedInputRaw(data).then(function () { + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + return isDecred ? processWholeScriptBlock(input.script, input.sequence) : processScriptBlocks(input.script, input.sequence); + }); + }).then(function () { + var data = _this.createVarint(outputs.length); + return _this.getTrustedInputRaw(data); + }); + }; + + var processOutputs = function processOutputs() { + return (0, utils.eachSeries)(outputs, function (output) { + var data = output.amount; + data = Buffer.concat([data, isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), //Version script + _this.createVarint(output.script.length), output.script]); + return _this.getTrustedInputRaw(data).then(function () { + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("output"); + }); + }).then(function () { + //Add expiry height for decred + var finalData = isDecred ? Buffer.concat([locktime, Buffer.from([0x00, 0x00, 0x00, 0x00])]) : locktime; + return _this.getTrustedInputRaw(finalData); + }); + }; + + var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), this.createVarint(inputs.length)]); + return this.getTrustedInputRaw(data, indexLookup).then(processInputs).then(processOutputs); + } + }, { + key: "getTrustedInputBIP143", + value: function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(indexLookup, transaction) { + var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var isDecred, sha, hash, data, outputs, locktime; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (transaction) { + _context.next = 2; + break; + } + + throw new Error("getTrustedInputBIP143: missing tx"); + + case 2: + isDecred = additionals.includes("decred"); + + if (!isDecred) { + _context.next = 5; + break; + } + + throw new Error("Decred does not implement BIP143"); + + case 5: + sha = (0, _createHash2.default)("sha256"); + + sha.update(this.serializeTransaction(transaction, true)); + hash = sha.digest(); + + sha = (0, _createHash2.default)("sha256"); + sha.update(hash); + hash = sha.digest(); + data = Buffer.alloc(4); + + data.writeUInt32LE(indexLookup, 0); + outputs = transaction.outputs, locktime = transaction.locktime; + + if (!(!outputs || !locktime)) { + _context.next = 16; + break; + } + + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + + case 16: + if (outputs[indexLookup]) { + _context.next = 18; + break; + } + + throw new Error("getTrustedInputBIP143: wrong index"); + + case 18: + hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); + _context.next = 21; + return hash.toString("hex"); + + case 21: + return _context.abrupt("return", _context.sent); + + case 22: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function getTrustedInputBIP143(_x4, _x5) { + return _ref.apply(this, arguments); + } + + return getTrustedInputBIP143; + }() + }, { + key: "getVarint", + value: function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [(data[offset + 4] << 24) + (data[offset + 3] << 16) + (data[offset + 2] << 8) + data[offset + 1], 5]; + } + + throw new Error("getVarint called with unexpected parameters"); + } + }, { + key: "startUntrustedHashTransactionInputRaw", + value: function startUntrustedHashTransactionInputRaw(newTransaction, firstRound, transactionData) { + var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; + + var p2 = bip143 ? additionals.includes("sapling") ? 0x05 : overwinter ? 0x04 : 0x02 : 0x00; + return this.transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + }, { + key: "startUntrustedHashTransactionInput", + value: function startUntrustedHashTransactionInput(newTransaction, transaction, inputs) { + var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var _this2 = this; + + var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; + + var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), this.createVarint(transaction.inputs.length)]); + return this.startUntrustedHashTransactionInputRaw(newTransaction, true, data, bip143, overwinter, additionals).then(function () { + var i = 0; + var isDecred = additionals.includes("decred"); + return (0, utils.eachSeries)(transaction.inputs, function (input) { + var prefix = void 0; + if (bip143) { + prefix = Buffer.from([0x02]); + } else { + if (inputs[i].trustedInput) { + prefix = Buffer.from([0x01, inputs[i].value.length]); + } else { + prefix = Buffer.from([0x00]); + } + } + data = Buffer.concat([prefix, inputs[i].value, isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), _this2.createVarint(input.script.length)]); + return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, data, bip143, overwinter, additionals).then(function () { + var scriptBlocks = []; + var offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } else { + while (offset !== input.script.length) { + var blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } else { + scriptBlocks.push(Buffer.concat([input.script.slice(offset, offset + blockSize), input.sequence])); + } + offset += blockSize; + } + } + return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { + return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, scriptBlock, bip143, overwinter, additionals); + }).then(function () { + i++; + }); + }); + }); + }); + } + }, { + key: "provideOutputFullChangePath", + value: function provideOutputFullChangePath(path) { + var paths = (0, utils.splitPath)(path); + var buffer = Buffer.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return this.transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + }, { + key: "hashOutputFull", + value: function hashOutputFull(outputScript) { + var _this3 = this; + + var additionals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + var offset = 0; + var p1 = 0x80; + var isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return this.transport.send(0xe0, 0x4a, p1, 0x00, outputScript); + } + return (0, utils.asyncWhile)(function () { + return offset < outputScript.length; + }, function () { + var blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length ? outputScript.length - offset : MAX_SCRIPT_BLOCK; + var p1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + var data = outputScript.slice(offset, offset + blockSize); + + return _this3.transport.send(0xe0, 0x4a, p1, 0x00, data).then(function () { + offset += blockSize; + }); + }); + } + }, { + key: "signTransaction", + value: function signTransaction(path) { + var lockTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_LOCKTIME; + var sigHashType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SIGHASH_ALL; + var expiryHeight = arguments[3]; + var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; + + var isDecred = additionals.includes("decred"); + var paths = (0, utils.splitPath)(path); + var offset = 0; + var pathsBuffer = Buffer.alloc(paths.length * 4); + paths.forEach(function (element) { + pathsBuffer.writeUInt32BE(element, offset); + offset += 4; + }); + var lockTimeBuffer = Buffer.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred ? Buffer.concat([Buffer.from([paths.length]), pathsBuffer, lockTimeBuffer, expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), Buffer.from([sigHashType])]) : Buffer.concat([Buffer.from([paths.length]), pathsBuffer, Buffer.from([0x00]), lockTimeBuffer, Buffer.from([sigHashType])]); + if (expiryHeight && !isDecred) { + buffer = Buffer.concat([buffer, expiryHeight]); + } + return this.transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + + }, { + key: "signMessageNew", + value: function signMessageNew(path, messageHex) { + var _this4 = this; + + var paths = (0, utils.splitPath)(path); + var message = new Buffer(messageHex, "hex"); + var offset = 0; + var toSend = []; + + var _loop = function _loop() { + var maxChunkSize = offset === 0 ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 : MAX_SCRIPT_BLOCK; + var chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; + var buffer = new Buffer(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + toSend.push(buffer); + offset += chunkSize; + }; + + while (offset !== message.length) { + _loop(); + } + return (0, utils.foreach)(toSend, function (data, i) { + return _this4.transport.send(0xe0, 0x4e, 0x00, i === 0 ? 0x01 : 0x80, data); + }).then(function () { + return _this4.transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00])).then(function (response) { + var v = response[0] - 0x30; + var r = response.slice(4, 4 + response[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + var offset = 4 + response[3] + 2; + var s = response.slice(offset, offset + response[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return { v: v, r: r, s: s }; + }); + }); + } + + /** + * To sign a transaction involving standard (P2PKH) inputs, call createPaymentTransactionNew with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @return the signed transaction ready to be broadcast + * @example + btc.createPaymentTransactionNew( + [ [tx1, 1] ], + ["0'/0/0"], + undefined, + "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + ).then(res => ...); + */ + + }, { + key: "createPaymentTransactionNew", + value: function createPaymentTransactionNew(inputs, associatedKeysets, changePath, outputScriptHex) { + var lockTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : DEFAULT_LOCKTIME; + var sigHashType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SIGHASH_ALL; + var segwit = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; + var initialTimestamp = arguments[7]; + + var _this5 = this; + + var additionals = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + var expiryHeight = arguments[9]; + + var isDecred = additionals.includes("decred"); + var isXST = additionals.includes("stealthcoin"); + var hasTimestamp = initialTimestamp !== undefined; + var startTime = Date.now(); + var sapling = additionals.includes("sapling"); + var bech32 = segwit && additionals.includes("bech32"); + var useBip143 = segwit || !!additionals && (additionals.includes("abc") || additionals.includes("gold") || additionals.includes("bip143")) || !!expiryHeight && !isDecred; + // Inputs are provided as arrays of [transaction, output_index, optional redeem script, optional sequence] + // associatedKeysets are provided as arrays of [path] + var nullScript = Buffer.alloc(0); + var nullPrevout = Buffer.alloc(0); + var defaultVersion = Buffer.alloc(4); + !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST ? defaultVersion.writeUInt32LE(2, 0) : defaultVersion.writeUInt32LE(1, 0); // Default version to 2 for XST not to have timestamp + var trustedInputs = []; + var regularOutputs = []; + var signatures = []; + var publicKeys = []; + var firstRun = true; + var resuming = false; + var targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer.alloc(0) + }; + var getTrustedInputCall = useBip143 ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); + var outputScript = Buffer.from(outputScriptHex, "hex"); + + return (0, utils.foreach)(inputs, function (input) { + return (0, utils.doIf)(!resuming, function () { + return getTrustedInputCall(input[1], input[0], additionals).then(function (trustedInput) { + var sequence = Buffer.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer.from(trustedInput, "hex"), + sequence: sequence + }); + }); + }).then(function () { + var outputs = input[0].outputs; + + var index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + }).then(function () { + if (!!expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); + } else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + }); + }).then(function () { + for (var i = 0; i < inputs.length; i++) { + var _sequence = Buffer.alloc(4); + _sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: _sequence + }); + } + }).then(function () { + return (0, utils.doIf)(!resuming, function () { + return ( + // Collect public keys + (0, utils.foreach)(inputs, function (input, i) { + return _this5.getWalletPublicKey_private(associatedKeysets[i]); + }).then(function (result) { + for (var index = 0; index < result.length; index++) { + publicKeys.push(_this5.compressPublicKey(Buffer.from(result[index].publicKey, "hex"))); + } + }) + ); + }); + }).then(function () { + if (hasTimestamp) { + targetTransaction.timestamp = Buffer.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + }).then(function () { + return (0, utils.doIf)(useBip143, function () { + return ( + // Do the first run with all inputs + _this5.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals).then(function () { + return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { + // $FlowFixMe + return _this5.provideOutputFullChangePath(changePath); + }).then(function () { + return _this5.hashOutputFull(outputScript); + }); + }) + ); + }); + }).then(function () { + return (0, utils.doIf)(!!expiryHeight && !isDecred, function () { + return ( + // FIXME: I think we should always pass lockTime here. + _this5.signTransaction("", lockTime, SIGHASH_ALL, expiryHeight) + ); + }); + }).then(function () { + return ( + // Do the second run with the individual transaction + (0, utils.foreach)(inputs, function (input, i) { + var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : !segwit ? regularOutputs[i].script : Buffer.concat([Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), _this5.hashPublicKey(publicKeys[i]), Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])]); + var pseudoTX = Object.assign({}, targetTransaction); + var pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; + } else { + pseudoTX.inputs[i].script = script; + } + return _this5.startUntrustedHashTransactionInput(!useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals).then(function () { + return (0, utils.doIf)(!useBip143, function () { + return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { + // $FlowFixMe + return _this5.provideOutputFullChangePath(changePath); + }).then(function () { + return _this5.hashOutputFull(outputScript, additionals); + }); + }); + }).then(function () { + return _this5.signTransaction(associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals); + }).then(function (signature) { + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + }); + }) + ); + }).then(function () { + // Populate the final input scripts + for (var _i = 0; _i < inputs.length; _i++) { + if (segwit) { + targetTransaction.witness = Buffer.alloc(0); + if (!bech32) { + targetTransaction.inputs[_i].script = Buffer.concat([Buffer.from("160014", "hex"), _this5.hashPublicKey(publicKeys[_i])]); + } + } else { + var signatureSize = Buffer.alloc(1); + var keySize = Buffer.alloc(1); + signatureSize[0] = signatures[_i].length; + keySize[0] = publicKeys[_i].length; + targetTransaction.inputs[_i].script = Buffer.concat([signatureSize, signatures[_i], keySize, publicKeys[_i]]); + } + var offset = useBip143 ? 0 : 4; + targetTransaction.inputs[_i].prevout = trustedInputs[_i].value.slice(offset, offset + 0x24); + } + + var lockTimeBuffer = Buffer.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + + var result = Buffer.concat([_this5.serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript]); + + if (segwit && !isDecred) { + var witness = Buffer.alloc(0); + for (var i = 0; i < inputs.length; i++) { + var tmpScriptData = Buffer.concat([Buffer.from("02", "hex"), Buffer.from([signatures[i].length]), signatures[i], Buffer.from([publicKeys[i].length]), publicKeys[i]]); + witness = Buffer.concat([witness, tmpScriptData]); + } + result = Buffer.concat([result, witness]); + } + + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer.concat([result, lockTimeBuffer]); + + if (expiryHeight) { + result = Buffer.concat([result, targetTransaction.nExpiryHeight || Buffer.alloc(0), targetTransaction.extraData || Buffer.alloc(0)]); + } + + if (isDecred) { + var decredWitness = Buffer.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness = Buffer.concat([decredWitness, Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Buffer.from([0x00, 0x00, 0x00, 0x00]), //Block height + Buffer.from([0xff, 0xff, 0xff, 0xff]), //Block index + Buffer.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script]); + }); + + result = Buffer.concat([result, decredWitness]); + } + + return result.toString("hex"); + }); + } + + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction( + [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + ["0'/0/0"], + "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + ).then(result => ...); + */ + + }, { + key: "signP2SHTransaction", + value: function signP2SHTransaction(inputs, associatedKeysets, outputScriptHex) { + var lockTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_LOCKTIME; + var sigHashType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SIGHASH_ALL; + + var _this6 = this; + + var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + var transactionVersion = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_VERSION; + + // Inputs are provided as arrays of [transaction, output_index, redeem script, optional sequence] + // associatedKeysets are provided as arrays of [path] + var nullScript = Buffer.alloc(0); + var nullPrevout = Buffer.alloc(0); + var defaultVersion = Buffer.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + var trustedInputs = []; + var regularOutputs = []; + var signatures = []; + var firstRun = true; + var resuming = false; + var targetTransaction = { + inputs: [], + version: defaultVersion + }; + + var getTrustedInputCall = segwit ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); + var outputScript = Buffer.from(outputScriptHex, "hex"); + + return (0, utils.foreach)(inputs, function (input) { + return (0, utils.doIf)(!resuming, function () { + return getTrustedInputCall(input[1], input[0]).then(function (trustedInput) { + var sequence = Buffer.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit ? Buffer.from(trustedInput, "hex") : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + }); + }).then(function () { + var outputs = input[0].outputs; + + var index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + }); + }).then(function () { + // Pre-build the target transaction + for (var i = 0; i < inputs.length; i++) { + var _sequence2 = Buffer.alloc(4); + _sequence2.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: _sequence2 + }); + } + }).then(function () { + return (0, utils.doIf)(segwit, function () { + return ( + // Do the first run with all inputs + _this6.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true).then(function () { + return _this6.hashOutputFull(outputScript); + }) + ); + }); + }).then(function () { + return (0, utils.foreach)(inputs, function (input, i) { + var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : regularOutputs[i].script; + var pseudoTX = Object.assign({}, targetTransaction); + var pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; + } else { + pseudoTX.inputs[i].script = script; + } + return _this6.startUntrustedHashTransactionInput(!segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit).then(function () { + return (0, utils.doIf)(!segwit, function () { + return _this6.hashOutputFull(outputScript); + }); + }).then(function () { + return _this6.signTransaction(associatedKeysets[i], lockTime, sigHashType).then(function (signature) { + signatures.push(segwit ? signature.toString("hex") : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + }); + }); + }); + }).then(function () { + return signatures; + }); + } + }, { + key: "compressPublicKey", + value: function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer.alloc(1); + prefixBuffer[0] = prefix; + return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + }, { + key: "createVarint", + value: function createVarint(value) { + if (value < 0xfd) { + var _buffer = Buffer.alloc(1); + _buffer[0] = value; + return _buffer; + } + if (value <= 0xffff) { + var _buffer2 = Buffer.alloc(3); + _buffer2[0] = 0xfd; + _buffer2[1] = value & 0xff; + _buffer2[2] = value >> 8 & 0xff; + return _buffer2; + } + var buffer = Buffer.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = value >> 8 & 0xff; + buffer[3] = value >> 16 & 0xff; + buffer[4] = value >> 24 & 0xff; + return buffer; + } + + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + + }, { + key: "splitTransaction", + value: function splitTransaction(transactionHex) { + var isSegwitSupported = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var hasTimestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var hasExtraData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; + + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer.alloc(0); + var nExpiryHeight = Buffer.alloc(0); + var nVersionGroupId = Buffer.alloc(0); + var extraData = Buffer.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && isSegwitSupported && transaction[offset] === 0 && transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = this.getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var _prevout = transaction.slice(offset, offset + 36); + offset += 36; + var _script = Buffer.alloc(0); + var _tree = Buffer.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = this.getVarint(transaction, offset); + offset += varint[1]; + _script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } else { + //Tree field + _tree = transaction.slice(offset, offset + 1); + offset += 1; + } + + var _sequence3 = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ prevout: _prevout, script: _script, sequence: _sequence3, tree: _tree }); + } + varint = this.getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var _i2 = 0; _i2 < numberOutputs; _i2++) { + var _amount = transaction.slice(offset, offset + 8); + offset += 8; + + if (isDecred) { + //Script version + offset += 2; + } + + varint = this.getVarint(transaction, offset); + offset += varint[1]; + var _script2 = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ amount: _amount, script: _script2 }); + } + var witnessScript = void 0, + locktime = void 0; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + + //Get witnesses for Decred + if (isDecred) { + varint = this.getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var _i3 = 0; _i3 < numberInputs; _i3++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = this.getVarint(transaction, offset); + offset += varint[1]; + var _script3 = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[_i3].script = _script3; + } + } + + return { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + + }, { + key: "serializeTransactionOutputs", + value: function serializeTransactionOutputs(_ref2) { + var _this7 = this; + + var outputs = _ref2.outputs; + + var outputBuffer = Buffer.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer.concat([outputBuffer, this.createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer.concat([outputBuffer, output.amount, _this7.createVarint(output.script.length), output.script]); + }); + } + return outputBuffer; + } + + /** + */ + + }, { + key: "serializeTransaction", + value: function serializeTransaction(transaction, skipWitness, timestamp) { + var _this8 = this; + + var additionals = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = isDecred || isBech32 ? Buffer.concat([inputBuffer, input.prevout, Buffer.from([0x00]), //tree + input.sequence]) : Buffer.concat([inputBuffer, input.prevout, _this8.createVarint(input.script.length), input.script, input.sequence]); + }); + + var outputBuffer = this.serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer.concat([outputBuffer, useWitness && transaction.witness || Buffer.alloc(0), transaction.locktime, transaction.nExpiryHeight || Buffer.alloc(0), transaction.extraData || Buffer.alloc(0)]); + } + + return Buffer.concat([transaction.version, timestamp ? timestamp : Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), this.createVarint(transaction.inputs.length), inputBuffer, outputBuffer]); + } + + /** + */ + + }, { + key: "displayTransactionDebug", + value: function displayTransactionDebug(transaction) { + console.log("version " + transaction.version.toString("hex")); + transaction.inputs.forEach(function (input, i) { + var prevout = input.prevout.toString("hex"); + var script = input.script.toString("hex"); + var sequence = input.sequence.toString("hex"); + console.log("input " + i + " prevout " + prevout + " script " + script + " sequence " + sequence); + }); + (transaction.outputs || []).forEach(function (output, i) { + var amount = output.amount.toString("hex"); + var script = output.script.toString("hex"); + console.log("output " + i + " amount " + amount + " script " + script); + }); + if (typeof transaction.locktime !== "undefined") { + console.log("locktime " + transaction.locktime.toString("hex")); + } + } + }]); + + return Btc; + }(); + + /** + */ + + + exports.default = Btc; + + /** + */ + + + /** + */ + + }); + + var Btc = unwrapExports(Btc_1); + + var Btc$1 = /*#__PURE__*/Object.freeze({ + default: Btc, + __moduleExports: Btc_1 + }); + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + 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. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active && !(this instanceof domain.Domain)) { + this.domain = domain.active; + } + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + 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 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + 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); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var needDomainExit = false; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + if (needDomainExit) + domain.exit(); + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + 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) { + 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) { + // 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]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + 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 _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + 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; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + 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) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + 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; + } + + var helpers = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + /* eslint-disable no-continue */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + + var errorClasses = {}; + var deserializers = {}; + + var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { + deserializers[name] = deserializer; + }; + + var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + // $FlowFixMe + C.prototype = new Error(); + + errorClasses[name] = C; + // $FlowFixMe we can't easily type a subset of Error for now... + return C; + }; + + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = exports.deserializeError = function deserializeError(object) { + if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } catch (e) { + // nothing + } + + var error = void 0; + if (typeof object.name === "string") { + var _object = object, + name = _object.name; + + var des = deserializers[name]; + if (des) { + error = des(object); + } else { + var _constructor = name === "Error" ? Error : errorClasses[name]; + + if (!_constructor) { + console.warn("deserializing an unknown class '" + name + "'"); + _constructor = createCustomErrorClass(name); + } + + error = Object.create(_constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } else { + error = new Error(object.message); + } + + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = exports.serializeError = function serializeError(value) { + if (!value) return value; + if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var to = {}; + seen.push(from); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var key = _step.value; + + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + }); + + unwrapExports(helpers); + var helpers_1 = helpers.addCustomErrorDeserializer; + var helpers_2 = helpers.createCustomErrorClass; + var helpers_3 = helpers.deserializeError; + var helpers_4 = helpers.serializeError; + + var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; + exports.TransportError = TransportError; + exports.getAltStatusMessage = getAltStatusMessage; + exports.TransportStatusError = TransportStatusError; + + + + exports.serializeError = helpers.serializeError; + exports.deserializeError = helpers.deserializeError; + exports.createCustomErrorClass = helpers.createCustomErrorClass; + exports.addCustomErrorDeserializer = helpers.addCustomErrorDeserializer; + var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers.createCustomErrorClass)("AccountNameRequired"); + var BluetoothRequired = exports.BluetoothRequired = (0, helpers.createCustomErrorClass)("BluetoothRequired"); + var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers.createCustomErrorClass)("BtcUnmatchedApp"); + var CantOpenDevice = exports.CantOpenDevice = (0, helpers.createCustomErrorClass)("CantOpenDevice"); + var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers.createCustomErrorClass)("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers.createCustomErrorClass)("DeviceNotGenuine"); + var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); + var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers.createCustomErrorClass)("DeviceInOSUExpected"); + var DeviceHalted = exports.DeviceHalted = (0, helpers.createCustomErrorClass)("DeviceHalted"); + var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers.createCustomErrorClass)("DeviceNameInvalid"); + var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers.createCustomErrorClass)("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers.createCustomErrorClass)("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = exports.EnpointConfigError = (0, helpers.createCustomErrorClass)("EnpointConfig"); + var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers.createCustomErrorClass)("FeeEstimationFailed"); + var HardResetFail = exports.HardResetFail = (0, helpers.createCustomErrorClass)("HardResetFail"); + var InvalidAddress = exports.InvalidAddress = (0, helpers.createCustomErrorClass)("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers.createCustomErrorClass)("LatestMCUInstalledError"); + var UnknownMCU = exports.UnknownMCU = (0, helpers.createCustomErrorClass)("UnknownMCU"); + var LedgerAPIError = exports.LedgerAPIError = (0, helpers.createCustomErrorClass)("LedgerAPIError"); + var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers.createCustomErrorClass)("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); + var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers.createCustomErrorClass)("ManagerDeviceLocked"); + var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); + var NetworkDown = exports.NetworkDown = (0, helpers.createCustomErrorClass)("NetworkDown"); + var NoAddressesFound = exports.NoAddressesFound = (0, helpers.createCustomErrorClass)("NoAddressesFound"); + var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers.createCustomErrorClass)("NotEnoughBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); + var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers.createCustomErrorClass)("PasswordsDontMatch"); + var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers.createCustomErrorClass)("PasswordIncorrect"); + var TimeoutTagged = exports.TimeoutTagged = (0, helpers.createCustomErrorClass)("TimeoutTagged"); + var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers.createCustomErrorClass)("UnexpectedBootloader"); + var UpdateYourApp = exports.UpdateYourApp = (0, helpers.createCustomErrorClass)("UpdateYourApp"); + var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); + var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers.createCustomErrorClass)("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers.createCustomErrorClass)("UserRefusedAllowManager"); + var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers.createCustomErrorClass)("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); + var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers.createCustomErrorClass)("DeviceShouldStayInApp"); + var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers.createCustomErrorClass)("WebsocketConnectionError"); + var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers.createCustomErrorClass)("WebsocketConnectionFailed"); + var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers.createCustomErrorClass)("WrongDeviceForAccount"); + var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers.createCustomErrorClass)("ETHAddressNonEIP"); + var CantScanQRCode = exports.CantScanQRCode = (0, helpers.createCustomErrorClass)("CantScanQRCode"); + var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers.createCustomErrorClass)("FeeNotLoaded"); + var FeeRequired = exports.FeeRequired = (0, helpers.createCustomErrorClass)("FeeRequired"); + var SyncError = exports.SyncError = (0, helpers.createCustomErrorClass)("SyncError"); + var PairingFailed = exports.PairingFailed = (0, helpers.createCustomErrorClass)("PairingFailed"); + var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers.createCustomErrorClass)("GenuineCheckFailed"); + var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers.createCustomErrorClass)("LedgerAPI4xx"); + var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers.createCustomErrorClass)("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); + + // db stuff, no need to translate + var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers.createCustomErrorClass)("NoDBPathGiven"); + var DBWrongPassword = exports.DBWrongPassword = (0, helpers.createCustomErrorClass)("DBWrongPassword"); + var DBNotReset = exports.DBNotReset = (0, helpers.createCustomErrorClass)("DBNotReset"); + + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + //$FlowFixMe + TransportError.prototype = new Error(); + + (0, helpers.addCustomErrorDeserializer)("TransportError", function (e) { + return new TransportError(e.message, e.id); + }); + + var StatusCodes = exports.StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { + return StatusCodes[k] === statusCode; + }) || "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + //$FlowFixMe + TransportStatusError.prototype = new Error(); + + (0, helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { + return new TransportStatusError(e.statusCode); + }); + + }); + + unwrapExports(lib); + var lib_1 = lib.StatusCodes; + var lib_2 = lib.DBNotReset; + var lib_3 = lib.DBWrongPassword; + var lib_4 = lib.NoDBPathGiven; + var lib_5 = lib.FirmwareOrAppUpdateRequired; + var lib_6 = lib.LedgerAPI5xx; + var lib_7 = lib.LedgerAPI4xx; + var lib_8 = lib.GenuineCheckFailed; + var lib_9 = lib.PairingFailed; + var lib_10 = lib.SyncError; + var lib_11 = lib.FeeRequired; + var lib_12 = lib.FeeNotLoaded; + var lib_13 = lib.CantScanQRCode; + var lib_14 = lib.ETHAddressNonEIP; + var lib_15 = lib.WrongDeviceForAccount; + var lib_16 = lib.WebsocketConnectionFailed; + var lib_17 = lib.WebsocketConnectionError; + var lib_18 = lib.DeviceShouldStayInApp; + var lib_19 = lib.TransportInterfaceNotAvailable; + var lib_20 = lib.TransportOpenUserCancelled; + var lib_21 = lib.UserRefusedOnDevice; + var lib_22 = lib.UserRefusedAllowManager; + var lib_23 = lib.UserRefusedFirmwareUpdate; + var lib_24 = lib.UserRefusedAddress; + var lib_25 = lib.UserRefusedDeviceNameChange; + var lib_26 = lib.UpdateYourApp; + var lib_27 = lib.UnexpectedBootloader; + var lib_28 = lib.TimeoutTagged; + var lib_29 = lib.PasswordIncorrectError; + var lib_30 = lib.PasswordsDontMatchError; + var lib_31 = lib.NotEnoughBalanceBecauseDestinationNotCreated; + var lib_32 = lib.NotEnoughBalance; + var lib_33 = lib.NoAddressesFound; + var lib_34 = lib.NetworkDown; + var lib_35 = lib.ManagerUninstallBTCDep; + var lib_36 = lib.ManagerNotEnoughSpaceError; + var lib_37 = lib.ManagerDeviceLockedError; + var lib_38 = lib.ManagerAppRelyOnBTCError; + var lib_39 = lib.ManagerAppAlreadyInstalledError; + var lib_40 = lib.LedgerAPINotAvailable; + var lib_41 = lib.LedgerAPIErrorWithMessage; + var lib_42 = lib.LedgerAPIError; + var lib_43 = lib.UnknownMCU; + var lib_44 = lib.LatestMCUInstalledError; + var lib_45 = lib.InvalidAddressBecauseDestinationIsAlsoSource; + var lib_46 = lib.InvalidAddress; + var lib_47 = lib.HardResetFail; + var lib_48 = lib.FeeEstimationFailed; + var lib_49 = lib.EthAppPleaseEnableContractData; + var lib_50 = lib.EnpointConfigError; + var lib_51 = lib.DisconnectedDeviceDuringOperation; + var lib_52 = lib.DisconnectedDevice; + var lib_53 = lib.DeviceSocketNoBulkStatus; + var lib_54 = lib.DeviceSocketFail; + var lib_55 = lib.DeviceNameInvalid; + var lib_56 = lib.DeviceHalted; + var lib_57 = lib.DeviceInOSUExpected; + var lib_58 = lib.DeviceOnDashboardExpected; + var lib_59 = lib.DeviceNotGenuineError; + var lib_60 = lib.DeviceGenuineSocketEarlyClose; + var lib_61 = lib.DeviceAppVerifyNotSupported; + var lib_62 = lib.CurrencyNotSupported; + var lib_63 = lib.CantOpenDevice; + var lib_64 = lib.BtcUnmatchedApp; + var lib_65 = lib.BluetoothRequired; + var lib_66 = lib.AccountNameRequiredError; + var lib_67 = lib.addCustomErrorDeserializer; + var lib_68 = lib.createCustomErrorClass; + var lib_69 = lib.deserializeError; + var lib_70 = lib.serializeError; + var lib_71 = lib.TransportError; + var lib_72 = lib.getAltStatusMessage; + var lib_73 = lib.TransportStatusError; + + var Transport_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + + + var _events3 = _interopRequireDefault(EventEmitter); + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + exports.TransportError = lib.TransportError; + exports.TransportStatusError = lib.TransportStatusError; + exports.StatusCodes = lib.StatusCodes; + exports.getAltStatusMessage = lib.getAltStatusMessage; + + /** + */ + + + /** + */ + + + /** + * type: add or remove event + * descriptor: a parameter that can be passed to open(descriptor) + * deviceModel: device info on the model (is it a nano s, nano x, ...) + * device: transport specific device info + */ + + /** + */ + + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport = function () { + function Transport() { + var _this = this; + + _classCallCheck(this, Transport); + + this.exchangeTimeout = 30000; + this._events = new _events3.default(); + + this.send = function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { + var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); + var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib.StatusCodes.OK]; + var response, sw; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(data.length >= 256)) { + _context.next = 2; + break; + } + + throw new lib.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + + case 2: + _context.next = 4; + return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); + + case 4: + response = _context.sent; + sw = response.readUInt16BE(response.length - 2); + + if (statusList.some(function (s) { + return s === sw; + })) { + _context.next = 8; + break; + } + + throw new lib.TransportStatusError(sw); + + case 8: + return _context.abrupt("return", response); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee, _this); + })); + + return function (_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; + }(); + + this.exchangeAtomicImpl = function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { + var resolveBusy, busyPromise, res; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!_this.exchangeBusyPromise) { + _context2.next = 2; + break; + } + + throw new lib.TransportError("Transport race condition", "RaceCondition"); + + case 2: + resolveBusy = void 0; + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + + _this.exchangeBusyPromise = busyPromise; + _context2.prev = 5; + _context2.next = 8; + return f(); + + case 8: + res = _context2.sent; + return _context2.abrupt("return", res); + + case 10: + _context2.prev = 10; + + if (resolveBusy) resolveBusy(); + _this.exchangeBusyPromise = null; + return _context2.finish(10); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, _this, [[5,, 10, 14]]); + })); + + return function (_x7) { + return _ref2.apply(this, arguments); + }; + }(); + + this._appAPIlock = null; + } + + /** + * Statically check if a transport is supported on the user's platform/browser. + */ + + + /** + * List once all available descriptors. For a better granularity, checkout `listen()`. + * @return a promise of descriptors + * @example + * TransportFoo.list().then(descriptors => ...) + */ + + + /** + * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) + * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. + * each listen() call will first emit all potential device already connected and then will emit events can come over times, + * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. + * @param observer is an object with a next, error and complete function (compatible with observer pattern) + * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. + * @example + const sub = TransportFoo.listen({ + next: e => { + if (e.type==="add") { + sub.unsubscribe(); + const transport = await TransportFoo.open(e.descriptor); + ... + } + }, + error: error => {}, + complete: () => {} + }) + */ + + + /** + * attempt to create a Transport instance with potentially a descriptor. + * @param descriptor: the descriptor to open the transport with. + * @param timeout: an optional timeout + * @return a Promise of Transport instance + * @example + TransportFoo.open(descriptor).then(transport => ...) + */ + + + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + + + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + + + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + + + _createClass(Transport, [{ + key: "on", + + + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + value: function on(eventName, cb) { + this._events.on(eventName, cb); + } + + /** + * Stop listening to an event on an instance of transport. + */ + + }, { + key: "off", + value: function off(eventName, cb) { + this._events.removeListener(eventName, cb); + } + }, { + key: "emit", + value: function emit(event) { + var _events; + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); + } + + /** + * Enable or not logs of the binary exchange + */ + + }, { + key: "setDebugMode", + value: function setDebugMode() { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + } + + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + + }, { + key: "setExchangeTimeout", + value: function setExchangeTimeout(exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + } + + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + + }, { + key: "decorateAppAPIMethods", + value: function decorateAppAPIMethods(self, methods, scrambleKey) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var methodName = _step.value; + + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, { + key: "decorateAppAPIMethod", + value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { + var _this2 = this; + + return function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var _appAPIlock; + + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _appAPIlock = _this2._appAPIlock; + + if (!_appAPIlock) { + _context3.next = 3; + break; + } + + return _context3.abrupt("return", Promise.reject(new lib.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); + + case 3: + _context3.prev = 3; + + _this2._appAPIlock = methodName; + _this2.setScrambleKey(scrambleKey); + _context3.next = 8; + return f.apply(ctx, args); + + case 8: + return _context3.abrupt("return", _context3.sent); + + case 9: + _context3.prev = 9; + + _this2._appAPIlock = null; + return _context3.finish(9); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, _this2, [[3,, 9, 12]]); + })); + + return function () { + return _ref3.apply(this, arguments); + }; + }(); + } + }], [{ + key: "create", + + + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + value: function create() { + var _this3 = this; + + var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; + var listenTimeout = arguments[1]; + + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this3.listen({ + next: function next(e) { + found = true; + if (sub) sub.unsubscribe(); + if (listenTimeoutId) clearTimeout(listenTimeoutId); + _this3.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function error(e) { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function complete() { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + if (!found) { + reject(new lib.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout ? setTimeout(function () { + sub.unsubscribe(); + reject(new lib.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) : null; + }); + } + + // $FlowFixMe + + }]); + + return Transport; + }(); + + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + exports.default = Transport; + + }); + + unwrapExports(Transport_1); + var Transport_2 = Transport_1.getAltStatusMessage; + var Transport_3 = Transport_1.StatusCodes; + var Transport_4 = Transport_1.TransportStatusError; + var Transport_5 = Transport_1.TransportError; + + var hidFraming = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + + var Tag = 0x05; + + function asUInt16BE(value) { + var b = Buffer.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + + var initialAcc = { + data: Buffer.alloc(0), + dataLength: 0, + sequence: 0 + }; + + /** + * + */ + var createHIDframing = function createHIDframing(channel, packetSize) { + return { + makeBlocks: function makeBlocks(apdu) { + var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer.concat([data, // fill data with padding + Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); + + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function reduceResponse(acc, chunk) { + var _ref = acc || initialAcc, + data = _ref.data, + dataLength = _ref.dataLength, + sequence = _ref.sequence; + + if (chunk.readUInt16BE(0) !== channel) { + throw new lib.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new lib.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new lib.TransportError("Invalid sequence", "InvalidSequence"); + } + + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function getReducedResult(acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + + exports.default = createHIDframing; + + }); + + unwrapExports(hidFraming); + + var lib$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + /** + * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) + * + ** Model + * Ledger Nano S : 0x10 + * Ledger Blue : 0x00 + * Ledger Nano X : 0x40 + * + ** Interface support bitfield + * Generic HID : 0x01 + * Keyboard HID : 0x02 + * U2F : 0x04 + * CCID : 0x08 + * WebUSB : 0x10 + */ + + var IIGenericHID = exports.IIGenericHID = 0x01; + var IIKeyboardHID = exports.IIKeyboardHID = 0x02; + var IIU2F = exports.IIU2F = 0x04; + var IICCID = exports.IICCID = 0x08; + var IIWebUSB = exports.IIWebUSB = 0x10; + + var devices = { + blue: { + id: "blue", + productName: "Ledger Blue", + productIdMM: 0, + legacyUsbProductId: 0x0000, + usbOnly: true + }, + nanoS: { + id: "nanoS", + productName: "Ledger Nano S", + productIdMM: 1, + legacyUsbProductId: 0x0001, + usbOnly: true + }, + nanoX: { + id: "nanoX", + productName: "Ledger Nano X", + productIdMM: 4, + legacyUsbProductId: 0x0004, + usbOnly: false, + bluetoothSpec: [{ + // this is the legacy one (prototype version). we will eventually drop it. + serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", + notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", + writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" + }, { + serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", + notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", + writeUuid: "13d63400-2c97-0004-0002-4c6564676572" + }] + } + }; + + // $FlowFixMe + var devicesList = Object.values(devices); + + /** + * + */ + var ledgerUSBVendorId = exports.ledgerUSBVendorId = 0x2c97; + + /** + * + */ + var getDeviceModel = exports.getDeviceModel = function getDeviceModel(id) { + var info = devices[id]; + if (!info) throw new Error("device '" + id + "' does not exist"); + return info; + }; + + /** + * + */ + var identifyUSBProductId = exports.identifyUSBProductId = function identifyUSBProductId(usbProductId) { + var legacy = devicesList.find(function (d) { + return d.legacyUsbProductId === usbProductId; + }); + if (legacy) return legacy; + var mm = usbProductId >> 8; + var deviceModel = devicesList.find(function (d) { + return d.productIdMM === mm; + }); + return deviceModel; + }; + + var bluetoothServices = []; + var serviceUuidToInfos = {}; + + for (var _id in devices) { + var _deviceModel = devices[_id]; + var _bluetoothSpec = _deviceModel.bluetoothSpec; + + if (_bluetoothSpec) { + for (var i = 0; i < _bluetoothSpec.length; i++) { + var spec = _bluetoothSpec[i]; + bluetoothServices.push(spec.serviceUuid); + serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); + } + } + } + + /** + * + */ + var getBluetoothServiceUuids = exports.getBluetoothServiceUuids = function getBluetoothServiceUuids() { + return bluetoothServices; + }; + + /** + * + */ + var getInfosForServiceUuid = exports.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { + return serviceUuidToInfos[uuid.toLowerCase()]; + }; + + /** + * + */ + + + /** + * + */ + + + /** + * + */ + + }); + + unwrapExports(lib$1); + var lib_1$1 = lib$1.IIGenericHID; + var lib_2$1 = lib$1.IIKeyboardHID; + var lib_3$1 = lib$1.IIU2F; + var lib_4$1 = lib$1.IICCID; + var lib_5$1 = lib$1.IIWebUSB; + var lib_6$1 = lib$1.ledgerUSBVendorId; + var lib_7$1 = lib$1.getDeviceModel; + var lib_8$1 = lib$1.identifyUSBProductId; + var lib_9$1 = lib$1.getBluetoothServiceUuids; + var lib_10$1 = lib$1.getInfosForServiceUuid; + + var lib$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + + /** + * A Log object + */ + var id = 0; + var subscribers = []; + + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = exports.log = function log(type, message, data) { + var obj = { type: type, id: String(++id), date: new Date() }; + if (message) obj.message = message; + if (data) obj.data = data; + dispatch(obj); + }; + + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = exports.listen = function listen(cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } catch (e) { + console.error(e); + } + } + } + + // for debug purpose + commonjsGlobal.__ledgerLogsListen = listen; + + }); + + unwrapExports(lib$2); + var lib_1$2 = lib$2.log; + var lib_2$2 = lib$2.listen; + + var webusb = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isSupported = exports.getFirstLedgerDevice = exports.getLedgerDevices = exports.requestLedgerDevice = undefined; + + var requestLedgerDevice = exports.requestLedgerDevice = function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + var device; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return navigator.usb.requestDevice({ filters: ledgerDevices }); + + case 2: + device = _context.sent; + return _context.abrupt("return", device); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function requestLedgerDevice() { + return _ref.apply(this, arguments); + }; + }(); + + var getLedgerDevices = exports.getLedgerDevices = function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var devices; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return navigator.usb.getDevices(); + + case 2: + devices = _context2.sent; + return _context2.abrupt("return", devices.filter(function (d) { + return d.vendorId === lib$1.ledgerUSBVendorId; + })); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function getLedgerDevices() { + return _ref2.apply(this, arguments); + }; + }(); + + var getFirstLedgerDevice = exports.getFirstLedgerDevice = function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var existingDevices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getLedgerDevices(); + + case 2: + existingDevices = _context3.sent; + + if (!(existingDevices.length > 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", existingDevices[0]); + + case 5: + return _context3.abrupt("return", requestLedgerDevice()); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function getFirstLedgerDevice() { + return _ref3.apply(this, arguments); + }; + }(); + + + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + var ledgerDevices = [{ vendorId: lib$1.ledgerUSBVendorId }]; + + var isSupported = exports.isSupported = function isSupported() { + return Promise.resolve( + // $FlowFixMe + !!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); + }; + + }); + + unwrapExports(webusb); + var webusb_1 = webusb.isSupported; + var webusb_2 = webusb.getFirstLedgerDevice; + var webusb_3 = webusb.getLedgerDevices; + var webusb_4 = webusb.requestLedgerDevice; + + var TransportWebUSB_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + + + var _hwTransport2 = _interopRequireDefault(Transport_1); + + + + var _hidFraming2 = _interopRequireDefault(hidFraming); + + + + + + + + + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var configurationValue = 1; + var interfaceNumber = 2; + var endpointNumber = 3; + + /** + * WebUSB Transport implementation + * @example + * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ + + var TransportWebUSB = function (_Transport) { + _inherits(TransportWebUSB, _Transport); + + function TransportWebUSB(device) { + _classCallCheck(this, TransportWebUSB); + + var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); + + _initialiseProps.call(_this); + + _this.device = device; + _this.deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); + return _this; + } + + /** + * Check if WebUSB transport is supported. + */ + + + /** + * List the WebUSB devices that was previously authorized by the user. + */ + + + /** + * Actively listen to WebUSB devices and emit ONE device + * that was either accepted before, if not it will trigger the native permission UI. + * + * Important: it must be called in the context of a UI click! + */ + + + _createClass(TransportWebUSB, [{ + key: "close", + + + /** + * Release the transport device + */ + value: function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.exchangeBusyPromise; + + case 2: + _context.next = 4; + return this.device.releaseInterface(interfaceNumber); + + case 4: + _context.next = 6; + return this.device.reset(); + + case 6: + _context.next = 8; + return this.device.close(); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _ref.apply(this, arguments); + } + + return close; + }() + + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + + }, { + key: "setScrambleKey", + value: function setScrambleKey() {} + }], [{ + key: "request", + + + /** + * Similar to create() except it will always display the device permission (even if some devices are already accepted). + */ + value: function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var device; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, webusb.requestLedgerDevice)(); + + case 2: + device = _context2.sent; + return _context2.abrupt("return", TransportWebUSB.open(device)); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function request() { + return _ref2.apply(this, arguments); + } + + return request; + }() + + /** + * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). + */ + + }, { + key: "openConnected", + value: function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var devices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, webusb.getLedgerDevices)(); + + case 2: + devices = _context3.sent; + + if (!(devices.length === 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", null); + + case 5: + return _context3.abrupt("return", TransportWebUSB.open(devices[0])); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function openConnected() { + return _ref3.apply(this, arguments); + } + + return openConnected; + }() + + /** + * Create a Ledger transport with a USBDevice + */ + + }, { + key: "open", + value: function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { + var transport, onDisconnect; + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return device.open(); + + case 2: + if (!(device.configuration === null)) { + _context4.next = 5; + break; + } + + _context4.next = 5; + return device.selectConfiguration(configurationValue); + + case 5: + _context4.next = 7; + return device.reset(); + + case 7: + _context4.prev = 7; + _context4.next = 10; + return device.claimInterface(interfaceNumber); + + case 10: + _context4.next = 17; + break; + + case 12: + _context4.prev = 12; + _context4.t0 = _context4["catch"](7); + _context4.next = 16; + return device.close(); + + case 16: + throw new lib.TransportInterfaceNotAvailable(_context4.t0.message); + + case 17: + transport = new TransportWebUSB(device); + + onDisconnect = function onDisconnect(e) { + if (device === e.device) { + // $FlowFixMe + navigator.usb.removeEventListener("disconnect", onDisconnect); + transport._emitDisconnect(new lib.DisconnectedDevice()); + } + }; + // $FlowFixMe + + + navigator.usb.addEventListener("disconnect", onDisconnect); + return _context4.abrupt("return", transport); + + case 21: + case "end": + return _context4.stop(); + } + } + }, _callee4, this, [[7, 12]]); + })); + + function open(_x) { + return _ref4.apply(this, arguments); + } + + return open; + }() + }]); + + return TransportWebUSB; + }(_hwTransport2.default); + + TransportWebUSB.isSupported = webusb.isSupported; + TransportWebUSB.list = webusb.getLedgerDevices; + + TransportWebUSB.listen = function (observer) { + var unsubscribed = false; + (0, webusb.getFirstLedgerDevice)().then(function (device) { + if (!unsubscribed) { + var deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); + observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); + observer.complete(); + } + }, function (error) { + observer.error(new lib.TransportOpenUserCancelled(error.message)); + }); + function unsubscribe() { + unsubscribed = true; + } + return { unsubscribe: unsubscribe }; + }; + + var _initialiseProps = function _initialiseProps() { + var _this2 = this; + + this.channel = Math.floor(Math.random() * 0xffff); + this.packetSize = 64; + this._disconnectEmitted = false; + + this._emitDisconnect = function (e) { + if (_this2._disconnectEmitted) return; + _this2._disconnectEmitted = true; + _this2.emit("disconnect", e); + }; + + this.exchange = function (apdu) { + return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { + var channel, packetSize, framing, blocks, i, result, acc, r, buffer; + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + channel = _this2.channel, packetSize = _this2.packetSize; + + (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); + + framing = (0, _hidFraming2.default)(channel, packetSize); + + // Write... + + blocks = framing.makeBlocks(apdu); + i = 0; + + case 5: + if (!(i < blocks.length)) { + _context5.next = 12; + break; + } + + (0, lib$2.log)("hid-frame", "=> " + blocks[i].toString("hex")); + _context5.next = 9; + return _this2.device.transferOut(endpointNumber, blocks[i]); + + case 9: + i++; + _context5.next = 5; + break; + + case 12: + + // Read... + result = void 0; + acc = void 0; + + case 14: + if (result = framing.getReducedResult(acc)) { + _context5.next = 23; + break; + } + + _context5.next = 17; + return _this2.device.transferIn(endpointNumber, packetSize); + + case 17: + r = _context5.sent; + buffer = Buffer.from(r.data.buffer); + + (0, lib$2.log)("hid-frame", "<= " + buffer.toString("hex")); + acc = framing.reduceResponse(acc, buffer); + _context5.next = 14; + break; + + case 23: + + (0, lib$2.log)("apdu", "<= " + result.toString("hex")); + return _context5.abrupt("return", result); + + case 25: + case "end": + return _context5.stop(); + } + } + }, _callee5, _this2); + }))).catch(function (e) { + if (e && e.message && e.message.includes("disconnected")) { + _this2._emitDisconnect(e); + throw new lib.DisconnectedDeviceDuringOperation(e.message); + } + throw e; + }); + }; + }; + + exports.default = TransportWebUSB; + + }); + + var TransportWebUSB = unwrapExports(TransportWebUSB_1); + + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ + default: TransportWebUSB, + __moduleExports: TransportWebUSB_1 + }); + + exports.Btc = Btc$1; + exports.TransportWebUSB = TransportWebUSB$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 0cbb82a2528d679700bb4eab754f0b05b5ae6fcd Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 17 Jan 2022 20:45:06 +1100 Subject: [PATCH 06/78] export --- js/ledger.js | 233 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 156 insertions(+), 77 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index b06dba2e..567e8446 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1038,6 +1038,7 @@ window.Buffer = buffer.Buffer; throw new Error("getTrustedInput: locktime & outputs is expected"); } var isDecred = additionals.includes("decred"); + var isXST = additionals.includes("stealthcoin"); var processScriptBlocks = function processScriptBlocks(script, sequence) { var scriptBlocks = []; var offset = 0; @@ -1062,19 +1063,20 @@ window.Buffer = buffer.Buffer; }); }; - var processWholeScriptBlock = function processWholeScriptBlock(script, sequence) { - return _this.getTrustedInputRaw(Buffer.concat([script, sequence])); + var processWholeScriptBlock = function processWholeScriptBlock(block) { + return _this.getTrustedInputRaw(block); }; var processInputs = function processInputs() { return (0, utils.eachSeries)(inputs, function (input) { var treeField = isDecred ? input.tree || Buffer.from([0x00]) : Buffer.alloc(0); - var data = Buffer.concat([input.prevout, treeField, _this.createVarint(input.script.length)]); + var data = Buffer.concat([input.prevout, treeField, isXST ? Buffer.from([0x00]) : _this.createVarint(input.script.length)]); return _this.getTrustedInputRaw(data).then(function () { // iteration (eachSeries) ended // TODO notify progress // deferred.notify("input"); - return isDecred ? processWholeScriptBlock(input.script, input.sequence) : processScriptBlocks(input.script, input.sequence); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return isDecred ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) : isXST ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence); }); }).then(function () { var data = _this.createVarint(outputs.length); @@ -1651,11 +1653,12 @@ window.Buffer = buffer.Buffer; value: function signP2SHTransaction(inputs, associatedKeysets, outputScriptHex) { var lockTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_LOCKTIME; var sigHashType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SIGHASH_ALL; + var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var _this6 = this; - var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var transactionVersion = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_VERSION; + var timeStamp = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; // Inputs are provided as arrays of [transaction, output_index, redeem script, optional sequence] // associatedKeysets are provided as arrays of [path] @@ -1663,6 +1666,8 @@ window.Buffer = buffer.Buffer; var nullPrevout = Buffer.alloc(0); var defaultVersion = Buffer.alloc(4); defaultVersion.writeUInt32LE(transactionVersion, 0); + var defaultTime = Buffer.alloc(4); + defaultTime.writeUInt32LE(timeStamp, 0); var trustedInputs = []; var regularOutputs = []; var signatures = []; @@ -1673,6 +1678,9 @@ window.Buffer = buffer.Buffer; version: defaultVersion }; + if (timeStamp > 0) { + targetTransaction.timestamp = defaultTime; + } var getTrustedInputCall = segwit ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); var outputScript = Buffer.from(outputScriptHex, "hex"); @@ -1731,7 +1739,7 @@ window.Buffer = buffer.Buffer; }); }).then(function () { return _this6.signTransaction(associatedKeysets[i], lockTime, sigHashType).then(function (signature) { - signatures.push(segwit ? signature.toString("hex") : signature.slice(0, signature.length - 1).toString("hex")); + signatures.push(signature.toString("hex")); targetTransaction.inputs[i].script = nullScript; if (firstRun) { firstRun = false; @@ -2644,7 +2652,7 @@ window.Buffer = buffer.Buffer; Object.defineProperty(exports, "__esModule", { value: true }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; + exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeTooHigh = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongAppForCurrency = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportWebUSBGestureRequired = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnavailableTezosOriginatedAccountSend = exports.UnavailableTezosOriginatedAccountReceive = exports.RecipientRequired = exports.MCUNotGenuineToDashboard = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.RecommendUndelegation = exports.RecommendSubAccountsToEmpty = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.GasLessThanEstimate = exports.NotSupportedLegacyAddress = exports.NotEnoughGas = exports.NoAccessToCamera = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughSpendableBalance = exports.NotEnoughBalanceInParentAccount = exports.NotEnoughBalanceToDelegate = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerFirmwareNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppDepUninstallRequired = exports.ManagerAppDepInstallRequired = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.InvalidXRPTag = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardUnexpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AmountRequired = exports.AccountNotSupported = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; exports.TransportError = TransportError; exports.getAltStatusMessage = getAltStatusMessage; exports.TransportStatusError = TransportStatusError; @@ -2656,14 +2664,18 @@ window.Buffer = buffer.Buffer; exports.createCustomErrorClass = helpers.createCustomErrorClass; exports.addCustomErrorDeserializer = helpers.addCustomErrorDeserializer; var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers.createCustomErrorClass)("AccountNameRequired"); + var AccountNotSupported = exports.AccountNotSupported = (0, helpers.createCustomErrorClass)("AccountNotSupported"); + var AmountRequired = exports.AmountRequired = (0, helpers.createCustomErrorClass)("AmountRequired"); var BluetoothRequired = exports.BluetoothRequired = (0, helpers.createCustomErrorClass)("BluetoothRequired"); var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers.createCustomErrorClass)("BtcUnmatchedApp"); var CantOpenDevice = exports.CantOpenDevice = (0, helpers.createCustomErrorClass)("CantOpenDevice"); + var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers.createCustomErrorClass)("CashAddrNotSupported"); var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers.createCustomErrorClass)("CurrencyNotSupported"); var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers.createCustomErrorClass)("DeviceNotGenuine"); var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = exports.DeviceOnDashboardUnexpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers.createCustomErrorClass)("DeviceInOSUExpected"); var DeviceHalted = exports.DeviceHalted = (0, helpers.createCustomErrorClass)("DeviceHalted"); var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers.createCustomErrorClass)("DeviceNameInvalid"); @@ -2675,6 +2687,7 @@ window.Buffer = buffer.Buffer; var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers.createCustomErrorClass)("FeeEstimationFailed"); var HardResetFail = exports.HardResetFail = (0, helpers.createCustomErrorClass)("HardResetFail"); + var InvalidXRPTag = exports.InvalidXRPTag = (0, helpers.createCustomErrorClass)("InvalidXRPTag"); var InvalidAddress = exports.InvalidAddress = (0, helpers.createCustomErrorClass)("InvalidAddress"); var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers.createCustomErrorClass)("LatestMCUInstalledError"); @@ -2684,17 +2697,33 @@ window.Buffer = buffer.Buffer; var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers.createCustomErrorClass)("LedgerAPINotAvailable"); var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = exports.ManagerAppDepInstallRequired = (0, helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = exports.ManagerAppDepUninstallRequired = (0, helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers.createCustomErrorClass)("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = exports.ManagerFirmwareNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); var NetworkDown = exports.NetworkDown = (0, helpers.createCustomErrorClass)("NetworkDown"); var NoAddressesFound = exports.NoAddressesFound = (0, helpers.createCustomErrorClass)("NoAddressesFound"); var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers.createCustomErrorClass)("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = exports.NotEnoughBalanceToDelegate = (0, helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = exports.NotEnoughBalanceInParentAccount = (0, helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = exports.NotEnoughSpendableBalance = (0, helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = exports.NoAccessToCamera = (0, helpers.createCustomErrorClass)("NoAccessToCamera"); + var NotEnoughGas = exports.NotEnoughGas = (0, helpers.createCustomErrorClass)("NotEnoughGas"); + var NotSupportedLegacyAddress = exports.NotSupportedLegacyAddress = (0, helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); + var GasLessThanEstimate = exports.GasLessThanEstimate = (0, helpers.createCustomErrorClass)("GasLessThanEstimate"); var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers.createCustomErrorClass)("PasswordsDontMatch"); var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers.createCustomErrorClass)("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = exports.RecommendSubAccountsToEmpty = (0, helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = exports.RecommendUndelegation = (0, helpers.createCustomErrorClass)("RecommendUndelegation"); var TimeoutTagged = exports.TimeoutTagged = (0, helpers.createCustomErrorClass)("TimeoutTagged"); var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers.createCustomErrorClass)("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = exports.MCUNotGenuineToDashboard = (0, helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); + var RecipientRequired = exports.RecipientRequired = (0, helpers.createCustomErrorClass)("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = exports.UnavailableTezosOriginatedAccountReceive = (0, helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = exports.UnavailableTezosOriginatedAccountSend = (0, helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); var UpdateYourApp = exports.UpdateYourApp = (0, helpers.createCustomErrorClass)("UpdateYourApp"); var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers.createCustomErrorClass)("UserRefusedAddress"); @@ -2703,14 +2732,17 @@ window.Buffer = buffer.Buffer; var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers.createCustomErrorClass)("TransportOpenUserCancelled"); var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); + var TransportWebUSBGestureRequired = exports.TransportWebUSBGestureRequired = (0, helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers.createCustomErrorClass)("DeviceShouldStayInApp"); var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers.createCustomErrorClass)("WebsocketConnectionError"); var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers.createCustomErrorClass)("WebsocketConnectionFailed"); var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers.createCustomErrorClass)("WrongDeviceForAccount"); + var WrongAppForCurrency = exports.WrongAppForCurrency = (0, helpers.createCustomErrorClass)("WrongAppForCurrency"); var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers.createCustomErrorClass)("ETHAddressNonEIP"); var CantScanQRCode = exports.CantScanQRCode = (0, helpers.createCustomErrorClass)("CantScanQRCode"); var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers.createCustomErrorClass)("FeeNotLoaded"); var FeeRequired = exports.FeeRequired = (0, helpers.createCustomErrorClass)("FeeRequired"); + var FeeTooHigh = exports.FeeTooHigh = (0, helpers.createCustomErrorClass)("FeeTooHigh"); var SyncError = exports.SyncError = (0, helpers.createCustomErrorClass)("SyncError"); var PairingFailed = exports.PairingFailed = (0, helpers.createCustomErrorClass)("PairingFailed"); var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers.createCustomErrorClass)("GenuineCheckFailed"); @@ -2828,69 +2860,93 @@ window.Buffer = buffer.Buffer; var lib_8 = lib.GenuineCheckFailed; var lib_9 = lib.PairingFailed; var lib_10 = lib.SyncError; - var lib_11 = lib.FeeRequired; - var lib_12 = lib.FeeNotLoaded; - var lib_13 = lib.CantScanQRCode; - var lib_14 = lib.ETHAddressNonEIP; - var lib_15 = lib.WrongDeviceForAccount; - var lib_16 = lib.WebsocketConnectionFailed; - var lib_17 = lib.WebsocketConnectionError; - var lib_18 = lib.DeviceShouldStayInApp; - var lib_19 = lib.TransportInterfaceNotAvailable; - var lib_20 = lib.TransportOpenUserCancelled; - var lib_21 = lib.UserRefusedOnDevice; - var lib_22 = lib.UserRefusedAllowManager; - var lib_23 = lib.UserRefusedFirmwareUpdate; - var lib_24 = lib.UserRefusedAddress; - var lib_25 = lib.UserRefusedDeviceNameChange; - var lib_26 = lib.UpdateYourApp; - var lib_27 = lib.UnexpectedBootloader; - var lib_28 = lib.TimeoutTagged; - var lib_29 = lib.PasswordIncorrectError; - var lib_30 = lib.PasswordsDontMatchError; - var lib_31 = lib.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_32 = lib.NotEnoughBalance; - var lib_33 = lib.NoAddressesFound; - var lib_34 = lib.NetworkDown; - var lib_35 = lib.ManagerUninstallBTCDep; - var lib_36 = lib.ManagerNotEnoughSpaceError; - var lib_37 = lib.ManagerDeviceLockedError; - var lib_38 = lib.ManagerAppRelyOnBTCError; - var lib_39 = lib.ManagerAppAlreadyInstalledError; - var lib_40 = lib.LedgerAPINotAvailable; - var lib_41 = lib.LedgerAPIErrorWithMessage; - var lib_42 = lib.LedgerAPIError; - var lib_43 = lib.UnknownMCU; - var lib_44 = lib.LatestMCUInstalledError; - var lib_45 = lib.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_46 = lib.InvalidAddress; - var lib_47 = lib.HardResetFail; - var lib_48 = lib.FeeEstimationFailed; - var lib_49 = lib.EthAppPleaseEnableContractData; - var lib_50 = lib.EnpointConfigError; - var lib_51 = lib.DisconnectedDeviceDuringOperation; - var lib_52 = lib.DisconnectedDevice; - var lib_53 = lib.DeviceSocketNoBulkStatus; - var lib_54 = lib.DeviceSocketFail; - var lib_55 = lib.DeviceNameInvalid; - var lib_56 = lib.DeviceHalted; - var lib_57 = lib.DeviceInOSUExpected; - var lib_58 = lib.DeviceOnDashboardExpected; - var lib_59 = lib.DeviceNotGenuineError; - var lib_60 = lib.DeviceGenuineSocketEarlyClose; - var lib_61 = lib.DeviceAppVerifyNotSupported; - var lib_62 = lib.CurrencyNotSupported; - var lib_63 = lib.CantOpenDevice; - var lib_64 = lib.BtcUnmatchedApp; - var lib_65 = lib.BluetoothRequired; - var lib_66 = lib.AccountNameRequiredError; - var lib_67 = lib.addCustomErrorDeserializer; - var lib_68 = lib.createCustomErrorClass; - var lib_69 = lib.deserializeError; - var lib_70 = lib.serializeError; - var lib_71 = lib.TransportError; - var lib_72 = lib.getAltStatusMessage; - var lib_73 = lib.TransportStatusError; + var lib_11 = lib.FeeTooHigh; + var lib_12 = lib.FeeRequired; + var lib_13 = lib.FeeNotLoaded; + var lib_14 = lib.CantScanQRCode; + var lib_15 = lib.ETHAddressNonEIP; + var lib_16 = lib.WrongAppForCurrency; + var lib_17 = lib.WrongDeviceForAccount; + var lib_18 = lib.WebsocketConnectionFailed; + var lib_19 = lib.WebsocketConnectionError; + var lib_20 = lib.DeviceShouldStayInApp; + var lib_21 = lib.TransportWebUSBGestureRequired; + var lib_22 = lib.TransportInterfaceNotAvailable; + var lib_23 = lib.TransportOpenUserCancelled; + var lib_24 = lib.UserRefusedOnDevice; + var lib_25 = lib.UserRefusedAllowManager; + var lib_26 = lib.UserRefusedFirmwareUpdate; + var lib_27 = lib.UserRefusedAddress; + var lib_28 = lib.UserRefusedDeviceNameChange; + var lib_29 = lib.UpdateYourApp; + var lib_30 = lib.UnavailableTezosOriginatedAccountSend; + var lib_31 = lib.UnavailableTezosOriginatedAccountReceive; + var lib_32 = lib.RecipientRequired; + var lib_33 = lib.MCUNotGenuineToDashboard; + var lib_34 = lib.UnexpectedBootloader; + var lib_35 = lib.TimeoutTagged; + var lib_36 = lib.RecommendUndelegation; + var lib_37 = lib.RecommendSubAccountsToEmpty; + var lib_38 = lib.PasswordIncorrectError; + var lib_39 = lib.PasswordsDontMatchError; + var lib_40 = lib.GasLessThanEstimate; + var lib_41 = lib.NotSupportedLegacyAddress; + var lib_42 = lib.NotEnoughGas; + var lib_43 = lib.NoAccessToCamera; + var lib_44 = lib.NotEnoughBalanceBecauseDestinationNotCreated; + var lib_45 = lib.NotEnoughSpendableBalance; + var lib_46 = lib.NotEnoughBalanceInParentAccount; + var lib_47 = lib.NotEnoughBalanceToDelegate; + var lib_48 = lib.NotEnoughBalance; + var lib_49 = lib.NoAddressesFound; + var lib_50 = lib.NetworkDown; + var lib_51 = lib.ManagerUninstallBTCDep; + var lib_52 = lib.ManagerNotEnoughSpaceError; + var lib_53 = lib.ManagerFirmwareNotEnoughSpaceError; + var lib_54 = lib.ManagerDeviceLockedError; + var lib_55 = lib.ManagerAppDepUninstallRequired; + var lib_56 = lib.ManagerAppDepInstallRequired; + var lib_57 = lib.ManagerAppRelyOnBTCError; + var lib_58 = lib.ManagerAppAlreadyInstalledError; + var lib_59 = lib.LedgerAPINotAvailable; + var lib_60 = lib.LedgerAPIErrorWithMessage; + var lib_61 = lib.LedgerAPIError; + var lib_62 = lib.UnknownMCU; + var lib_63 = lib.LatestMCUInstalledError; + var lib_64 = lib.InvalidAddressBecauseDestinationIsAlsoSource; + var lib_65 = lib.InvalidAddress; + var lib_66 = lib.InvalidXRPTag; + var lib_67 = lib.HardResetFail; + var lib_68 = lib.FeeEstimationFailed; + var lib_69 = lib.EthAppPleaseEnableContractData; + var lib_70 = lib.EnpointConfigError; + var lib_71 = lib.DisconnectedDeviceDuringOperation; + var lib_72 = lib.DisconnectedDevice; + var lib_73 = lib.DeviceSocketNoBulkStatus; + var lib_74 = lib.DeviceSocketFail; + var lib_75 = lib.DeviceNameInvalid; + var lib_76 = lib.DeviceHalted; + var lib_77 = lib.DeviceInOSUExpected; + var lib_78 = lib.DeviceOnDashboardUnexpected; + var lib_79 = lib.DeviceOnDashboardExpected; + var lib_80 = lib.DeviceNotGenuineError; + var lib_81 = lib.DeviceGenuineSocketEarlyClose; + var lib_82 = lib.DeviceAppVerifyNotSupported; + var lib_83 = lib.CurrencyNotSupported; + var lib_84 = lib.CashAddrNotSupported; + var lib_85 = lib.CantOpenDevice; + var lib_86 = lib.BtcUnmatchedApp; + var lib_87 = lib.BluetoothRequired; + var lib_88 = lib.AmountRequired; + var lib_89 = lib.AccountNotSupported; + var lib_90 = lib.AccountNameRequiredError; + var lib_91 = lib.addCustomErrorDeserializer; + var lib_92 = lib.createCustomErrorClass; + var lib_93 = lib.deserializeError; + var lib_94 = lib.serializeError; + var lib_95 = lib.TransportError; + var lib_96 = lib.getAltStatusMessage; + var lib_97 = lib.TransportStatusError; var Transport_1 = createCommonjsModule(function (module, exports) { @@ -3457,23 +3513,29 @@ window.Buffer = buffer.Buffer; blue: { id: "blue", productName: "Ledger Blue", - productIdMM: 0, + productIdMM: 0x00, legacyUsbProductId: 0x0000, - usbOnly: true + usbOnly: true, + memorySize: 480 * 1024, + blockSize: 4 * 1024 }, nanoS: { id: "nanoS", productName: "Ledger Nano S", - productIdMM: 1, + productIdMM: 0x10, legacyUsbProductId: 0x0001, - usbOnly: true + usbOnly: true, + memorySize: 320 * 1024, + blockSize: 4 * 1024 }, nanoX: { id: "nanoX", productName: "Ledger Nano X", - productIdMM: 4, + productIdMM: 0x40, legacyUsbProductId: 0x0004, usbOnly: false, + memorySize: 2 * 1024 * 1024, + blockSize: 4 * 1024, bluetoothSpec: [{ // this is the legacy one (prototype version). we will eventually drop it. serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", @@ -3487,6 +3549,12 @@ window.Buffer = buffer.Buffer; } }; + var productMap = { + Blue: "blue", + "Nano S": "nanoS", + "Nano X": "nanoX" + }; + // $FlowFixMe var devicesList = Object.values(devices); @@ -3512,6 +3580,7 @@ window.Buffer = buffer.Buffer; return d.legacyUsbProductId === usbProductId; }); if (legacy) return legacy; + var mm = usbProductId >> 8; var deviceModel = devicesList.find(function (d) { return d.productIdMM === mm; @@ -3519,6 +3588,15 @@ window.Buffer = buffer.Buffer; return deviceModel; }; + var identifyProductName = exports.identifyProductName = function identifyProductName(productName) { + var productId = productMap[productName]; + var deviceModel = devicesList.find(function (d) { + return d.id === productId; + }); + + return deviceModel; + }; + var bluetoothServices = []; var serviceUuidToInfos = {}; @@ -3574,8 +3652,9 @@ window.Buffer = buffer.Buffer; var lib_6$1 = lib$1.ledgerUSBVendorId; var lib_7$1 = lib$1.getDeviceModel; var lib_8$1 = lib$1.identifyUSBProductId; - var lib_9$1 = lib$1.getBluetoothServiceUuids; - var lib_10$1 = lib$1.getInfosForServiceUuid; + var lib_9$1 = lib$1.identifyProductName; + var lib_10$1 = lib$1.getBluetoothServiceUuids; + var lib_11$1 = lib$1.getInfosForServiceUuid; var lib$2 = createCommonjsModule(function (module, exports) { From f542cf2e24c9f95b0c1b240529f6be1c3ae9fcab Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 13:08:55 +1100 Subject: [PATCH 07/78] another day another ledger --- js/ledger.js | 4256 +------------------------------------------------- 1 file changed, 1 insertion(+), 4255 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 567e8446..36c47c91 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,4261 +2,7 @@ window.global = window; window.Buffer = buffer.Buffer; -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.NewLedger = {}))); -}(this, (function (exports) { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - var runtime_1 = createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - - }( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports - )); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); - } - }); - - var utils = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.defer = defer; - exports.splitPath = splitPath; - exports.eachSeries = eachSeries; - exports.foreach = foreach; - exports.doIf = doIf; - exports.asyncWhile = asyncWhile; - function defer() { - var resolve = void 0, - reject = void 0; - var promise = new Promise(function (success, failure) { - resolve = success; - reject = failure; - }); - if (!resolve || !reject) throw "defer() error"; // this never happens and is just to make flow happy - return { promise: promise, resolve: resolve, reject: reject }; - } - - // TODO use bip32-path library - /******************************************************************************** - * Ledger Node JS API - * (c) 2016-2017 Ledger - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ********************************************************************************/ - - - function splitPath(path) { - var result = []; - var components = path.split("/"); - components.forEach(function (element) { - var number = parseInt(element, 10); - if (isNaN(number)) { - return; // FIXME shouldn't it throws instead? - } - if (element.length > 1 && element[element.length - 1] === "'") { - number += 0x80000000; - } - result.push(number); - }); - return result; - } - - // TODO use async await - - function eachSeries(arr, fun) { - return arr.reduce(function (p, e) { - return p.then(function () { - return fun(e); - }); - }, Promise.resolve()); - } - - function foreach(arr, callback) { - function iterate(index, array, result) { - if (index >= array.length) { - return result; - } else return callback(array[index], index).then(function (res) { - result.push(res); - return iterate(index + 1, array, result); - }); - } - return Promise.resolve().then(function () { - return iterate(0, arr, []); - }); - } - - function doIf(condition, callback) { - return Promise.resolve().then(function () { - if (condition) { - return callback(); - } - }); - } - - function asyncWhile(predicate, callback) { - function iterate(result) { - if (!predicate()) { - return result; - } else { - return callback().then(function (res) { - result.push(res); - return iterate(result); - }); - } - } - return Promise.resolve([]).then(iterate); - } - - var isLedgerDevice = exports.isLedgerDevice = function isLedgerDevice(device) { - return device.vendorId === 0x2581 && device.productId === 0x3b7c || device.vendorId === 0x2c97; - }; - - }); - - unwrapExports(utils); - var utils_1 = utils.defer; - var utils_2 = utils.splitPath; - var utils_3 = utils.eachSeries; - var utils_4 = utils.foreach; - var utils_5 = utils.doIf; - var utils_6 = utils.asyncWhile; - var utils_7 = utils.isLedgerDevice; - - var require$$0 = {}; - - var createHash = require$$0.createHash; - - var Btc_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - // TODO future refactoring - // - drop utils.js & refactoring with async/await style - // - try to avoid every place we do hex<>Buffer conversion. also accept Buffer as func parameters (could accept both a string or a Buffer in the API) - // - there are redundant code across apps (see Eth vs Btc). we might want to factorize it somewhere. also each app apdu call should be abstracted it out as an api - - - - - - - var _createHash2 = _interopRequireDefault(createHash); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - /** - * address format is one of legacy | p2sh | bech32 - */ - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2 - }; - - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - - var Btc = function () { - function Btc(transport) { - var scrambleKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "BTC"; - - _classCallCheck(this, Btc); - - this.transport = transport; - transport.decorateAppAPIMethods(this, ["getWalletPublicKey", "signP2SHTransaction", "signMessageNew", "createPaymentTransactionNew"], scrambleKey); - } - - _createClass(Btc, [{ - key: "hashPublicKey", - value: function hashPublicKey(buffer) { - return (0, _createHash2.default)("rmd160").update((0, _createHash2.default)("sha256").update(buffer).digest()).digest(); - } - }, { - key: "getWalletPublicKey_private", - value: function getWalletPublicKey_private(path) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var _verify$format$option = _extends({ - verify: false, - format: "legacy" - }, options), - verify = _verify$format$option.verify, - format = _verify$format$option.format; - - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - var paths = (0, utils.splitPath)(path); - var p1 = verify ? 1 : 0; - var p2 = addressFormatMap[format]; - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x40, p1, p2, buffer).then(function (response) { - var publicKeyLength = response[0]; - var addressLength = response[1 + publicKeyLength]; - var publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - var bitcoinAddress = response.slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength).toString("ascii"); - var chainCode = response.slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32).toString("hex"); - return { publicKey: publicKey, bitcoinAddress: bitcoinAddress, chainCode: chainCode }; - }); - } - - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - - }, { - key: "getWalletPublicKey", - value: function getWalletPublicKey(path, opts) { - var options = void 0; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - format: arguments[2] ? "p2sh" : "legacy" - }; - } else { - options = opts || {}; - } - return this.getWalletPublicKey_private(path, options); - } - }, { - key: "getTrustedInputRaw", - value: function getTrustedInputRaw(transactionData, indexLookup) { - var data = void 0; - var firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - var prefix = Buffer.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer.concat([prefix, transactionData], transactionData.length + 4); - } else { - data = transactionData; - } - return this.transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data).then(function (trustedInput) { - return trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - }); - } - }, { - key: "getTrustedInput", - value: function getTrustedInput(indexLookup, transaction) { - var _this = this; - - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var inputs = transaction.inputs, - outputs = transaction.outputs, - locktime = transaction.locktime; - - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var processScriptBlocks = function processScriptBlocks(script, sequence) { - var scriptBlocks = []; - var offset = 0; - while (offset !== script.length) { - var blockSize = script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), sequence])); - } - offset += blockSize; - } - - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(sequence); - } - - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this.getTrustedInputRaw(scriptBlock); - }); - }; - - var processWholeScriptBlock = function processWholeScriptBlock(block) { - return _this.getTrustedInputRaw(block); - }; - - var processInputs = function processInputs() { - return (0, utils.eachSeries)(inputs, function (input) { - var treeField = isDecred ? input.tree || Buffer.from([0x00]) : Buffer.alloc(0); - var data = Buffer.concat([input.prevout, treeField, isXST ? Buffer.from([0x00]) : _this.createVarint(input.script.length)]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return isDecred ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) : isXST ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence); - }); - }).then(function () { - var data = _this.createVarint(outputs.length); - return _this.getTrustedInputRaw(data); - }); - }; - - var processOutputs = function processOutputs() { - return (0, utils.eachSeries)(outputs, function (output) { - var data = output.amount; - data = Buffer.concat([data, isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), //Version script - _this.createVarint(output.script.length), output.script]); - return _this.getTrustedInputRaw(data).then(function () { - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("output"); - }); - }).then(function () { - //Add expiry height for decred - var finalData = isDecred ? Buffer.concat([locktime, Buffer.from([0x00, 0x00, 0x00, 0x00])]) : locktime; - return _this.getTrustedInputRaw(finalData); - }); - }; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), this.createVarint(inputs.length)]); - return this.getTrustedInputRaw(data, indexLookup).then(processInputs).then(processOutputs); - } - }, { - key: "getTrustedInputBIP143", - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(indexLookup, transaction) { - var additionals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var isDecred, sha, hash, data, outputs, locktime; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (transaction) { - _context.next = 2; - break; - } - - throw new Error("getTrustedInputBIP143: missing tx"); - - case 2: - isDecred = additionals.includes("decred"); - - if (!isDecred) { - _context.next = 5; - break; - } - - throw new Error("Decred does not implement BIP143"); - - case 5: - sha = (0, _createHash2.default)("sha256"); - - sha.update(this.serializeTransaction(transaction, true)); - hash = sha.digest(); - - sha = (0, _createHash2.default)("sha256"); - sha.update(hash); - hash = sha.digest(); - data = Buffer.alloc(4); - - data.writeUInt32LE(indexLookup, 0); - outputs = transaction.outputs, locktime = transaction.locktime; - - if (!(!outputs || !locktime)) { - _context.next = 16; - break; - } - - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - - case 16: - if (outputs[indexLookup]) { - _context.next = 18; - break; - } - - throw new Error("getTrustedInputBIP143: wrong index"); - - case 18: - hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); - _context.next = 21; - return hash.toString("hex"); - - case 21: - return _context.abrupt("return", _context.sent); - - case 22: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function getTrustedInputBIP143(_x4, _x5) { - return _ref.apply(this, arguments); - } - - return getTrustedInputBIP143; - }() - }, { - key: "getVarint", - value: function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [(data[offset + 4] << 24) + (data[offset + 3] << 16) + (data[offset + 2] << 8) + data[offset + 1], 5]; - } - - throw new Error("getVarint called with unexpected parameters"); - } - }, { - key: "startUntrustedHashTransactionInputRaw", - value: function startUntrustedHashTransactionInputRaw(newTransaction, firstRound, transactionData) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var p2 = bip143 ? additionals.includes("sapling") ? 0x05 : overwinter ? 0x04 : 0x02 : 0x00; - return this.transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - }, { - key: "startUntrustedHashTransactionInput", - value: function startUntrustedHashTransactionInput(newTransaction, transaction, inputs) { - var bip143 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - - var _this2 = this; - - var overwinter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var additionals = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; - - var data = Buffer.concat([transaction.version, transaction.timestamp || Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), this.createVarint(transaction.inputs.length)]); - return this.startUntrustedHashTransactionInputRaw(newTransaction, true, data, bip143, overwinter, additionals).then(function () { - var i = 0; - var isDecred = additionals.includes("decred"); - return (0, utils.eachSeries)(transaction.inputs, function (input) { - var prefix = void 0; - if (bip143) { - prefix = Buffer.from([0x02]); - } else { - if (inputs[i].trustedInput) { - prefix = Buffer.from([0x01, inputs[i].value.length]); - } else { - prefix = Buffer.from([0x00]); - } - } - data = Buffer.concat([prefix, inputs[i].value, isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), _this2.createVarint(input.script.length)]); - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, data, bip143, overwinter, additionals).then(function () { - var scriptBlocks = []; - var offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } else { - while (offset !== input.script.length) { - var blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK ? MAX_SCRIPT_BLOCK : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } else { - scriptBlocks.push(Buffer.concat([input.script.slice(offset, offset + blockSize), input.sequence])); - } - offset += blockSize; - } - } - return (0, utils.eachSeries)(scriptBlocks, function (scriptBlock) { - return _this2.startUntrustedHashTransactionInputRaw(newTransaction, false, scriptBlock, bip143, overwinter, additionals); - }).then(function () { - i++; - }); - }); - }); - }); - } - }, { - key: "provideOutputFullChangePath", - value: function provideOutputFullChangePath(path) { - var paths = (0, utils.splitPath)(path); - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return this.transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - }, { - key: "hashOutputFull", - value: function hashOutputFull(outputScript) { - var _this3 = this; - - var additionals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - - var offset = 0; - var p1 = 0x80; - var isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return this.transport.send(0xe0, 0x4a, p1, 0x00, outputScript); - } - return (0, utils.asyncWhile)(function () { - return offset < outputScript.length; - }, function () { - var blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length ? outputScript.length - offset : MAX_SCRIPT_BLOCK; - var p1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - var data = outputScript.slice(offset, offset + blockSize); - - return _this3.transport.send(0xe0, 0x4a, p1, 0x00, data).then(function () { - offset += blockSize; - }); - }); - } - }, { - key: "signTransaction", - value: function signTransaction(path) { - var lockTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SIGHASH_ALL; - var expiryHeight = arguments[3]; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var isDecred = additionals.includes("decred"); - var paths = (0, utils.splitPath)(path); - var offset = 0; - var pathsBuffer = Buffer.alloc(paths.length * 4); - paths.forEach(function (element) { - pathsBuffer.writeUInt32BE(element, offset); - offset += 4; - }); - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred ? Buffer.concat([Buffer.from([paths.length]), pathsBuffer, lockTimeBuffer, expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), Buffer.from([sigHashType])]) : Buffer.concat([Buffer.from([paths.length]), pathsBuffer, Buffer.from([0x00]), lockTimeBuffer, Buffer.from([sigHashType])]); - if (expiryHeight && !isDecred) { - buffer = Buffer.concat([buffer, expiryHeight]); - } - return this.transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - - }, { - key: "signMessageNew", - value: function signMessageNew(path, messageHex) { - var _this4 = this; - - var paths = (0, utils.splitPath)(path); - var message = new Buffer(messageHex, "hex"); - var offset = 0; - var toSend = []; - - var _loop = function _loop() { - var maxChunkSize = offset === 0 ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 : MAX_SCRIPT_BLOCK; - var chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - var buffer = new Buffer(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - toSend.push(buffer); - offset += chunkSize; - }; - - while (offset !== message.length) { - _loop(); - } - return (0, utils.foreach)(toSend, function (data, i) { - return _this4.transport.send(0xe0, 0x4e, 0x00, i === 0 ? 0x01 : 0x80, data); - }).then(function () { - return _this4.transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00])).then(function (response) { - var v = response[0] - 0x30; - var r = response.slice(4, 4 + response[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - var offset = 4 + response[3] + 2; - var s = response.slice(offset, offset + response[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return { v: v, r: r, s: s }; - }); - }); - } - - /** - * To sign a transaction involving standard (P2PKH) inputs, call createPaymentTransactionNew with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @return the signed transaction ready to be broadcast - * @example - btc.createPaymentTransactionNew( - [ [tx1, 1] ], - ["0'/0/0"], - undefined, - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(res => ...); - */ - - }, { - key: "createPaymentTransactionNew", - value: function createPaymentTransactionNew(inputs, associatedKeysets, changePath, outputScriptHex) { - var lockTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SIGHASH_ALL; - var segwit = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; - var initialTimestamp = arguments[7]; - - var _this5 = this; - - var additionals = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; - var expiryHeight = arguments[9]; - - var isDecred = additionals.includes("decred"); - var isXST = additionals.includes("stealthcoin"); - var hasTimestamp = initialTimestamp !== undefined; - var startTime = Date.now(); - var sapling = additionals.includes("sapling"); - var bech32 = segwit && additionals.includes("bech32"); - var useBip143 = segwit || !!additionals && (additionals.includes("abc") || additionals.includes("gold") || additionals.includes("bip143")) || !!expiryHeight && !isDecred; - // Inputs are provided as arrays of [transaction, output_index, optional redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST ? defaultVersion.writeUInt32LE(2, 0) : defaultVersion.writeUInt32LE(1, 0); // Default version to 2 for XST not to have timestamp - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var publicKeys = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer.alloc(0) - }; - var getTrustedInputCall = useBip143 ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0], additionals).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer.from(trustedInput, "hex"), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }).then(function () { - if (!!expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); - } else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - }); - }).then(function () { - for (var i = 0; i < inputs.length; i++) { - var _sequence = Buffer.alloc(4); - _sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence - }); - } - }).then(function () { - return (0, utils.doIf)(!resuming, function () { - return ( - // Collect public keys - (0, utils.foreach)(inputs, function (input, i) { - return _this5.getWalletPublicKey_private(associatedKeysets[i]); - }).then(function (result) { - for (var index = 0; index < result.length; index++) { - publicKeys.push(_this5.compressPublicKey(Buffer.from(result[index].publicKey, "hex"))); - } - }) - ); - }); - }).then(function () { - if (hasTimestamp) { - targetTransaction.timestamp = Buffer.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - }).then(function () { - return (0, utils.doIf)(useBip143, function () { - return ( - // Do the first run with all inputs - _this5.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals).then(function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript); - }); - }) - ); - }); - }).then(function () { - return (0, utils.doIf)(!!expiryHeight && !isDecred, function () { - return ( - // FIXME: I think we should always pass lockTime here. - _this5.signTransaction("", lockTime, SIGHASH_ALL, expiryHeight) - ); - }); - }).then(function () { - return ( - // Do the second run with the individual transaction - (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : !segwit ? regularOutputs[i].script : Buffer.concat([Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), _this5.hashPublicKey(publicKeys[i]), Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])]); - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this5.startUntrustedHashTransactionInput(!useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals).then(function () { - return (0, utils.doIf)(!useBip143, function () { - return (0, utils.doIf)(!resuming && typeof changePath != "undefined", function () { - // $FlowFixMe - return _this5.provideOutputFullChangePath(changePath); - }).then(function () { - return _this5.hashOutputFull(outputScript, additionals); - }); - }); - }).then(function () { - return _this5.signTransaction(associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals); - }).then(function (signature) { - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }) - ); - }).then(function () { - // Populate the final input scripts - for (var _i = 0; _i < inputs.length; _i++) { - if (segwit) { - targetTransaction.witness = Buffer.alloc(0); - if (!bech32) { - targetTransaction.inputs[_i].script = Buffer.concat([Buffer.from("160014", "hex"), _this5.hashPublicKey(publicKeys[_i])]); - } - } else { - var signatureSize = Buffer.alloc(1); - var keySize = Buffer.alloc(1); - signatureSize[0] = signatures[_i].length; - keySize[0] = publicKeys[_i].length; - targetTransaction.inputs[_i].script = Buffer.concat([signatureSize, signatures[_i], keySize, publicKeys[_i]]); - } - var offset = useBip143 ? 0 : 4; - targetTransaction.inputs[_i].prevout = trustedInputs[_i].value.slice(offset, offset + 0x24); - } - - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - - var result = Buffer.concat([_this5.serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript]); - - if (segwit && !isDecred) { - var witness = Buffer.alloc(0); - for (var i = 0; i < inputs.length; i++) { - var tmpScriptData = Buffer.concat([Buffer.from("02", "hex"), Buffer.from([signatures[i].length]), signatures[i], Buffer.from([publicKeys[i].length]), publicKeys[i]]); - witness = Buffer.concat([witness, tmpScriptData]); - } - result = Buffer.concat([result, witness]); - } - - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer.concat([result, lockTimeBuffer]); - - if (expiryHeight) { - result = Buffer.concat([result, targetTransaction.nExpiryHeight || Buffer.alloc(0), targetTransaction.extraData || Buffer.alloc(0)]); - } - - if (isDecred) { - var decredWitness = Buffer.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness = Buffer.concat([decredWitness, Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Buffer.from([0x00, 0x00, 0x00, 0x00]), //Block height - Buffer.from([0xff, 0xff, 0xff, 0xff]), //Block index - Buffer.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script]); - }); - - result = Buffer.concat([result, decredWitness]); - } - - return result.toString("hex"); - }); - } - - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction( - [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - ["0'/0/0"], - "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - ).then(result => ...); - */ - - }, { - key: "signP2SHTransaction", - value: function signP2SHTransaction(inputs, associatedKeysets, outputScriptHex) { - var lockTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_LOCKTIME; - var sigHashType = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SIGHASH_ALL; - var segwit = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; - - var _this6 = this; - - var transactionVersion = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : DEFAULT_VERSION; - var timeStamp = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; - - // Inputs are provided as arrays of [transaction, output_index, redeem script, optional sequence] - // associatedKeysets are provided as arrays of [path] - var nullScript = Buffer.alloc(0); - var nullPrevout = Buffer.alloc(0); - var defaultVersion = Buffer.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - var defaultTime = Buffer.alloc(4); - defaultTime.writeUInt32LE(timeStamp, 0); - var trustedInputs = []; - var regularOutputs = []; - var signatures = []; - var firstRun = true; - var resuming = false; - var targetTransaction = { - inputs: [], - version: defaultVersion - }; - - if (timeStamp > 0) { - targetTransaction.timestamp = defaultTime; - } - var getTrustedInputCall = segwit ? this.getTrustedInputBIP143.bind(this) : this.getTrustedInput.bind(this); - var outputScript = Buffer.from(outputScriptHex, "hex"); - - return (0, utils.foreach)(inputs, function (input) { - return (0, utils.doIf)(!resuming, function () { - return getTrustedInputCall(input[1], input[0]).then(function (trustedInput) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit ? Buffer.from(trustedInput, "hex") : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - }); - }).then(function () { - var outputs = input[0].outputs; - - var index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - }); - }).then(function () { - // Pre-build the target transaction - for (var i = 0; i < inputs.length; i++) { - var _sequence2 = Buffer.alloc(4); - _sequence2.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: _sequence2 - }); - } - }).then(function () { - return (0, utils.doIf)(segwit, function () { - return ( - // Do the first run with all inputs - _this6.startUntrustedHashTransactionInput(true, targetTransaction, trustedInputs, true).then(function () { - return _this6.hashOutputFull(outputScript); - }) - ); - }); - }).then(function () { - return (0, utils.foreach)(inputs, function (input, i) { - var script = inputs[i].length >= 3 && typeof inputs[i][2] === "string" ? Buffer.from(inputs[i][2], "hex") : regularOutputs[i].script; - var pseudoTX = Object.assign({}, targetTransaction); - var pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [_extends({}, pseudoTX.inputs[i], { script: script })]; - } else { - pseudoTX.inputs[i].script = script; - } - return _this6.startUntrustedHashTransactionInput(!segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit).then(function () { - return (0, utils.doIf)(!segwit, function () { - return _this6.hashOutputFull(outputScript); - }); - }).then(function () { - return _this6.signTransaction(associatedKeysets[i], lockTime, sigHashType).then(function (signature) { - signatures.push(signature.toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - }); - }); - }); - }).then(function () { - return signatures; - }); - } - }, { - key: "compressPublicKey", - value: function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer.alloc(1); - prefixBuffer[0] = prefix; - return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - }, { - key: "createVarint", - value: function createVarint(value) { - if (value < 0xfd) { - var _buffer = Buffer.alloc(1); - _buffer[0] = value; - return _buffer; - } - if (value <= 0xffff) { - var _buffer2 = Buffer.alloc(3); - _buffer2[0] = 0xfd; - _buffer2[1] = value & 0xff; - _buffer2[2] = value >> 8 & 0xff; - return _buffer2; - } - var buffer = Buffer.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = value >> 8 & 0xff; - buffer[3] = value >> 16 & 0xff; - buffer[4] = value >> 24 & 0xff; - return buffer; - } - - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - - }, { - key: "splitTransaction", - value: function splitTransaction(transactionHex) { - var isSegwitSupported = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var hasTimestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var hasExtraData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var additionals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; - - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer.alloc(0); - var nExpiryHeight = Buffer.alloc(0); - var nVersionGroupId = Buffer.alloc(0); - var extraData = Buffer.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && isSegwitSupported && transaction[offset] === 0 && transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = this.getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var _prevout = transaction.slice(offset, offset + 36); - offset += 36; - var _script = Buffer.alloc(0); - var _tree = Buffer.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - _script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } else { - //Tree field - _tree = transaction.slice(offset, offset + 1); - offset += 1; - } - - var _sequence3 = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ prevout: _prevout, script: _script, sequence: _sequence3, tree: _tree }); - } - varint = this.getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var _i2 = 0; _i2 < numberOutputs; _i2++) { - var _amount = transaction.slice(offset, offset + 8); - offset += 8; - - if (isDecred) { - //Script version - offset += 2; - } - - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script2 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ amount: _amount, script: _script2 }); - } - var witnessScript = void 0, - locktime = void 0; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - - //Get witnesses for Decred - if (isDecred) { - varint = this.getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var _i3 = 0; _i3 < numberInputs; _i3++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = this.getVarint(transaction, offset); - offset += varint[1]; - var _script3 = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[_i3].script = _script3; - } - } - - return { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - - }, { - key: "serializeTransactionOutputs", - value: function serializeTransactionOutputs(_ref2) { - var _this7 = this; - - var outputs = _ref2.outputs; - - var outputBuffer = Buffer.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, this.createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer.concat([outputBuffer, output.amount, _this7.createVarint(output.script.length), output.script]); - }); - } - return outputBuffer; - } - - /** - */ - - }, { - key: "serializeTransaction", - value: function serializeTransaction(transaction, skipWitness, timestamp) { - var _this8 = this; - - var additionals = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; - - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = isDecred || isBech32 ? Buffer.concat([inputBuffer, input.prevout, Buffer.from([0x00]), //tree - input.sequence]) : Buffer.concat([inputBuffer, input.prevout, _this8.createVarint(input.script.length), input.script, input.sequence]); - }); - - var outputBuffer = this.serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, useWitness && transaction.witness || Buffer.alloc(0), transaction.locktime, transaction.nExpiryHeight || Buffer.alloc(0), transaction.extraData || Buffer.alloc(0)]); - } - - return Buffer.concat([transaction.version, timestamp ? timestamp : Buffer.alloc(0), transaction.nVersionGroupId || Buffer.alloc(0), useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), this.createVarint(transaction.inputs.length), inputBuffer, outputBuffer]); - } - - /** - */ - - }, { - key: "displayTransactionDebug", - value: function displayTransactionDebug(transaction) { - console.log("version " + transaction.version.toString("hex")); - transaction.inputs.forEach(function (input, i) { - var prevout = input.prevout.toString("hex"); - var script = input.script.toString("hex"); - var sequence = input.sequence.toString("hex"); - console.log("input " + i + " prevout " + prevout + " script " + script + " sequence " + sequence); - }); - (transaction.outputs || []).forEach(function (output, i) { - var amount = output.amount.toString("hex"); - var script = output.script.toString("hex"); - console.log("output " + i + " amount " + amount + " script " + script); - }); - if (typeof transaction.locktime !== "undefined") { - console.log("locktime " + transaction.locktime.toString("hex")); - } - } - }]); - - return Btc; - }(); - - /** - */ - - - exports.default = Btc; - - /** - */ - - - /** - */ - - }); - - var Btc = unwrapExports(Btc_1); - - var Btc$1 = /*#__PURE__*/Object.freeze({ - default: Btc, - __moduleExports: Btc_1 - }); - - var domain; - - // This constructor is used to store event handlers. Instantiating this is - // faster than explicitly calling `Object.create(null)` to get a "clean" empty - // object (tested with v8 v4.9). - function EventHandlers() {} - EventHandlers.prototype = Object.create(null); - - function EventEmitter() { - EventEmitter.init.call(this); - } - - // nodejs oddity - // require('events') === require('events').EventEmitter - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.usingDomains = false; - - EventEmitter.prototype.domain = undefined; - EventEmitter.prototype._events = undefined; - 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. - EventEmitter.defaultMaxListeners = 10; - - EventEmitter.init = function() { - this.domain = null; - if (EventEmitter.usingDomains) { - // if there is an active domain, then attach to it. - if (domain.active && !(this instanceof domain.Domain)) { - this.domain = domain.active; - } - } - - if (!this._events || this._events === Object.getPrototypeOf(this)._events) { - this._events = new EventHandlers(); - 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 || isNaN(n)) - throw new TypeError('"n" argument must be a positive number'); - 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); - }; - - // These standalone emit* functions are used to optimize calling of event - // handlers for fast cases because emit() itself often has a variable number of - // arguments and can be deoptimized because of that. These functions always have - // the same number of arguments and thus do not get deoptimized, so the code - // inside them can execute faster. - function emitNone(handler, isFn, self) { - if (isFn) - handler.call(self); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self); - } - } - function emitOne(handler, isFn, self, arg1) { - if (isFn) - handler.call(self, arg1); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1); - } - } - function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) - handler.call(self, arg1, arg2); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2); - } - } - function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) - handler.call(self, arg1, arg2, arg3); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2, arg3); - } - } - - function emitMany(handler, isFn, self, args) { - if (isFn) - handler.apply(self, args); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].apply(self, args); - } - } - - EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events, domain; - var needDomainExit = false; - var doError = (type === 'error'); - - events = this._events; - if (events) - doError = (doError && events.error == null); - else if (!doError) - return false; - - domain = this.domain; - - // If there is no 'error' event listener then throw. - if (doError) { - er = arguments[1]; - if (domain) { - if (!er) - er = new Error('Uncaught, unspecified "error" event'); - er.domainEmitter = this; - er.domain = domain; - er.domainThrown = false; - domain.emit('error', er); - } else if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - return false; - } - - handler = events[type]; - - if (!handler) - return false; - - var isFn = typeof handler === 'function'; - len = arguments.length; - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - default: - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - emitMany(handler, isFn, this, args); - } - - if (needDomainExit) - domain.exit(); - - return true; - }; - - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = target._events; - if (!events) { - events = target._events = new EventHandlers(); - 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) { - 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) { - // 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]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } - - // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + type + ' listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - emitWarning(w); - } - } - } - - return target; - } - function emitWarning(e) { - typeof console.warn === 'function' ? console.warn(e) : console.log(e); - } - 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 _onceWrap(target, type, listener) { - var fired = false; - function g() { - target.removeListener(type, g); - if (!fired) { - fired = true; - listener.apply(target, arguments); - } - } - g.listener = listener; - return g; - } - - EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - - EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = this._events; - if (!events) - return this; - - list = events[type]; - if (!list) - return this; - - if (list === listener || (list.listener && list.listener === listener)) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - 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; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list[0] = undefined; - if (--this._eventsCount === 0) { - this._events = new EventHandlers(); - return this; - } else { - delete events[type]; - } - } else { - spliceOne(list, position); - } - - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events; - - events = this._events; - if (!events) - return this; - - // not listening for removeListener, no need to emit - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = new EventHandlers(); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) - this._events = new EventHandlers(); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - for (var i = 0, key; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = new EventHandlers(); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - do { - this.removeListener(type, listeners[listeners.length - 1]); - } while (listeners[0]); - } - - return this; - }; - - EventEmitter.prototype.listeners = function listeners(type) { - var evlistener; - var ret; - var events = this._events; - - if (!events) - ret = []; - else { - evlistener = events[type]; - if (!evlistener) - ret = []; - else if (typeof evlistener === 'function') - ret = [evlistener.listener || evlistener]; - else - ret = unwrapListeners(evlistener); - } - - return ret; - }; - - 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) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; - } - - EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; - }; - - // About 1.5x faster than the two-arg version of Array#splice(). - function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; - list.pop(); - } - - function arrayClone(arr, i) { - var copy = new Array(i); - while (i--) - copy[i] = arr[i]; - return copy; - } - - 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; - } - - var helpers = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - var addCustomErrorDeserializer = exports.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = exports.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = exports.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = exports.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - }); - - unwrapExports(helpers); - var helpers_1 = helpers.addCustomErrorDeserializer; - var helpers_2 = helpers.createCustomErrorClass; - var helpers_3 = helpers.deserializeError; - var helpers_4 = helpers.serializeError; - - var lib = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.StatusCodes = exports.DBNotReset = exports.DBWrongPassword = exports.NoDBPathGiven = exports.FirmwareOrAppUpdateRequired = exports.LedgerAPI5xx = exports.LedgerAPI4xx = exports.GenuineCheckFailed = exports.PairingFailed = exports.SyncError = exports.FeeTooHigh = exports.FeeRequired = exports.FeeNotLoaded = exports.CantScanQRCode = exports.ETHAddressNonEIP = exports.WrongAppForCurrency = exports.WrongDeviceForAccount = exports.WebsocketConnectionFailed = exports.WebsocketConnectionError = exports.DeviceShouldStayInApp = exports.TransportWebUSBGestureRequired = exports.TransportInterfaceNotAvailable = exports.TransportOpenUserCancelled = exports.UserRefusedOnDevice = exports.UserRefusedAllowManager = exports.UserRefusedFirmwareUpdate = exports.UserRefusedAddress = exports.UserRefusedDeviceNameChange = exports.UpdateYourApp = exports.UnavailableTezosOriginatedAccountSend = exports.UnavailableTezosOriginatedAccountReceive = exports.RecipientRequired = exports.MCUNotGenuineToDashboard = exports.UnexpectedBootloader = exports.TimeoutTagged = exports.RecommendUndelegation = exports.RecommendSubAccountsToEmpty = exports.PasswordIncorrectError = exports.PasswordsDontMatchError = exports.GasLessThanEstimate = exports.NotSupportedLegacyAddress = exports.NotEnoughGas = exports.NoAccessToCamera = exports.NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughSpendableBalance = exports.NotEnoughBalanceInParentAccount = exports.NotEnoughBalanceToDelegate = exports.NotEnoughBalance = exports.NoAddressesFound = exports.NetworkDown = exports.ManagerUninstallBTCDep = exports.ManagerNotEnoughSpaceError = exports.ManagerFirmwareNotEnoughSpaceError = exports.ManagerDeviceLockedError = exports.ManagerAppDepUninstallRequired = exports.ManagerAppDepInstallRequired = exports.ManagerAppRelyOnBTCError = exports.ManagerAppAlreadyInstalledError = exports.LedgerAPINotAvailable = exports.LedgerAPIErrorWithMessage = exports.LedgerAPIError = exports.UnknownMCU = exports.LatestMCUInstalledError = exports.InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddress = exports.InvalidXRPTag = exports.HardResetFail = exports.FeeEstimationFailed = exports.EthAppPleaseEnableContractData = exports.EnpointConfigError = exports.DisconnectedDeviceDuringOperation = exports.DisconnectedDevice = exports.DeviceSocketNoBulkStatus = exports.DeviceSocketFail = exports.DeviceNameInvalid = exports.DeviceHalted = exports.DeviceInOSUExpected = exports.DeviceOnDashboardUnexpected = exports.DeviceOnDashboardExpected = exports.DeviceNotGenuineError = exports.DeviceGenuineSocketEarlyClose = exports.DeviceAppVerifyNotSupported = exports.CurrencyNotSupported = exports.CashAddrNotSupported = exports.CantOpenDevice = exports.BtcUnmatchedApp = exports.BluetoothRequired = exports.AmountRequired = exports.AccountNotSupported = exports.AccountNameRequiredError = exports.addCustomErrorDeserializer = exports.createCustomErrorClass = exports.deserializeError = exports.serializeError = undefined; - exports.TransportError = TransportError; - exports.getAltStatusMessage = getAltStatusMessage; - exports.TransportStatusError = TransportStatusError; - - - - exports.serializeError = helpers.serializeError; - exports.deserializeError = helpers.deserializeError; - exports.createCustomErrorClass = helpers.createCustomErrorClass; - exports.addCustomErrorDeserializer = helpers.addCustomErrorDeserializer; - var AccountNameRequiredError = exports.AccountNameRequiredError = (0, helpers.createCustomErrorClass)("AccountNameRequired"); - var AccountNotSupported = exports.AccountNotSupported = (0, helpers.createCustomErrorClass)("AccountNotSupported"); - var AmountRequired = exports.AmountRequired = (0, helpers.createCustomErrorClass)("AmountRequired"); - var BluetoothRequired = exports.BluetoothRequired = (0, helpers.createCustomErrorClass)("BluetoothRequired"); - var BtcUnmatchedApp = exports.BtcUnmatchedApp = (0, helpers.createCustomErrorClass)("BtcUnmatchedApp"); - var CantOpenDevice = exports.CantOpenDevice = (0, helpers.createCustomErrorClass)("CantOpenDevice"); - var CashAddrNotSupported = exports.CashAddrNotSupported = (0, helpers.createCustomErrorClass)("CashAddrNotSupported"); - var CurrencyNotSupported = exports.CurrencyNotSupported = (0, helpers.createCustomErrorClass)("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = exports.DeviceAppVerifyNotSupported = (0, helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = exports.DeviceGenuineSocketEarlyClose = (0, helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = exports.DeviceNotGenuineError = (0, helpers.createCustomErrorClass)("DeviceNotGenuine"); - var DeviceOnDashboardExpected = exports.DeviceOnDashboardExpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = exports.DeviceOnDashboardUnexpected = (0, helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = exports.DeviceInOSUExpected = (0, helpers.createCustomErrorClass)("DeviceInOSUExpected"); - var DeviceHalted = exports.DeviceHalted = (0, helpers.createCustomErrorClass)("DeviceHalted"); - var DeviceNameInvalid = exports.DeviceNameInvalid = (0, helpers.createCustomErrorClass)("DeviceNameInvalid"); - var DeviceSocketFail = exports.DeviceSocketFail = (0, helpers.createCustomErrorClass)("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = exports.DeviceSocketNoBulkStatus = (0, helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = exports.DisconnectedDevice = (0, helpers.createCustomErrorClass)("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = exports.DisconnectedDeviceDuringOperation = (0, helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = exports.EnpointConfigError = (0, helpers.createCustomErrorClass)("EnpointConfig"); - var EthAppPleaseEnableContractData = exports.EthAppPleaseEnableContractData = (0, helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = exports.FeeEstimationFailed = (0, helpers.createCustomErrorClass)("FeeEstimationFailed"); - var HardResetFail = exports.HardResetFail = (0, helpers.createCustomErrorClass)("HardResetFail"); - var InvalidXRPTag = exports.InvalidXRPTag = (0, helpers.createCustomErrorClass)("InvalidXRPTag"); - var InvalidAddress = exports.InvalidAddress = (0, helpers.createCustomErrorClass)("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = exports.InvalidAddressBecauseDestinationIsAlsoSource = (0, helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = exports.LatestMCUInstalledError = (0, helpers.createCustomErrorClass)("LatestMCUInstalledError"); - var UnknownMCU = exports.UnknownMCU = (0, helpers.createCustomErrorClass)("UnknownMCU"); - var LedgerAPIError = exports.LedgerAPIError = (0, helpers.createCustomErrorClass)("LedgerAPIError"); - var LedgerAPIErrorWithMessage = exports.LedgerAPIErrorWithMessage = (0, helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = exports.LedgerAPINotAvailable = (0, helpers.createCustomErrorClass)("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = exports.ManagerAppAlreadyInstalledError = (0, helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = exports.ManagerAppRelyOnBTCError = (0, helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = exports.ManagerAppDepInstallRequired = (0, helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = exports.ManagerAppDepUninstallRequired = (0, helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = exports.ManagerDeviceLockedError = (0, helpers.createCustomErrorClass)("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = exports.ManagerFirmwareNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = exports.ManagerNotEnoughSpaceError = (0, helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = exports.ManagerUninstallBTCDep = (0, helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); - var NetworkDown = exports.NetworkDown = (0, helpers.createCustomErrorClass)("NetworkDown"); - var NoAddressesFound = exports.NoAddressesFound = (0, helpers.createCustomErrorClass)("NoAddressesFound"); - var NotEnoughBalance = exports.NotEnoughBalance = (0, helpers.createCustomErrorClass)("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = exports.NotEnoughBalanceToDelegate = (0, helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = exports.NotEnoughBalanceInParentAccount = (0, helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = exports.NotEnoughSpendableBalance = (0, helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = exports.NotEnoughBalanceBecauseDestinationNotCreated = (0, helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = exports.NoAccessToCamera = (0, helpers.createCustomErrorClass)("NoAccessToCamera"); - var NotEnoughGas = exports.NotEnoughGas = (0, helpers.createCustomErrorClass)("NotEnoughGas"); - var NotSupportedLegacyAddress = exports.NotSupportedLegacyAddress = (0, helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); - var GasLessThanEstimate = exports.GasLessThanEstimate = (0, helpers.createCustomErrorClass)("GasLessThanEstimate"); - var PasswordsDontMatchError = exports.PasswordsDontMatchError = (0, helpers.createCustomErrorClass)("PasswordsDontMatch"); - var PasswordIncorrectError = exports.PasswordIncorrectError = (0, helpers.createCustomErrorClass)("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = exports.RecommendSubAccountsToEmpty = (0, helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = exports.RecommendUndelegation = (0, helpers.createCustomErrorClass)("RecommendUndelegation"); - var TimeoutTagged = exports.TimeoutTagged = (0, helpers.createCustomErrorClass)("TimeoutTagged"); - var UnexpectedBootloader = exports.UnexpectedBootloader = (0, helpers.createCustomErrorClass)("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = exports.MCUNotGenuineToDashboard = (0, helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); - var RecipientRequired = exports.RecipientRequired = (0, helpers.createCustomErrorClass)("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = exports.UnavailableTezosOriginatedAccountReceive = (0, helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = exports.UnavailableTezosOriginatedAccountSend = (0, helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); - var UpdateYourApp = exports.UpdateYourApp = (0, helpers.createCustomErrorClass)("UpdateYourApp"); - var UserRefusedDeviceNameChange = exports.UserRefusedDeviceNameChange = (0, helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); - var UserRefusedAddress = exports.UserRefusedAddress = (0, helpers.createCustomErrorClass)("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = exports.UserRefusedFirmwareUpdate = (0, helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = exports.UserRefusedAllowManager = (0, helpers.createCustomErrorClass)("UserRefusedAllowManager"); - var UserRefusedOnDevice = exports.UserRefusedOnDevice = (0, helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = exports.TransportOpenUserCancelled = (0, helpers.createCustomErrorClass)("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = exports.TransportInterfaceNotAvailable = (0, helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); - var TransportWebUSBGestureRequired = exports.TransportWebUSBGestureRequired = (0, helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = exports.DeviceShouldStayInApp = (0, helpers.createCustomErrorClass)("DeviceShouldStayInApp"); - var WebsocketConnectionError = exports.WebsocketConnectionError = (0, helpers.createCustomErrorClass)("WebsocketConnectionError"); - var WebsocketConnectionFailed = exports.WebsocketConnectionFailed = (0, helpers.createCustomErrorClass)("WebsocketConnectionFailed"); - var WrongDeviceForAccount = exports.WrongDeviceForAccount = (0, helpers.createCustomErrorClass)("WrongDeviceForAccount"); - var WrongAppForCurrency = exports.WrongAppForCurrency = (0, helpers.createCustomErrorClass)("WrongAppForCurrency"); - var ETHAddressNonEIP = exports.ETHAddressNonEIP = (0, helpers.createCustomErrorClass)("ETHAddressNonEIP"); - var CantScanQRCode = exports.CantScanQRCode = (0, helpers.createCustomErrorClass)("CantScanQRCode"); - var FeeNotLoaded = exports.FeeNotLoaded = (0, helpers.createCustomErrorClass)("FeeNotLoaded"); - var FeeRequired = exports.FeeRequired = (0, helpers.createCustomErrorClass)("FeeRequired"); - var FeeTooHigh = exports.FeeTooHigh = (0, helpers.createCustomErrorClass)("FeeTooHigh"); - var SyncError = exports.SyncError = (0, helpers.createCustomErrorClass)("SyncError"); - var PairingFailed = exports.PairingFailed = (0, helpers.createCustomErrorClass)("PairingFailed"); - var GenuineCheckFailed = exports.GenuineCheckFailed = (0, helpers.createCustomErrorClass)("GenuineCheckFailed"); - var LedgerAPI4xx = exports.LedgerAPI4xx = (0, helpers.createCustomErrorClass)("LedgerAPI4xx"); - var LedgerAPI5xx = exports.LedgerAPI5xx = (0, helpers.createCustomErrorClass)("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = exports.FirmwareOrAppUpdateRequired = (0, helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - var NoDBPathGiven = exports.NoDBPathGiven = (0, helpers.createCustomErrorClass)("NoDBPathGiven"); - var DBWrongPassword = exports.DBWrongPassword = (0, helpers.createCustomErrorClass)("DBWrongPassword"); - var DBNotReset = exports.DBNotReset = (0, helpers.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = exports.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - }); - - unwrapExports(lib); - var lib_1 = lib.StatusCodes; - var lib_2 = lib.DBNotReset; - var lib_3 = lib.DBWrongPassword; - var lib_4 = lib.NoDBPathGiven; - var lib_5 = lib.FirmwareOrAppUpdateRequired; - var lib_6 = lib.LedgerAPI5xx; - var lib_7 = lib.LedgerAPI4xx; - var lib_8 = lib.GenuineCheckFailed; - var lib_9 = lib.PairingFailed; - var lib_10 = lib.SyncError; - var lib_11 = lib.FeeTooHigh; - var lib_12 = lib.FeeRequired; - var lib_13 = lib.FeeNotLoaded; - var lib_14 = lib.CantScanQRCode; - var lib_15 = lib.ETHAddressNonEIP; - var lib_16 = lib.WrongAppForCurrency; - var lib_17 = lib.WrongDeviceForAccount; - var lib_18 = lib.WebsocketConnectionFailed; - var lib_19 = lib.WebsocketConnectionError; - var lib_20 = lib.DeviceShouldStayInApp; - var lib_21 = lib.TransportWebUSBGestureRequired; - var lib_22 = lib.TransportInterfaceNotAvailable; - var lib_23 = lib.TransportOpenUserCancelled; - var lib_24 = lib.UserRefusedOnDevice; - var lib_25 = lib.UserRefusedAllowManager; - var lib_26 = lib.UserRefusedFirmwareUpdate; - var lib_27 = lib.UserRefusedAddress; - var lib_28 = lib.UserRefusedDeviceNameChange; - var lib_29 = lib.UpdateYourApp; - var lib_30 = lib.UnavailableTezosOriginatedAccountSend; - var lib_31 = lib.UnavailableTezosOriginatedAccountReceive; - var lib_32 = lib.RecipientRequired; - var lib_33 = lib.MCUNotGenuineToDashboard; - var lib_34 = lib.UnexpectedBootloader; - var lib_35 = lib.TimeoutTagged; - var lib_36 = lib.RecommendUndelegation; - var lib_37 = lib.RecommendSubAccountsToEmpty; - var lib_38 = lib.PasswordIncorrectError; - var lib_39 = lib.PasswordsDontMatchError; - var lib_40 = lib.GasLessThanEstimate; - var lib_41 = lib.NotSupportedLegacyAddress; - var lib_42 = lib.NotEnoughGas; - var lib_43 = lib.NoAccessToCamera; - var lib_44 = lib.NotEnoughBalanceBecauseDestinationNotCreated; - var lib_45 = lib.NotEnoughSpendableBalance; - var lib_46 = lib.NotEnoughBalanceInParentAccount; - var lib_47 = lib.NotEnoughBalanceToDelegate; - var lib_48 = lib.NotEnoughBalance; - var lib_49 = lib.NoAddressesFound; - var lib_50 = lib.NetworkDown; - var lib_51 = lib.ManagerUninstallBTCDep; - var lib_52 = lib.ManagerNotEnoughSpaceError; - var lib_53 = lib.ManagerFirmwareNotEnoughSpaceError; - var lib_54 = lib.ManagerDeviceLockedError; - var lib_55 = lib.ManagerAppDepUninstallRequired; - var lib_56 = lib.ManagerAppDepInstallRequired; - var lib_57 = lib.ManagerAppRelyOnBTCError; - var lib_58 = lib.ManagerAppAlreadyInstalledError; - var lib_59 = lib.LedgerAPINotAvailable; - var lib_60 = lib.LedgerAPIErrorWithMessage; - var lib_61 = lib.LedgerAPIError; - var lib_62 = lib.UnknownMCU; - var lib_63 = lib.LatestMCUInstalledError; - var lib_64 = lib.InvalidAddressBecauseDestinationIsAlsoSource; - var lib_65 = lib.InvalidAddress; - var lib_66 = lib.InvalidXRPTag; - var lib_67 = lib.HardResetFail; - var lib_68 = lib.FeeEstimationFailed; - var lib_69 = lib.EthAppPleaseEnableContractData; - var lib_70 = lib.EnpointConfigError; - var lib_71 = lib.DisconnectedDeviceDuringOperation; - var lib_72 = lib.DisconnectedDevice; - var lib_73 = lib.DeviceSocketNoBulkStatus; - var lib_74 = lib.DeviceSocketFail; - var lib_75 = lib.DeviceNameInvalid; - var lib_76 = lib.DeviceHalted; - var lib_77 = lib.DeviceInOSUExpected; - var lib_78 = lib.DeviceOnDashboardUnexpected; - var lib_79 = lib.DeviceOnDashboardExpected; - var lib_80 = lib.DeviceNotGenuineError; - var lib_81 = lib.DeviceGenuineSocketEarlyClose; - var lib_82 = lib.DeviceAppVerifyNotSupported; - var lib_83 = lib.CurrencyNotSupported; - var lib_84 = lib.CashAddrNotSupported; - var lib_85 = lib.CantOpenDevice; - var lib_86 = lib.BtcUnmatchedApp; - var lib_87 = lib.BluetoothRequired; - var lib_88 = lib.AmountRequired; - var lib_89 = lib.AccountNotSupported; - var lib_90 = lib.AccountNameRequiredError; - var lib_91 = lib.addCustomErrorDeserializer; - var lib_92 = lib.createCustomErrorClass; - var lib_93 = lib.deserializeError; - var lib_94 = lib.serializeError; - var lib_95 = lib.TransportError; - var lib_96 = lib.getAltStatusMessage; - var lib_97 = lib.TransportStatusError; - - var Transport_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.getAltStatusMessage = exports.StatusCodes = exports.TransportStatusError = exports.TransportError = undefined; - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _events3 = _interopRequireDefault(EventEmitter); - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - exports.TransportError = lib.TransportError; - exports.TransportStatusError = lib.TransportStatusError; - exports.StatusCodes = lib.StatusCodes; - exports.getAltStatusMessage = lib.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [lib.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new lib.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new lib.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new lib.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new lib.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new lib.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new lib.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - exports.default = Transport; - - }); - - unwrapExports(Transport_1); - var Transport_2 = Transport_1.getAltStatusMessage; - var Transport_3 = Transport_1.StatusCodes; - var Transport_4 = Transport_1.TransportStatusError; - var Transport_5 = Transport_1.TransportError; - - var hidFraming = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - - var Tag = 0x05; - - function asUInt16BE(value) { - var b = Buffer.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - - var initialAcc = { - data: Buffer.alloc(0), - dataLength: 0, - sequence: 0 - }; - - /** - * - */ - var createHIDframing = function createHIDframing(channel, packetSize) { - return { - makeBlocks: function makeBlocks(apdu) { - var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer.concat([data, // fill data with padding - Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); - - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function reduceResponse(acc, chunk) { - var _ref = acc || initialAcc, - data = _ref.data, - dataLength = _ref.dataLength, - sequence = _ref.sequence; - - if (chunk.readUInt16BE(0) !== channel) { - throw new lib.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new lib.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new lib.TransportError("Invalid sequence", "InvalidSequence"); - } - - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - - exports.default = createHIDframing; - - }); - - unwrapExports(hidFraming); - - var lib$1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - /** - * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) - * - ** Model - * Ledger Nano S : 0x10 - * Ledger Blue : 0x00 - * Ledger Nano X : 0x40 - * - ** Interface support bitfield - * Generic HID : 0x01 - * Keyboard HID : 0x02 - * U2F : 0x04 - * CCID : 0x08 - * WebUSB : 0x10 - */ - - var IIGenericHID = exports.IIGenericHID = 0x01; - var IIKeyboardHID = exports.IIKeyboardHID = 0x02; - var IIU2F = exports.IIU2F = 0x04; - var IICCID = exports.IICCID = 0x08; - var IIWebUSB = exports.IIWebUSB = 0x10; - - var devices = { - blue: { - id: "blue", - productName: "Ledger Blue", - productIdMM: 0x00, - legacyUsbProductId: 0x0000, - usbOnly: true, - memorySize: 480 * 1024, - blockSize: 4 * 1024 - }, - nanoS: { - id: "nanoS", - productName: "Ledger Nano S", - productIdMM: 0x10, - legacyUsbProductId: 0x0001, - usbOnly: true, - memorySize: 320 * 1024, - blockSize: 4 * 1024 - }, - nanoX: { - id: "nanoX", - productName: "Ledger Nano X", - productIdMM: 0x40, - legacyUsbProductId: 0x0004, - usbOnly: false, - memorySize: 2 * 1024 * 1024, - blockSize: 4 * 1024, - bluetoothSpec: [{ - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" - }, { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572" - }] - } - }; - - var productMap = { - Blue: "blue", - "Nano S": "nanoS", - "Nano X": "nanoX" - }; - - // $FlowFixMe - var devicesList = Object.values(devices); - - /** - * - */ - var ledgerUSBVendorId = exports.ledgerUSBVendorId = 0x2c97; - - /** - * - */ - var getDeviceModel = exports.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; - - /** - * - */ - var identifyUSBProductId = exports.identifyUSBProductId = function identifyUSBProductId(usbProductId) { - var legacy = devicesList.find(function (d) { - return d.legacyUsbProductId === usbProductId; - }); - if (legacy) return legacy; - - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { - return d.productIdMM === mm; - }); - return deviceModel; - }; - - var identifyProductName = exports.identifyProductName = function identifyProductName(productName) { - var productId = productMap[productName]; - var deviceModel = devicesList.find(function (d) { - return d.id === productId; - }); - - return deviceModel; - }; - - var bluetoothServices = []; - var serviceUuidToInfos = {}; - - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; - - if (_bluetoothSpec) { - for (var i = 0; i < _bluetoothSpec.length; i++) { - var spec = _bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); - } - } - } - - /** - * - */ - var getBluetoothServiceUuids = exports.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - var getInfosForServiceUuid = exports.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; - - /** - * - */ - - - /** - * - */ - - - /** - * - */ - - }); - - unwrapExports(lib$1); - var lib_1$1 = lib$1.IIGenericHID; - var lib_2$1 = lib$1.IIKeyboardHID; - var lib_3$1 = lib$1.IIU2F; - var lib_4$1 = lib$1.IICCID; - var lib_5$1 = lib$1.IIWebUSB; - var lib_6$1 = lib$1.ledgerUSBVendorId; - var lib_7$1 = lib$1.getDeviceModel; - var lib_8$1 = lib$1.identifyUSBProductId; - var lib_9$1 = lib$1.identifyProductName; - var lib_10$1 = lib$1.getBluetoothServiceUuids; - var lib_11$1 = lib$1.getInfosForServiceUuid; - - var lib$2 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - - /** - * A Log object - */ - var id = 0; - var subscribers = []; - - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = exports.log = function log(type, message, data) { - var obj = { type: type, id: String(++id), date: new Date() }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = exports.listen = function listen(cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } - - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; - - }); - - unwrapExports(lib$2); - var lib_1$2 = lib$2.log; - var lib_2$2 = lib$2.listen; - - var webusb = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.isSupported = exports.getFirstLedgerDevice = exports.getLedgerDevices = exports.requestLedgerDevice = undefined; - - var requestLedgerDevice = exports.requestLedgerDevice = function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var device; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return navigator.usb.requestDevice({ filters: ledgerDevices }); - - case 2: - device = _context.sent; - return _context.abrupt("return", device); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function requestLedgerDevice() { - return _ref.apply(this, arguments); - }; - }(); - - var getLedgerDevices = exports.getLedgerDevices = function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var devices; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return navigator.usb.getDevices(); - - case 2: - devices = _context2.sent; - return _context2.abrupt("return", devices.filter(function (d) { - return d.vendorId === lib$1.ledgerUSBVendorId; - })); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function getLedgerDevices() { - return _ref2.apply(this, arguments); - }; - }(); - - var getFirstLedgerDevice = exports.getFirstLedgerDevice = function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var existingDevices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getLedgerDevices(); - - case 2: - existingDevices = _context3.sent; - - if (!(existingDevices.length > 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", existingDevices[0]); - - case 5: - return _context3.abrupt("return", requestLedgerDevice()); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); - - - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - var ledgerDevices = [{ vendorId: lib$1.ledgerUSBVendorId }]; - - var isSupported = exports.isSupported = function isSupported() { - return Promise.resolve( - // $FlowFixMe - !!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; - - }); - - unwrapExports(webusb); - var webusb_1 = webusb.isSupported; - var webusb_2 = webusb.getFirstLedgerDevice; - var webusb_3 = webusb.getLedgerDevices; - var webusb_4 = webusb.requestLedgerDevice; - - var TransportWebUSB_1 = createCommonjsModule(function (module, exports) { - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - - - var _hwTransport2 = _interopRequireDefault(Transport_1); - - - - var _hidFraming2 = _interopRequireDefault(hidFraming); - - - - - - - - - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var configurationValue = 1; - var interfaceNumber = 2; - var endpointNumber = 3; - - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ - - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); - - function TransportWebUSB(device) { - _classCallCheck(this, TransportWebUSB); - - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); - - _initialiseProps.call(_this); - - _this.device = device; - _this.deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - return _this; - } - - /** - * Check if WebUSB transport is supported. - */ - - - /** - * List the WebUSB devices that was previously authorized by the user. - */ - - - /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! - */ - - - _createClass(TransportWebUSB, [{ - key: "close", - - - /** - * Release the transport device - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.exchangeBusyPromise; - - case 2: - _context.next = 4; - return this.device.releaseInterface(interfaceNumber); - - case 4: - _context.next = 6; - return this.device.reset(); - - case 6: - _context.next = 8; - return this.device.close(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _ref.apply(this, arguments); - } - - return close; - }() - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey() {} - }], [{ - key: "request", - - - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var device; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return (0, webusb.requestLedgerDevice)(); - - case 2: - device = _context2.sent; - return _context2.abrupt("return", TransportWebUSB.open(device)); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function request() { - return _ref2.apply(this, arguments); - } - - return request; - }() - - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ - - }, { - key: "openConnected", - value: function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var devices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return (0, webusb.getLedgerDevices)(); - - case 2: - devices = _context3.sent; - - if (!(devices.length === 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", null); - - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function openConnected() { - return _ref3.apply(this, arguments); - } - - return openConnected; - }() - - /** - * Create a Ledger transport with a USBDevice - */ - - }, { - key: "open", - value: function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { - var transport, onDisconnect; - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return device.open(); - - case 2: - if (!(device.configuration === null)) { - _context4.next = 5; - break; - } - - _context4.next = 5; - return device.selectConfiguration(configurationValue); - - case 5: - _context4.next = 7; - return device.reset(); - - case 7: - _context4.prev = 7; - _context4.next = 10; - return device.claimInterface(interfaceNumber); - - case 10: - _context4.next = 17; - break; - - case 12: - _context4.prev = 12; - _context4.t0 = _context4["catch"](7); - _context4.next = 16; - return device.close(); - - case 16: - throw new lib.TransportInterfaceNotAvailable(_context4.t0.message); - - case 17: - transport = new TransportWebUSB(device); - - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new lib.DisconnectedDevice()); - } - }; - // $FlowFixMe - - - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); - - case 21: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[7, 12]]); - })); - - function open(_x) { - return _ref4.apply(this, arguments); - } - - return open; - }() - }]); - - return TransportWebUSB; - }(_hwTransport2.default); - - TransportWebUSB.isSupported = webusb.isSupported; - TransportWebUSB.list = webusb.getLedgerDevices; - - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - (0, webusb.getFirstLedgerDevice)().then(function (device) { - if (!unsubscribed) { - var deviceModel = (0, lib$1.identifyUSBProductId)(device.productId); - observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); - observer.complete(); - } - }, function (error) { - observer.error(new lib.TransportOpenUserCancelled(error.message)); - }); - function unsubscribe() { - unsubscribed = true; - } - return { unsubscribe: unsubscribe }; - }; - - var _initialiseProps = function _initialiseProps() { - var _this2 = this; - - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; - - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; - - this.exchange = function (apdu) { - return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - channel = _this2.channel, packetSize = _this2.packetSize; - - (0, lib$2.log)("apdu", "=> " + apdu.toString("hex")); - - framing = (0, _hidFraming2.default)(channel, packetSize); - - // Write... - - blocks = framing.makeBlocks(apdu); - i = 0; - - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } - - (0, lib$2.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); - - case 9: - i++; - _context5.next = 5; - break; - - case 12: - - // Read... - result = void 0; - acc = void 0; - - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } - - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); - - case 17: - r = _context5.sent; - buffer = Buffer.from(r.data.buffer); - - (0, lib$2.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; - - case 23: - - (0, lib$2.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); - - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5, _this2); - }))).catch(function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this2._emitDisconnect(e); - throw new lib.DisconnectedDeviceDuringOperation(e.message); - } - throw e; - }); - }; - }; - - exports.default = TransportWebUSB; - - }); - - var TransportWebUSB = unwrapExports(TransportWebUSB_1); - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ - default: TransportWebUSB, - __moduleExports: TransportWebUSB_1 - }); - - exports.Btc = Btc$1; - exports.TransportWebUSB = TransportWebUSB$1; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.NewLedger={})}(this,function(e){"use strict";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,r){return e(r={exports:{}},r.exports),r.exports}n(function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",i=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag";function u(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{u({},"")}catch(e){u=function(e,r,t){return e[r]=t}}function c(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),i=new A(n||[]);return a._invoke=function(e,r,t){var n=f;return function(o,a){if(n===p)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return N()}for(t.method=o,t.arg=a;;){var i=t.delegate;if(i){var s=D(i,t);if(s){if(s===v)continue;return s}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===f)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=p;var u=l(e,r,t);if("normal"===u.type){if(n=t.done?h:d,u.arg===v)continue;return{value:u.arg,done:t.done}}"throw"===u.type&&(n=h,t.method="throw",t.arg=u.arg)}}}(e,t,i),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var f="suspendedStart",d="suspendedYield",p="executing",h="completed",v={};function g(){}function m(){}function E(){}var y={};u(y,a,function(){return this});var C=Object.getPrototypeOf,w=C&&C(C(x([])));w&&w!==t&&n.call(w,a)&&(y=w);var I=E.prototype=g.prototype=Object.create(y);function b(e){["next","throw","return"].forEach(function(r){u(e,r,function(e){return this._invoke(r,e)})})}function B(e,r){var t;this._invoke=function(o,a){function i(){return new r(function(t,i){!function t(o,a,i,s){var u=l(e[o],e,a);if("throw"!==u.type){var c=u.arg,f=c.value;return f&&"object"==typeof f&&n.call(f,"__await")?r.resolve(f.__await).then(function(e){t("next",e,i,s)},function(e){t("throw",e,i,s)}):r.resolve(f).then(function(e){c.value=e,i(c)},function(e){return t("throw",e,i,s)})}s(u.arg)}(o,a,t,i)})}return t=t?t.then(i,i):i()}}function D(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,D(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function T(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function S(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function x(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function t(){for(;++o=0;--a){var i=this.tryEntries[a],s=i.completion;if("root"===i.tryLoc)return o("end");if(i.tryLoc<=this.prev){var u=n.call(i,"catchLoc"),c=n.call(i,"finallyLoc");if(u&&c){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),S(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;S(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:x(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}});var o=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.defer=function(){var e=void 0,r=void 0,t=new Promise(function(t,n){e=t,r=n});if(!e||!r)throw"defer() error";return{promise:t,resolve:e,reject:r}},r.splitPath=function(e){var r=[];return e.split("/").forEach(function(e){var t=parseInt(e,10);isNaN(t)||(e.length>1&&"'"===e[e.length-1]&&(t+=2147483648),r.push(t))}),r},r.eachSeries=function(e,r){return e.reduce(function(e,t){return e.then(function(){return r(t)})},Promise.resolve())},r.foreach=function(e,r){return Promise.resolve().then(function(){return function e(t,n,o){return t>=n.length?o:r(n[t],t).then(function(r){return o.push(r),e(t+1,n,o)})}(0,e,[])})},r.doIf=function(e,r){return Promise.resolve().then(function(){if(e)return r()})},r.asyncWhile=function(e,r){return Promise.resolve([]).then(function t(n){return e()?r().then(function(e){return n.push(e),t(n)}):n})};r.isLedgerDevice=function(e){return 9601===e.vendorId&&15228===e.productId||11415===e.vendorId}});t(o);o.defer,o.splitPath,o.eachSeries,o.foreach,o.doIf,o.asyncWhile,o.isLedgerDevice;var a={}.createHash,i=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t,n=Object.assign||function(e){for(var r=1;r1&&void 0!==arguments[1]?arguments[1]:"BTC";!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),this.transport=r,r.decorateAppAPIMethods(this,["getWalletPublicKey","signP2SHTransaction","signMessageNew","createPaymentTransactionNew"],t)}return i(e,[{key:"hashPublicKey",value:function(e){return(0,s.default)("rmd160").update((0,s.default)("sha256").update(e).digest()).digest()}},{key:"getWalletPublicKey_private",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=n({verify:!1,format:"legacy"},r),a=t.verify,i=t.format;if(!(i in u))throw new Error("btc.getWalletPublicKey invalid format="+i);var s=(0,o.splitPath)(e),c=a?1:0,l=u[i],f=Buffer.alloc(1+4*s.length);return f[0]=s.length,s.forEach(function(e,r){f.writeUInt32BE(e,1+4*r)}),this.transport.send(224,64,c,l,f).then(function(e){var r=e[0],t=e[1+r];return{publicKey:e.slice(1,1+r).toString("hex"),bitcoinAddress:e.slice(1+r+1,1+r+1+t).toString("ascii"),chainCode:e.slice(1+r+1+t,1+r+1+t+32).toString("hex")}})}},{key:"getWalletPublicKey",value:function(e,r){var t=void 0;return arguments.length>2||"boolean"==typeof r?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),t={verify:!!r,format:arguments[2]?"p2sh":"legacy"}):t=r||{},this.getWalletPublicKey_private(e,t)}},{key:"getTrustedInputRaw",value:function(e,r){var t=void 0,n=!1;if("number"==typeof r){n=!0;var o=Buffer.alloc(4);o.writeUInt32BE(r,0),t=Buffer.concat([o,e],e.length+4)}else t=e;return this.transport.send(224,66,n?0:128,0,t).then(function(e){return e.slice(0,e.length-2).toString("hex")})}},{key:"getTrustedInput",value:function(e,r){var t=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],a=r.inputs,i=r.outputs,s=r.locktime;if(!i||!s)throw new Error("getTrustedInput: locktime & outputs is expected");var u=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e){return t.getTrustedInputRaw(e)},f=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),this.createVarint(a.length)]);return this.getTrustedInputRaw(f,e).then(function(){return(0,o.eachSeries)(a,function(e){var r=u?e.tree||Buffer.from([0]):Buffer.alloc(0),n=Buffer.concat([e.prevout,r,c?Buffer.from([0]):t.createVarint(e.script.length)]);return t.getTrustedInputRaw(n).then(function(){return u?l(Buffer.concat([e.script,e.sequence])):c?l(e.sequence):function(e,r){for(var n=[],a=0;a!==e.length;){var i=e.length-a>50?50:e.length-a;a+i!==e.length?n.push(e.slice(a,a+i)):n.push(Buffer.concat([e.slice(a,a+i),r])),a+=i}return 0===e.length&&n.push(r),(0,o.eachSeries)(n,function(e){return t.getTrustedInputRaw(e)})}(e.script,e.sequence)})}).then(function(){var e=t.createVarint(i.length);return t.getTrustedInputRaw(e)})}).then(function(){return(0,o.eachSeries)(i,function(e){var r=e.amount;return r=Buffer.concat([r,u?Buffer.from([0,0]):Buffer.alloc(0),t.createVarint(e.script.length),e.script]),t.getTrustedInputRaw(r).then(function(){})}).then(function(){var e=u?Buffer.concat([s,Buffer.from([0,0,0,0])]):s;return t.getTrustedInputRaw(e)})})}},{key:"getTrustedInputBIP143",value:function(){var e,r=(e=regeneratorRuntime.mark(function e(r,t){var n,o,a,i,u,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}throw new Error("getTrustedInputBIP143: missing tx");case 2:if(!c.includes("decred")){e.next=5;break}throw new Error("Decred does not implement BIP143");case 5:if((n=(0,s.default)("sha256")).update(this.serializeTransaction(t,!0)),o=n.digest(),(n=(0,s.default)("sha256")).update(o),o=n.digest(),(a=Buffer.alloc(4)).writeUInt32LE(r,0),i=t.outputs,u=t.locktime,i&&u){e.next=16;break}throw new Error("getTrustedInputBIP143: locktime & outputs is expected");case 16:if(i[r]){e.next=18;break}throw new Error("getTrustedInputBIP143: wrong index");case 18:return o=Buffer.concat([o,a,i[r].amount]),e.next=21,o.toString("hex");case 21:return e.abrupt("return",e.sent);case 22:case"end":return e.stop()}},e,this)}),function(){var r=e.apply(this,arguments);return new Promise(function(e,t){return function n(o,a){try{var i=r[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then(function(e){n("next",e)},function(e){n("throw",e)});e(s)}("next")})});return function(e,t){return r.apply(this,arguments)}}()},{key:"getVarint",value:function(e,r){if(e[r]<253)return[e[r],1];if(253===e[r])return[(e[r+2]<<8)+e[r+1],3];if(254===e[r])return[(e[r+4]<<24)+(e[r+3]<<16)+(e[r+2]<<8)+e[r+1],5];throw new Error("getVarint called with unexpected parameters")}},{key:"startUntrustedHashTransactionInputRaw",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],i=n?a.includes("sapling")?5:o?4:2:0;return this.transport.send(224,68,r?0:128,e?i:128,t)}},{key:"startUntrustedHashTransactionInput",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=this,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],u=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),this.createVarint(r.inputs.length)]);return this.startUntrustedHashTransactionInputRaw(e,!0,u,n,i,s).then(function(){var c=0,l=s.includes("decred");return(0,o.eachSeries)(r.inputs,function(r){var f=void 0;return f=n?Buffer.from([2]):t[c].trustedInput?Buffer.from([1,t[c].value.length]):Buffer.from([0]),u=Buffer.concat([f,t[c].value,l?Buffer.from([0]):Buffer.alloc(0),a.createVarint(r.script.length)]),a.startUntrustedHashTransactionInputRaw(e,!1,u,n,i,s).then(function(){var t=[],u=0;if(0===r.script.length)t.push(r.sequence);else for(;u!==r.script.length;){var l=r.script.length-u>50?50:r.script.length-u;u+l!==r.script.length?t.push(r.script.slice(u,u+l)):t.push(Buffer.concat([r.script.slice(u,u+l),r.sequence])),u+=l}return(0,o.eachSeries)(t,function(r){return a.startUntrustedHashTransactionInputRaw(e,!1,r,n,i,s)}).then(function(){c++})})})})}},{key:"provideOutputFullChangePath",value:function(e){var r=(0,o.splitPath)(e),t=Buffer.alloc(1+4*r.length);return t[0]=r.length,r.forEach(function(e,r){t.writeUInt32BE(e,1+4*r)}),this.transport.send(224,74,255,0,t)}},{key:"hashOutputFull",value:function(e){var r=this,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=0;return t.includes("decred")?this.transport.send(224,74,128,0,e):(0,o.asyncWhile)(function(){return n=e.length?e.length-n:50,o=n+t===e.length?128:0,a=e.slice(n,n+t);return r.transport.send(224,74,o,0,a).then(function(){n+=t})})}},{key:"signTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments[3],a=(arguments.length>4&&void 0!==arguments[4]?arguments[4]:[]).includes("decred"),i=(0,o.splitPath)(e),s=0,u=Buffer.alloc(4*i.length);i.forEach(function(e){u.writeUInt32BE(e,s),s+=4});var c=Buffer.alloc(4);c.writeUInt32BE(r,0);var l=a?Buffer.concat([Buffer.from([i.length]),u,c,n||Buffer.from([0,0,0,0]),Buffer.from([t])]):Buffer.concat([Buffer.from([i.length]),u,Buffer.from([0]),c,Buffer.from([t])]);return n&&!a&&(l=Buffer.concat([l,n])),this.transport.send(224,72,0,0,l).then(function(e){return e.length>0?(e[0]=48,e.slice(0,e.length-2)):e})}},{key:"signMessageNew",value:function(e,r){for(var t=this,n=(0,o.splitPath)(e),a=new Buffer(r,"hex"),i=0,s=[],u=function(){var e=0===i?49-4*n.length-4:50,r=i+e>a.length?a.length-i:e,t=new Buffer(0===i?1+4*n.length+2+r:r);0===i?(t[0]=n.length,n.forEach(function(e,r){t.writeUInt32BE(e,1+4*r)}),t.writeUInt16BE(a.length,1+4*n.length),a.copy(t,1+4*n.length+2,i,i+r)):a.copy(t,0,i,i+r),s.push(t),i+=r};i!==a.length;)u();return(0,o.foreach)(s,function(e,r){return t.transport.send(224,78,0,0===r?1:128,e)}).then(function(){return t.transport.send(224,78,128,0,Buffer.from([0])).then(function(e){var r=e[0]-48,t=e.slice(4,4+e[3]);0===t[0]&&(t=t.slice(1)),t=t.toString("hex");var n=4+e[3]+2,o=e.slice(n,n+e[n-1]);return 0===o[0]&&(o=o.slice(1)),{v:r,r:t,s:o=o.toString("hex")}})})}},{key:"createPaymentTransactionNew",value:function(e,r,t,a){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1,u=arguments.length>6&&void 0!==arguments[6]&&arguments[6],c=arguments[7],l=this,f=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments[9],p=f.includes("decred"),h=f.includes("stealthcoin"),v=void 0!==c,g=Date.now(),m=f.includes("sapling"),E=u&&f.includes("bech32"),y=u||!!f&&(f.includes("abc")||f.includes("gold")||f.includes("bip143"))||!!d&&!p,C=Buffer.alloc(0),w=Buffer.alloc(0),I=Buffer.alloc(4);d&&!p?I.writeUInt32LE(m?2147483652:2147483651,0):h?I.writeUInt32LE(2,0):I.writeUInt32LE(1,0);var b=[],B=[],D=[],T=[],S=!0,A={inputs:[],version:I,timestamp:Buffer.alloc(0)},x=y?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),N=Buffer.from(a,"hex");return(0,o.foreach)(e,function(e){return(0,o.doIf)(!0,function(){return x(e[1],e[0],f).then(function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:4294967295,0),b.push({trustedInput:!0,value:Buffer.from(r,"hex"),sequence:t})})}).then(function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&B.push(r[t])}).then(function(){d&&!p?(A.nVersionGroupId=Buffer.from(m?[133,32,47,137]:[112,130,196,3]),A.nExpiryHeight=d,A.extraData=Buffer.from(m?[0,0,0,0,0,0,0,0,0,0,0]:[0])):p&&(A.nExpiryHeight=d)})}).then(function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:4294967295,0),A.inputs.push({script:C,prevout:w,sequence:t})}}).then(function(){return(0,o.doIf)(!0,function(){return(0,o.foreach)(e,function(e,t){return l.getWalletPublicKey_private(r[t])}).then(function(e){for(var r=0;r=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):u?Buffer.concat([Buffer.from([118,169,20]),l.hashPublicKey(T[c]),Buffer.from([136,172])]):B[c].script,v=Object.assign({},A),g=y?[b[c]]:b;return y?v.inputs=[n({},v.inputs[c],{script:h})]:v.inputs[c].script=h,l.startUntrustedHashTransactionInput(!y&&S,v,g,y,!!d&&!p,f).then(function(){return(0,o.doIf)(!y,function(){return(0,o.doIf)(void 0!==t,function(){return l.provideOutputFullChangePath(t)}).then(function(){return l.hashOutputFull(N,f)})})}).then(function(){return l.signTransaction(r[c],i,s,d,f)}).then(function(e){D.push(e),A.inputs[c].script=C,S&&(S=!1)})})}).then(function(){for(var r=0;r3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],u=this,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,f=Buffer.alloc(0),d=Buffer.alloc(0),p=Buffer.alloc(4);p.writeUInt32LE(c,0);var h=Buffer.alloc(4);h.writeUInt32LE(l,0);var v=[],g=[],m=[],E=!0,y={inputs:[],version:p};l>0&&(y.timestamp=h);var C=s?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),w=Buffer.from(t,"hex");return(0,o.foreach)(e,function(e){return(0,o.doIf)(!0,function(){return C(e[1],e[0]).then(function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:4294967295,0),v.push({trustedInput:!1,value:s?Buffer.from(r,"hex"):Buffer.from(r,"hex").slice(4,40),sequence:t})})}).then(function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&g.push(r[t])})}).then(function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:4294967295,0),y.inputs.push({script:f,prevout:d,sequence:t})}}).then(function(){return(0,o.doIf)(s,function(){return u.startUntrustedHashTransactionInput(!0,y,v,!0).then(function(){return u.hashOutputFull(w)})})}).then(function(){return(0,o.foreach)(e,function(t,c){var l=e[c].length>=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):g[c].script,d=Object.assign({},y),p=s?[v[c]]:v;return s?d.inputs=[n({},d.inputs[c],{script:l})]:d.inputs[c].script=l,u.startUntrustedHashTransactionInput(!s&&E,d,p,s).then(function(){return(0,o.doIf)(!s,function(){return u.hashOutputFull(w)})}).then(function(){return u.signTransaction(r[c],a,i).then(function(e){m.push(e.toString("hex")),y.inputs[c].script=f,E&&(E=!1)})})})}).then(function(){return m})}},{key:"compressPublicKey",value:function(e){var r=0!=(1&e[64])?3:2,t=Buffer.alloc(1);return t[0]=r,Buffer.concat([t,e.slice(1,33)])}},{key:"createVarint",value:function(e){if(e<253){var r=Buffer.alloc(1);return r[0]=e,r}if(e<=65535){var t=Buffer.alloc(3);return t[0]=253,t[1]=255&e,t[2]=e>>8&255,t}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&e,n[2]=e>>8&255,n[3]=e>>16&255,n[4]=e>>24&255,n}},{key:"splitTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],a=[],i=[],s=!1,u=0,c=Buffer.alloc(0),l=Buffer.alloc(0),f=Buffer.alloc(0),d=Buffer.alloc(0),p=o.includes("decred"),h=Buffer.from(e,"hex"),v=h.slice(u,u+4),g=v.equals(Buffer.from([3,0,0,128]))||v.equals(Buffer.from([4,0,0,128]));u+=4,!t&&r&&0===h[u]&&0!==h[u+1]&&(u+=2,s=!0),t&&(c=h.slice(u,4+u),u+=4),g&&(f=h.slice(u,4+u),u+=4);var m=this.getVarint(h,u),E=m[0];u+=m[1];for(var y=0;y3&&void 0!==arguments[3]?arguments[3]:[],a=o.includes("decred"),i=o.includes("bech32"),s=Buffer.alloc(0),u=void 0!==e.witness&&!r;e.inputs.forEach(function(e){s=a||i?Buffer.concat([s,e.prevout,Buffer.from([0]),e.sequence]):Buffer.concat([s,e.prevout,n.createVarint(e.script.length),e.script,e.sequence])});var c=this.serializeTransactionOutputs(e);return void 0!==e.outputs&&void 0!==e.locktime&&(c=Buffer.concat([c,u&&e.witness||Buffer.alloc(0),e.locktime,e.nExpiryHeight||Buffer.alloc(0),e.extraData||Buffer.alloc(0)])),Buffer.concat([e.version,t||Buffer.alloc(0),e.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),this.createVarint(e.inputs.length),s,c])}},{key:"displayTransactionDebug",value:function(e){console.log("version "+e.version.toString("hex")),e.inputs.forEach(function(e,r){var t=e.prevout.toString("hex"),n=e.script.toString("hex"),o=e.sequence.toString("hex");console.log("input "+r+" prevout "+t+" script "+n+" sequence "+o)}),(e.outputs||[]).forEach(function(e,r){var t=e.amount.toString("hex"),n=e.script.toString("hex");console.log("output "+r+" amount "+t+" script "+n)}),void 0!==e.locktime&&console.log("locktime "+e.locktime.toString("hex"))}}]),e}();r.default=c}),s=t(i),u=Object.freeze({default:s,__moduleExports:i});function c(){}function l(){l.init.call(this)}function f(e){return void 0===e._maxListeners?l.defaultMaxListeners:e._maxListeners}function d(e,r,t,n){var o,a,i,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",r,t.listener?t.listener:t),a=e._events),i=a[r]):(a=e._events=new c,e._eventsCount=0),i){if("function"==typeof i?i=a[r]=n?[t,i]:[i,t]:n?i.unshift(t):i.push(t),!i.warned&&(o=f(e))&&o>0&&i.length>o){i.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=r,u.count=i.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else i=a[r]=t,++e._eventsCount;return e}function p(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function h(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function v(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}c.prototype=Object.create(null),l.EventEmitter=l,l.usingDomains=!1,l.prototype.domain=void 0,l.prototype._events=void 0,l.prototype._maxListeners=void 0,l.defaultMaxListeners=10,l.init=function(){this.domain=null,l.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new c,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},l.prototype.getMaxListeners=function(){return f(this)},l.prototype.emit=function(e){var r,t,n,o,a,i,s,u="error"===e;if(i=this._events)u=u&&null==i.error;else if(!u)return!1;if(s=this.domain,u){if(r=arguments[1],!s){if(r instanceof Error)throw r;var c=new Error('Uncaught, unspecified "error" event. ('+r+")");throw c.context=r,c}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=s,r.domainThrown=!1,s.emit("error",r),!1}if(!(t=i[e]))return!1;var l="function"==typeof t;switch(n=arguments.length){case 1:!function(e,r,t){if(r)e.call(t);else for(var n=e.length,o=v(e,n),a=0;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new c,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var g=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var i=JSON.parse(r.message);i.message&&i.name&&(r=i)}catch(e){}var s=void 0;if("string"==typeof r.name){var u=r.name,c=o[u];if(c)s=c(r);else{var l="Error"===u?Error:n[u];l||(console.warn("deserializing an unknown class '"+u+"'"),l=a(u)),s=Object.create(l.prototype);try{for(var f in r)r.hasOwnProperty(f)&&(s[f]=r[f])}catch(e){}}}else s=new Error(r.message);return!s.stack&&Error.captureStackTrace&&Error.captureStackTrace(s,e),s}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?function e(r,n){var o={};n.push(r);var a=!0;var i=!1;var s=void 0;try{for(var u,c=Object.keys(r)[Symbol.iterator]();!(a=(u=c.next()).done);a=!0){var l=u.value,f=r[l];"function"!=typeof f&&(f&&"object"===(void 0===f?"undefined":t(f))?-1!==n.indexOf(r[l])?o[l]="[Circular]":o[l]=e(r[l],n.slice(0)):o[l]=f)}}catch(e){i=!0,s=e}finally{try{!a&&c.return&&c.return()}finally{if(i)throw s}}"string"==typeof r.name&&(o.name=r.name);"string"==typeof r.message&&(o.message=r.message);"string"==typeof r.stack&&(o.stack=r.stack);return o}(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e}});t(g);g.addCustomErrorDeserializer,g.createCustomErrorClass,g.deserializeError,g.serializeError;var m=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=g.serializeError,r.deserializeError=g.deserializeError,r.createCustomErrorClass=g.createCustomErrorClass,r.addCustomErrorDeserializer=g.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,g.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,g.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,g.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,g.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,g.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,g.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,g.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,g.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,g.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,g.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,g.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,g.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,g.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,g.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,g.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,g.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,g.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,g.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,g.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,g.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,g.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,g.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,g.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,g.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,g.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,g.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,g.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,g.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,g.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,g.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,g.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,g.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,g.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,g.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,g.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,g.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,g.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,g.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,g.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,g.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,g.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,g.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,g.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,g.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,g.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,g.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,g.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,g.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,g.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,g.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,g.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,g.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,g.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,g.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,g.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,g.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,g.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,g.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,g.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,g.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,g.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,g.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,g.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,g.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,g.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,g.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,g.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,g.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,g.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,g.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,g.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,g.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,g.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,g.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,g.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,g.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,g.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,g.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,g.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,g.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,g.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,g.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,g.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,g.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,g.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,g.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,g.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,g.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,g.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,g.addCustomErrorDeserializer)("TransportError",function(e){return new t(e.message,e.id)});var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find(function(r){return n[r]===e})||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,g.addCustomErrorDeserializer)("TransportStatusError",function(e){return new a(e.statusCode)})});t(m);m.StatusCodes,m.DBNotReset,m.DBWrongPassword,m.NoDBPathGiven,m.FirmwareOrAppUpdateRequired,m.LedgerAPI5xx,m.LedgerAPI4xx,m.GenuineCheckFailed,m.PairingFailed,m.SyncError,m.FeeTooHigh,m.FeeRequired,m.FeeNotLoaded,m.CantScanQRCode,m.ETHAddressNonEIP,m.WrongAppForCurrency,m.WrongDeviceForAccount,m.WebsocketConnectionFailed,m.WebsocketConnectionError,m.DeviceShouldStayInApp,m.TransportWebUSBGestureRequired,m.TransportInterfaceNotAvailable,m.TransportOpenUserCancelled,m.UserRefusedOnDevice,m.UserRefusedAllowManager,m.UserRefusedFirmwareUpdate,m.UserRefusedAddress,m.UserRefusedDeviceNameChange,m.UpdateYourApp,m.UnavailableTezosOriginatedAccountSend,m.UnavailableTezosOriginatedAccountReceive,m.RecipientRequired,m.MCUNotGenuineToDashboard,m.UnexpectedBootloader,m.TimeoutTagged,m.RecommendUndelegation,m.RecommendSubAccountsToEmpty,m.PasswordIncorrectError,m.PasswordsDontMatchError,m.GasLessThanEstimate,m.NotSupportedLegacyAddress,m.NotEnoughGas,m.NoAccessToCamera,m.NotEnoughBalanceBecauseDestinationNotCreated,m.NotEnoughSpendableBalance,m.NotEnoughBalanceInParentAccount,m.NotEnoughBalanceToDelegate,m.NotEnoughBalance,m.NoAddressesFound,m.NetworkDown,m.ManagerUninstallBTCDep,m.ManagerNotEnoughSpaceError,m.ManagerFirmwareNotEnoughSpaceError,m.ManagerDeviceLockedError,m.ManagerAppDepUninstallRequired,m.ManagerAppDepInstallRequired,m.ManagerAppRelyOnBTCError,m.ManagerAppAlreadyInstalledError,m.LedgerAPINotAvailable,m.LedgerAPIErrorWithMessage,m.LedgerAPIError,m.UnknownMCU,m.LatestMCUInstalledError,m.InvalidAddressBecauseDestinationIsAlsoSource,m.InvalidAddress,m.InvalidXRPTag,m.HardResetFail,m.FeeEstimationFailed,m.EthAppPleaseEnableContractData,m.EnpointConfigError,m.DisconnectedDeviceDuringOperation,m.DisconnectedDevice,m.DeviceSocketNoBulkStatus,m.DeviceSocketFail,m.DeviceNameInvalid,m.DeviceHalted,m.DeviceInOSUExpected,m.DeviceOnDashboardUnexpected,m.DeviceOnDashboardExpected,m.DeviceNotGenuineError,m.DeviceGenuineSocketEarlyClose,m.DeviceAppVerifyNotSupported,m.CurrencyNotSupported,m.CashAddrNotSupported,m.CantOpenDevice,m.BtcUnmatchedApp,m.BluetoothRequired,m.AmountRequired,m.AccountNotSupported,m.AccountNameRequiredError,m.addCustomErrorDeserializer,m.createCustomErrorClass,m.deserializeError,m.serializeError,m.TransportError,m.getAltStatusMessage,m.TransportStatusError;var E=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[m.StatusCodes.OK];return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(u.length>=256)){e.next=2;break}throw new m.TransportError("data.length exceed 256 bytes limit. Got: "+u.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([u.length]),u]));case 4:if(i=e.sent,s=i.readUInt16BE(i.length-2),c.some(function(e){return e===s})){e.next=8;break}throw new m.TransportStatusError(s);case 8:return e.abrupt("return",i);case 9:case"end":return e.stop()}},e,n)})),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=a(regeneratorRuntime.mark(function e(r){var t,o,a;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new m.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise(function(e){t=e}),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}},e,n,[[5,,10,14]])})),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise(function(n,o){var a=!1,i=e.listen({next:function(t){a=!0,i&&i.unsubscribe(),s&&clearTimeout(s),e.open(t.descriptor,r).then(n,o)},error:function(e){s&&clearTimeout(s),o(e)},complete:function(){s&&clearTimeout(s),a||o(new m.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),s=t?setTimeout(function(){i.unsubscribe(),o(new m.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))},t):null})}}]),e}();i.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",i.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=i});t(E);E.getAltStatusMessage,E.StatusCodes,E.TransportStatusError,E.TransportError;var y=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),i=r-5,s=Math.ceil(a.length/i);a=Buffer.concat([a,Buffer.alloc(s*i-a.length+1).fill(0)]);for(var u=[],c=0;ci&&(a=a.slice(0,i)),{data:a,dataLength:i,sequence:s}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}});t(y);var C=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find(function(e){return e.productIdMM===t})},r.identifyProductName=function(e){var r=o[e];return a.find(function(e){return e.id===r})},[]),s={};for(var u in n){var c=n[u],l=c.bluetoothSpec;if(l)for(var f=0;f0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}},e,this)})),function(){return o.apply(this,arguments)});function s(e){return function(){var r=e.apply(this,arguments);return new Promise(function(e,t){return function n(o,a){try{var i=r[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then(function(e){n("next",e)},function(e){n("throw",e)});e(s)}("next")})}}var u=[{vendorId:C.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}});t(I);I.isSupported,I.getFirstLedgerDevice,I.getLedgerDevices,I.requestLedgerDevice;var b=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),i=(0,o.default)(n,a),s=i.makeBlocks(r),u=0;case 5:if(!(u "+s[u].toString("hex")),t.next=9,e.device.transferOut(3,s[u]);case 9:u++,t.next=5;break;case 12:c=void 0,l=void 0;case 14:if(c=i.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:f=t.sent,d=Buffer.from(f.data.buffer),(0,w.log)("hid-frame","<= "+d.toString("hex")),l=i.reduceResponse(l,d),t.next=14;break;case 23:return(0,w.log)("apdu","<= "+c.toString("hex")),t.abrupt("return",c);case 25:case"end":return t.stop()}},t,e)}))).catch(function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new m.DisconnectedDeviceDuringOperation(r.message);throw r})}};r.default=s}),B=t(b),D=Object.freeze({default:B,__moduleExports:b});e.Btc=u,e.TransportWebUSB=D,Object.defineProperty(e,"__esModule",{value:!0})}); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From a6dc6644a50acf1382d9b1129599c06a85f9c54e Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 14:23:09 +1100 Subject: [PATCH 08/78] more --- js/ledger.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index 36c47c91..b62b905a 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,7 +2,9 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.NewLedger={})}(this,function(e){"use strict";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,r){return e(r={exports:{}},r.exports),r.exports}n(function(e){var r=function(e){var r,t=Object.prototype,n=t.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",i=o.asyncIterator||"@@asyncIterator",s=o.toStringTag||"@@toStringTag";function u(e,r,t){return Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[r]}try{u({},"")}catch(e){u=function(e,r,t){return e[r]=t}}function c(e,r,t,n){var o=r&&r.prototype instanceof g?r:g,a=Object.create(o.prototype),i=new A(n||[]);return a._invoke=function(e,r,t){var n=f;return function(o,a){if(n===p)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return N()}for(t.method=o,t.arg=a;;){var i=t.delegate;if(i){var s=D(i,t);if(s){if(s===v)continue;return s}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if(n===f)throw n=h,t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);n=p;var u=l(e,r,t);if("normal"===u.type){if(n=t.done?h:d,u.arg===v)continue;return{value:u.arg,done:t.done}}"throw"===u.type&&(n=h,t.method="throw",t.arg=u.arg)}}}(e,t,i),a}function l(e,r,t){try{return{type:"normal",arg:e.call(r,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=c;var f="suspendedStart",d="suspendedYield",p="executing",h="completed",v={};function g(){}function m(){}function E(){}var y={};u(y,a,function(){return this});var C=Object.getPrototypeOf,w=C&&C(C(x([])));w&&w!==t&&n.call(w,a)&&(y=w);var I=E.prototype=g.prototype=Object.create(y);function b(e){["next","throw","return"].forEach(function(r){u(e,r,function(e){return this._invoke(r,e)})})}function B(e,r){var t;this._invoke=function(o,a){function i(){return new r(function(t,i){!function t(o,a,i,s){var u=l(e[o],e,a);if("throw"!==u.type){var c=u.arg,f=c.value;return f&&"object"==typeof f&&n.call(f,"__await")?r.resolve(f.__await).then(function(e){t("next",e,i,s)},function(e){t("throw",e,i,s)}):r.resolve(f).then(function(e){c.value=e,i(c)},function(e){return t("throw",e,i,s)})}s(u.arg)}(o,a,t,i)})}return t=t?t.then(i,i):i()}}function D(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,D(e,t),"throw"===t.method))return v;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=l(n,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,v;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,v):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,v)}function T(e){var r={tryLoc:e[0]};1 in e&&(r.catchLoc=e[1]),2 in e&&(r.finallyLoc=e[2],r.afterLoc=e[3]),this.tryEntries.push(r)}function S(e){var r=e.completion||{};r.type="normal",delete r.arg,e.completion=r}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function x(e){if(e){var t=e[a];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function t(){for(;++o=0;--a){var i=this.tryEntries[a],s=i.completion;if("root"===i.tryLoc)return o("end");if(i.tryLoc<=this.prev){var u=n.call(i,"catchLoc"),c=n.call(i,"finallyLoc");if(u&&c){if(this.prev=0;--t){var o=this.tryEntries[t];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--r){var t=this.tryEntries[r];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),S(t),v}},catch:function(e){for(var r=this.tryEntries.length-1;r>=0;--r){var t=this.tryEntries[r];if(t.tryLoc===e){var n=t.completion;if("throw"===n.type){var o=n.arg;S(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:x(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),v}},e}(e.exports);try{regeneratorRuntime=r}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}});var o=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.defer=function(){var e=void 0,r=void 0,t=new Promise(function(t,n){e=t,r=n});if(!e||!r)throw"defer() error";return{promise:t,resolve:e,reject:r}},r.splitPath=function(e){var r=[];return e.split("/").forEach(function(e){var t=parseInt(e,10);isNaN(t)||(e.length>1&&"'"===e[e.length-1]&&(t+=2147483648),r.push(t))}),r},r.eachSeries=function(e,r){return e.reduce(function(e,t){return e.then(function(){return r(t)})},Promise.resolve())},r.foreach=function(e,r){return Promise.resolve().then(function(){return function e(t,n,o){return t>=n.length?o:r(n[t],t).then(function(r){return o.push(r),e(t+1,n,o)})}(0,e,[])})},r.doIf=function(e,r){return Promise.resolve().then(function(){if(e)return r()})},r.asyncWhile=function(e,r){return Promise.resolve([]).then(function t(n){return e()?r().then(function(e){return n.push(e),t(n)}):n})};r.isLedgerDevice=function(e){return 9601===e.vendorId&&15228===e.productId||11415===e.vendorId}});t(o);o.defer,o.splitPath,o.eachSeries,o.foreach,o.doIf,o.asyncWhile,o.isLedgerDevice;var a={}.createHash,i=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t,n=Object.assign||function(e){for(var r=1;r1&&void 0!==arguments[1]?arguments[1]:"BTC";!function(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}(this,e),this.transport=r,r.decorateAppAPIMethods(this,["getWalletPublicKey","signP2SHTransaction","signMessageNew","createPaymentTransactionNew"],t)}return i(e,[{key:"hashPublicKey",value:function(e){return(0,s.default)("rmd160").update((0,s.default)("sha256").update(e).digest()).digest()}},{key:"getWalletPublicKey_private",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=n({verify:!1,format:"legacy"},r),a=t.verify,i=t.format;if(!(i in u))throw new Error("btc.getWalletPublicKey invalid format="+i);var s=(0,o.splitPath)(e),c=a?1:0,l=u[i],f=Buffer.alloc(1+4*s.length);return f[0]=s.length,s.forEach(function(e,r){f.writeUInt32BE(e,1+4*r)}),this.transport.send(224,64,c,l,f).then(function(e){var r=e[0],t=e[1+r];return{publicKey:e.slice(1,1+r).toString("hex"),bitcoinAddress:e.slice(1+r+1,1+r+1+t).toString("ascii"),chainCode:e.slice(1+r+1+t,1+r+1+t+32).toString("hex")}})}},{key:"getWalletPublicKey",value:function(e,r){var t=void 0;return arguments.length>2||"boolean"==typeof r?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),t={verify:!!r,format:arguments[2]?"p2sh":"legacy"}):t=r||{},this.getWalletPublicKey_private(e,t)}},{key:"getTrustedInputRaw",value:function(e,r){var t=void 0,n=!1;if("number"==typeof r){n=!0;var o=Buffer.alloc(4);o.writeUInt32BE(r,0),t=Buffer.concat([o,e],e.length+4)}else t=e;return this.transport.send(224,66,n?0:128,0,t).then(function(e){return e.slice(0,e.length-2).toString("hex")})}},{key:"getTrustedInput",value:function(e,r){var t=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],a=r.inputs,i=r.outputs,s=r.locktime;if(!i||!s)throw new Error("getTrustedInput: locktime & outputs is expected");var u=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e){return t.getTrustedInputRaw(e)},f=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),this.createVarint(a.length)]);return this.getTrustedInputRaw(f,e).then(function(){return(0,o.eachSeries)(a,function(e){var r=u?e.tree||Buffer.from([0]):Buffer.alloc(0),n=Buffer.concat([e.prevout,r,c?Buffer.from([0]):t.createVarint(e.script.length)]);return t.getTrustedInputRaw(n).then(function(){return u?l(Buffer.concat([e.script,e.sequence])):c?l(e.sequence):function(e,r){for(var n=[],a=0;a!==e.length;){var i=e.length-a>50?50:e.length-a;a+i!==e.length?n.push(e.slice(a,a+i)):n.push(Buffer.concat([e.slice(a,a+i),r])),a+=i}return 0===e.length&&n.push(r),(0,o.eachSeries)(n,function(e){return t.getTrustedInputRaw(e)})}(e.script,e.sequence)})}).then(function(){var e=t.createVarint(i.length);return t.getTrustedInputRaw(e)})}).then(function(){return(0,o.eachSeries)(i,function(e){var r=e.amount;return r=Buffer.concat([r,u?Buffer.from([0,0]):Buffer.alloc(0),t.createVarint(e.script.length),e.script]),t.getTrustedInputRaw(r).then(function(){})}).then(function(){var e=u?Buffer.concat([s,Buffer.from([0,0,0,0])]):s;return t.getTrustedInputRaw(e)})})}},{key:"getTrustedInputBIP143",value:function(){var e,r=(e=regeneratorRuntime.mark(function e(r,t){var n,o,a,i,u,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t){e.next=2;break}throw new Error("getTrustedInputBIP143: missing tx");case 2:if(!c.includes("decred")){e.next=5;break}throw new Error("Decred does not implement BIP143");case 5:if((n=(0,s.default)("sha256")).update(this.serializeTransaction(t,!0)),o=n.digest(),(n=(0,s.default)("sha256")).update(o),o=n.digest(),(a=Buffer.alloc(4)).writeUInt32LE(r,0),i=t.outputs,u=t.locktime,i&&u){e.next=16;break}throw new Error("getTrustedInputBIP143: locktime & outputs is expected");case 16:if(i[r]){e.next=18;break}throw new Error("getTrustedInputBIP143: wrong index");case 18:return o=Buffer.concat([o,a,i[r].amount]),e.next=21,o.toString("hex");case 21:return e.abrupt("return",e.sent);case 22:case"end":return e.stop()}},e,this)}),function(){var r=e.apply(this,arguments);return new Promise(function(e,t){return function n(o,a){try{var i=r[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then(function(e){n("next",e)},function(e){n("throw",e)});e(s)}("next")})});return function(e,t){return r.apply(this,arguments)}}()},{key:"getVarint",value:function(e,r){if(e[r]<253)return[e[r],1];if(253===e[r])return[(e[r+2]<<8)+e[r+1],3];if(254===e[r])return[(e[r+4]<<24)+(e[r+3]<<16)+(e[r+2]<<8)+e[r+1],5];throw new Error("getVarint called with unexpected parameters")}},{key:"startUntrustedHashTransactionInputRaw",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],i=n?a.includes("sapling")?5:o?4:2:0;return this.transport.send(224,68,r?0:128,e?i:128,t)}},{key:"startUntrustedHashTransactionInput",value:function(e,r,t){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=this,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[],u=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),this.createVarint(r.inputs.length)]);return this.startUntrustedHashTransactionInputRaw(e,!0,u,n,i,s).then(function(){var c=0,l=s.includes("decred");return(0,o.eachSeries)(r.inputs,function(r){var f=void 0;return f=n?Buffer.from([2]):t[c].trustedInput?Buffer.from([1,t[c].value.length]):Buffer.from([0]),u=Buffer.concat([f,t[c].value,l?Buffer.from([0]):Buffer.alloc(0),a.createVarint(r.script.length)]),a.startUntrustedHashTransactionInputRaw(e,!1,u,n,i,s).then(function(){var t=[],u=0;if(0===r.script.length)t.push(r.sequence);else for(;u!==r.script.length;){var l=r.script.length-u>50?50:r.script.length-u;u+l!==r.script.length?t.push(r.script.slice(u,u+l)):t.push(Buffer.concat([r.script.slice(u,u+l),r.sequence])),u+=l}return(0,o.eachSeries)(t,function(r){return a.startUntrustedHashTransactionInputRaw(e,!1,r,n,i,s)}).then(function(){c++})})})})}},{key:"provideOutputFullChangePath",value:function(e){var r=(0,o.splitPath)(e),t=Buffer.alloc(1+4*r.length);return t[0]=r.length,r.forEach(function(e,r){t.writeUInt32BE(e,1+4*r)}),this.transport.send(224,74,255,0,t)}},{key:"hashOutputFull",value:function(e){var r=this,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=0;return t.includes("decred")?this.transport.send(224,74,128,0,e):(0,o.asyncWhile)(function(){return n=e.length?e.length-n:50,o=n+t===e.length?128:0,a=e.slice(n,n+t);return r.transport.send(224,74,o,0,a).then(function(){n+=t})})}},{key:"signTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments[3],a=(arguments.length>4&&void 0!==arguments[4]?arguments[4]:[]).includes("decred"),i=(0,o.splitPath)(e),s=0,u=Buffer.alloc(4*i.length);i.forEach(function(e){u.writeUInt32BE(e,s),s+=4});var c=Buffer.alloc(4);c.writeUInt32BE(r,0);var l=a?Buffer.concat([Buffer.from([i.length]),u,c,n||Buffer.from([0,0,0,0]),Buffer.from([t])]):Buffer.concat([Buffer.from([i.length]),u,Buffer.from([0]),c,Buffer.from([t])]);return n&&!a&&(l=Buffer.concat([l,n])),this.transport.send(224,72,0,0,l).then(function(e){return e.length>0?(e[0]=48,e.slice(0,e.length-2)):e})}},{key:"signMessageNew",value:function(e,r){for(var t=this,n=(0,o.splitPath)(e),a=new Buffer(r,"hex"),i=0,s=[],u=function(){var e=0===i?49-4*n.length-4:50,r=i+e>a.length?a.length-i:e,t=new Buffer(0===i?1+4*n.length+2+r:r);0===i?(t[0]=n.length,n.forEach(function(e,r){t.writeUInt32BE(e,1+4*r)}),t.writeUInt16BE(a.length,1+4*n.length),a.copy(t,1+4*n.length+2,i,i+r)):a.copy(t,0,i,i+r),s.push(t),i+=r};i!==a.length;)u();return(0,o.foreach)(s,function(e,r){return t.transport.send(224,78,0,0===r?1:128,e)}).then(function(){return t.transport.send(224,78,128,0,Buffer.from([0])).then(function(e){var r=e[0]-48,t=e.slice(4,4+e[3]);0===t[0]&&(t=t.slice(1)),t=t.toString("hex");var n=4+e[3]+2,o=e.slice(n,n+e[n-1]);return 0===o[0]&&(o=o.slice(1)),{v:r,r:t,s:o=o.toString("hex")}})})}},{key:"createPaymentTransactionNew",value:function(e,r,t,a){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1,u=arguments.length>6&&void 0!==arguments[6]&&arguments[6],c=arguments[7],l=this,f=arguments.length>8&&void 0!==arguments[8]?arguments[8]:[],d=arguments[9],p=f.includes("decred"),h=f.includes("stealthcoin"),v=void 0!==c,g=Date.now(),m=f.includes("sapling"),E=u&&f.includes("bech32"),y=u||!!f&&(f.includes("abc")||f.includes("gold")||f.includes("bip143"))||!!d&&!p,C=Buffer.alloc(0),w=Buffer.alloc(0),I=Buffer.alloc(4);d&&!p?I.writeUInt32LE(m?2147483652:2147483651,0):h?I.writeUInt32LE(2,0):I.writeUInt32LE(1,0);var b=[],B=[],D=[],T=[],S=!0,A={inputs:[],version:I,timestamp:Buffer.alloc(0)},x=y?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),N=Buffer.from(a,"hex");return(0,o.foreach)(e,function(e){return(0,o.doIf)(!0,function(){return x(e[1],e[0],f).then(function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:4294967295,0),b.push({trustedInput:!0,value:Buffer.from(r,"hex"),sequence:t})})}).then(function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&B.push(r[t])}).then(function(){d&&!p?(A.nVersionGroupId=Buffer.from(m?[133,32,47,137]:[112,130,196,3]),A.nExpiryHeight=d,A.extraData=Buffer.from(m?[0,0,0,0,0,0,0,0,0,0,0]:[0])):p&&(A.nExpiryHeight=d)})}).then(function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:4294967295,0),A.inputs.push({script:C,prevout:w,sequence:t})}}).then(function(){return(0,o.doIf)(!0,function(){return(0,o.foreach)(e,function(e,t){return l.getWalletPublicKey_private(r[t])}).then(function(e){for(var r=0;r=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):u?Buffer.concat([Buffer.from([118,169,20]),l.hashPublicKey(T[c]),Buffer.from([136,172])]):B[c].script,v=Object.assign({},A),g=y?[b[c]]:b;return y?v.inputs=[n({},v.inputs[c],{script:h})]:v.inputs[c].script=h,l.startUntrustedHashTransactionInput(!y&&S,v,g,y,!!d&&!p,f).then(function(){return(0,o.doIf)(!y,function(){return(0,o.doIf)(void 0!==t,function(){return l.provideOutputFullChangePath(t)}).then(function(){return l.hashOutputFull(N,f)})})}).then(function(){return l.signTransaction(r[c],i,s,d,f)}).then(function(e){D.push(e),A.inputs[c].script=C,S&&(S=!1)})})}).then(function(){for(var r=0;r3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],u=this,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,f=Buffer.alloc(0),d=Buffer.alloc(0),p=Buffer.alloc(4);p.writeUInt32LE(c,0);var h=Buffer.alloc(4);h.writeUInt32LE(l,0);var v=[],g=[],m=[],E=!0,y={inputs:[],version:p};l>0&&(y.timestamp=h);var C=s?this.getTrustedInputBIP143.bind(this):this.getTrustedInput.bind(this),w=Buffer.from(t,"hex");return(0,o.foreach)(e,function(e){return(0,o.doIf)(!0,function(){return C(e[1],e[0]).then(function(r){var t=Buffer.alloc(4);t.writeUInt32LE(e.length>=4&&"number"==typeof e[3]?e[3]:4294967295,0),v.push({trustedInput:!1,value:s?Buffer.from(r,"hex"):Buffer.from(r,"hex").slice(4,40),sequence:t})})}).then(function(){var r=e[0].outputs,t=e[1];r&&t<=r.length-1&&g.push(r[t])})}).then(function(){for(var r=0;r=4&&"number"==typeof e[r][3]?e[r][3]:4294967295,0),y.inputs.push({script:f,prevout:d,sequence:t})}}).then(function(){return(0,o.doIf)(s,function(){return u.startUntrustedHashTransactionInput(!0,y,v,!0).then(function(){return u.hashOutputFull(w)})})}).then(function(){return(0,o.foreach)(e,function(t,c){var l=e[c].length>=3&&"string"==typeof e[c][2]?Buffer.from(e[c][2],"hex"):g[c].script,d=Object.assign({},y),p=s?[v[c]]:v;return s?d.inputs=[n({},d.inputs[c],{script:l})]:d.inputs[c].script=l,u.startUntrustedHashTransactionInput(!s&&E,d,p,s).then(function(){return(0,o.doIf)(!s,function(){return u.hashOutputFull(w)})}).then(function(){return u.signTransaction(r[c],a,i).then(function(e){m.push(e.toString("hex")),y.inputs[c].script=f,E&&(E=!1)})})})}).then(function(){return m})}},{key:"compressPublicKey",value:function(e){var r=0!=(1&e[64])?3:2,t=Buffer.alloc(1);return t[0]=r,Buffer.concat([t,e.slice(1,33)])}},{key:"createVarint",value:function(e){if(e<253){var r=Buffer.alloc(1);return r[0]=e,r}if(e<=65535){var t=Buffer.alloc(3);return t[0]=253,t[1]=255&e,t[2]=e>>8&255,t}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&e,n[2]=e>>8&255,n[3]=e>>16&255,n[4]=e>>24&255,n}},{key:"splitTransaction",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],a=[],i=[],s=!1,u=0,c=Buffer.alloc(0),l=Buffer.alloc(0),f=Buffer.alloc(0),d=Buffer.alloc(0),p=o.includes("decred"),h=Buffer.from(e,"hex"),v=h.slice(u,u+4),g=v.equals(Buffer.from([3,0,0,128]))||v.equals(Buffer.from([4,0,0,128]));u+=4,!t&&r&&0===h[u]&&0!==h[u+1]&&(u+=2,s=!0),t&&(c=h.slice(u,4+u),u+=4),g&&(f=h.slice(u,4+u),u+=4);var m=this.getVarint(h,u),E=m[0];u+=m[1];for(var y=0;y3&&void 0!==arguments[3]?arguments[3]:[],a=o.includes("decred"),i=o.includes("bech32"),s=Buffer.alloc(0),u=void 0!==e.witness&&!r;e.inputs.forEach(function(e){s=a||i?Buffer.concat([s,e.prevout,Buffer.from([0]),e.sequence]):Buffer.concat([s,e.prevout,n.createVarint(e.script.length),e.script,e.sequence])});var c=this.serializeTransactionOutputs(e);return void 0!==e.outputs&&void 0!==e.locktime&&(c=Buffer.concat([c,u&&e.witness||Buffer.alloc(0),e.locktime,e.nExpiryHeight||Buffer.alloc(0),e.extraData||Buffer.alloc(0)])),Buffer.concat([e.version,t||Buffer.alloc(0),e.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),this.createVarint(e.inputs.length),s,c])}},{key:"displayTransactionDebug",value:function(e){console.log("version "+e.version.toString("hex")),e.inputs.forEach(function(e,r){var t=e.prevout.toString("hex"),n=e.script.toString("hex"),o=e.sequence.toString("hex");console.log("input "+r+" prevout "+t+" script "+n+" sequence "+o)}),(e.outputs||[]).forEach(function(e,r){var t=e.amount.toString("hex"),n=e.script.toString("hex");console.log("output "+r+" amount "+t+" script "+n)}),void 0!==e.locktime&&console.log("locktime "+e.locktime.toString("hex"))}}]),e}();r.default=c}),s=t(i),u=Object.freeze({default:s,__moduleExports:i});function c(){}function l(){l.init.call(this)}function f(e){return void 0===e._maxListeners?l.defaultMaxListeners:e._maxListeners}function d(e,r,t,n){var o,a,i,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",r,t.listener?t.listener:t),a=e._events),i=a[r]):(a=e._events=new c,e._eventsCount=0),i){if("function"==typeof i?i=a[r]=n?[t,i]:[i,t]:n?i.unshift(t):i.push(t),!i.warned&&(o=f(e))&&o>0&&i.length>o){i.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+r+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=r,u.count=i.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else i=a[r]=t,++e._eventsCount;return e}function p(e,r,t){var n=!1;function o(){e.removeListener(r,o),n||(n=!0,t.apply(e,arguments))}return o.listener=t,o}function h(e){var r=this._events;if(r){var t=r[e];if("function"==typeof t)return 1;if(t)return t.length}return 0}function v(e,r){for(var t=new Array(r);r--;)t[r]=e[r];return t}c.prototype=Object.create(null),l.EventEmitter=l,l.usingDomains=!1,l.prototype.domain=void 0,l.prototype._events=void 0,l.prototype._maxListeners=void 0,l.defaultMaxListeners=10,l.init=function(){this.domain=null,l.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new c,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},l.prototype.getMaxListeners=function(){return f(this)},l.prototype.emit=function(e){var r,t,n,o,a,i,s,u="error"===e;if(i=this._events)u=u&&null==i.error;else if(!u)return!1;if(s=this.domain,u){if(r=arguments[1],!s){if(r instanceof Error)throw r;var c=new Error('Uncaught, unspecified "error" event. ('+r+")");throw c.context=r,c}return r||(r=new Error('Uncaught, unspecified "error" event')),r.domainEmitter=this,r.domain=s,r.domainThrown=!1,s.emit("error",r),!1}if(!(t=i[e]))return!1;var l="function"==typeof t;switch(n=arguments.length){case 1:!function(e,r,t){if(r)e.call(t);else for(var n=e.length,o=v(e,n),a=0;a0;)if(t[a]===r||t[a].listener&&t[a].listener===r){i=t[a].listener,o=a;break}if(o<0)return this;if(1===t.length){if(t[0]=void 0,0==--this._eventsCount)return this._events=new c,this;delete n[e]}else!function(e,r){for(var t=r,n=t+1,o=e.length;n0?Reflect.ownKeys(this._events):[]};var g=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},o={},a=(r.addCustomErrorDeserializer=function(e,r){o[e]=r},r.createCustomErrorClass=function(e){var r=function(r,t){Object.assign(this,t),this.name=e,this.message=r||e,this.stack=(new Error).stack};return r.prototype=new Error,n[e]=r,r});r.deserializeError=function e(r){if("object"===(void 0===r?"undefined":t(r))&&r){try{var i=JSON.parse(r.message);i.message&&i.name&&(r=i)}catch(e){}var s=void 0;if("string"==typeof r.name){var u=r.name,c=o[u];if(c)s=c(r);else{var l="Error"===u?Error:n[u];l||(console.warn("deserializing an unknown class '"+u+"'"),l=a(u)),s=Object.create(l.prototype);try{for(var f in r)r.hasOwnProperty(f)&&(s[f]=r[f])}catch(e){}}}else s=new Error(r.message);return!s.stack&&Error.captureStackTrace&&Error.captureStackTrace(s,e),s}return new Error(String(r))},r.serializeError=function(e){return e?"object"===(void 0===e?"undefined":t(e))?function e(r,n){var o={};n.push(r);var a=!0;var i=!1;var s=void 0;try{for(var u,c=Object.keys(r)[Symbol.iterator]();!(a=(u=c.next()).done);a=!0){var l=u.value,f=r[l];"function"!=typeof f&&(f&&"object"===(void 0===f?"undefined":t(f))?-1!==n.indexOf(r[l])?o[l]="[Circular]":o[l]=e(r[l],n.slice(0)):o[l]=f)}}catch(e){i=!0,s=e}finally{try{!a&&c.return&&c.return()}finally{if(i)throw s}}"string"==typeof r.name&&(o.name=r.name);"string"==typeof r.message&&(o.message=r.message);"string"==typeof r.stack&&(o.stack=r.stack);return o}(e,[]):"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e:e}});t(g);g.addCustomErrorDeserializer,g.createCustomErrorClass,g.deserializeError,g.serializeError;var m=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.StatusCodes=r.DBNotReset=r.DBWrongPassword=r.NoDBPathGiven=r.FirmwareOrAppUpdateRequired=r.LedgerAPI5xx=r.LedgerAPI4xx=r.GenuineCheckFailed=r.PairingFailed=r.SyncError=r.FeeTooHigh=r.FeeRequired=r.FeeNotLoaded=r.CantScanQRCode=r.ETHAddressNonEIP=r.WrongAppForCurrency=r.WrongDeviceForAccount=r.WebsocketConnectionFailed=r.WebsocketConnectionError=r.DeviceShouldStayInApp=r.TransportWebUSBGestureRequired=r.TransportInterfaceNotAvailable=r.TransportOpenUserCancelled=r.UserRefusedOnDevice=r.UserRefusedAllowManager=r.UserRefusedFirmwareUpdate=r.UserRefusedAddress=r.UserRefusedDeviceNameChange=r.UpdateYourApp=r.UnavailableTezosOriginatedAccountSend=r.UnavailableTezosOriginatedAccountReceive=r.RecipientRequired=r.MCUNotGenuineToDashboard=r.UnexpectedBootloader=r.TimeoutTagged=r.RecommendUndelegation=r.RecommendSubAccountsToEmpty=r.PasswordIncorrectError=r.PasswordsDontMatchError=r.GasLessThanEstimate=r.NotSupportedLegacyAddress=r.NotEnoughGas=r.NoAccessToCamera=r.NotEnoughBalanceBecauseDestinationNotCreated=r.NotEnoughSpendableBalance=r.NotEnoughBalanceInParentAccount=r.NotEnoughBalanceToDelegate=r.NotEnoughBalance=r.NoAddressesFound=r.NetworkDown=r.ManagerUninstallBTCDep=r.ManagerNotEnoughSpaceError=r.ManagerFirmwareNotEnoughSpaceError=r.ManagerDeviceLockedError=r.ManagerAppDepUninstallRequired=r.ManagerAppDepInstallRequired=r.ManagerAppRelyOnBTCError=r.ManagerAppAlreadyInstalledError=r.LedgerAPINotAvailable=r.LedgerAPIErrorWithMessage=r.LedgerAPIError=r.UnknownMCU=r.LatestMCUInstalledError=r.InvalidAddressBecauseDestinationIsAlsoSource=r.InvalidAddress=r.InvalidXRPTag=r.HardResetFail=r.FeeEstimationFailed=r.EthAppPleaseEnableContractData=r.EnpointConfigError=r.DisconnectedDeviceDuringOperation=r.DisconnectedDevice=r.DeviceSocketNoBulkStatus=r.DeviceSocketFail=r.DeviceNameInvalid=r.DeviceHalted=r.DeviceInOSUExpected=r.DeviceOnDashboardUnexpected=r.DeviceOnDashboardExpected=r.DeviceNotGenuineError=r.DeviceGenuineSocketEarlyClose=r.DeviceAppVerifyNotSupported=r.CurrencyNotSupported=r.CashAddrNotSupported=r.CantOpenDevice=r.BtcUnmatchedApp=r.BluetoothRequired=r.AmountRequired=r.AccountNotSupported=r.AccountNameRequiredError=r.addCustomErrorDeserializer=r.createCustomErrorClass=r.deserializeError=r.serializeError=void 0,r.TransportError=t,r.getAltStatusMessage=o,r.TransportStatusError=a,r.serializeError=g.serializeError,r.deserializeError=g.deserializeError,r.createCustomErrorClass=g.createCustomErrorClass,r.addCustomErrorDeserializer=g.addCustomErrorDeserializer;r.AccountNameRequiredError=(0,g.createCustomErrorClass)("AccountNameRequired"),r.AccountNotSupported=(0,g.createCustomErrorClass)("AccountNotSupported"),r.AmountRequired=(0,g.createCustomErrorClass)("AmountRequired"),r.BluetoothRequired=(0,g.createCustomErrorClass)("BluetoothRequired"),r.BtcUnmatchedApp=(0,g.createCustomErrorClass)("BtcUnmatchedApp"),r.CantOpenDevice=(0,g.createCustomErrorClass)("CantOpenDevice"),r.CashAddrNotSupported=(0,g.createCustomErrorClass)("CashAddrNotSupported"),r.CurrencyNotSupported=(0,g.createCustomErrorClass)("CurrencyNotSupported"),r.DeviceAppVerifyNotSupported=(0,g.createCustomErrorClass)("DeviceAppVerifyNotSupported"),r.DeviceGenuineSocketEarlyClose=(0,g.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),r.DeviceNotGenuineError=(0,g.createCustomErrorClass)("DeviceNotGenuine"),r.DeviceOnDashboardExpected=(0,g.createCustomErrorClass)("DeviceOnDashboardExpected"),r.DeviceOnDashboardUnexpected=(0,g.createCustomErrorClass)("DeviceOnDashboardUnexpected"),r.DeviceInOSUExpected=(0,g.createCustomErrorClass)("DeviceInOSUExpected"),r.DeviceHalted=(0,g.createCustomErrorClass)("DeviceHalted"),r.DeviceNameInvalid=(0,g.createCustomErrorClass)("DeviceNameInvalid"),r.DeviceSocketFail=(0,g.createCustomErrorClass)("DeviceSocketFail"),r.DeviceSocketNoBulkStatus=(0,g.createCustomErrorClass)("DeviceSocketNoBulkStatus"),r.DisconnectedDevice=(0,g.createCustomErrorClass)("DisconnectedDevice"),r.DisconnectedDeviceDuringOperation=(0,g.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),r.EnpointConfigError=(0,g.createCustomErrorClass)("EnpointConfig"),r.EthAppPleaseEnableContractData=(0,g.createCustomErrorClass)("EthAppPleaseEnableContractData"),r.FeeEstimationFailed=(0,g.createCustomErrorClass)("FeeEstimationFailed"),r.HardResetFail=(0,g.createCustomErrorClass)("HardResetFail"),r.InvalidXRPTag=(0,g.createCustomErrorClass)("InvalidXRPTag"),r.InvalidAddress=(0,g.createCustomErrorClass)("InvalidAddress"),r.InvalidAddressBecauseDestinationIsAlsoSource=(0,g.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),r.LatestMCUInstalledError=(0,g.createCustomErrorClass)("LatestMCUInstalledError"),r.UnknownMCU=(0,g.createCustomErrorClass)("UnknownMCU"),r.LedgerAPIError=(0,g.createCustomErrorClass)("LedgerAPIError"),r.LedgerAPIErrorWithMessage=(0,g.createCustomErrorClass)("LedgerAPIErrorWithMessage"),r.LedgerAPINotAvailable=(0,g.createCustomErrorClass)("LedgerAPINotAvailable"),r.ManagerAppAlreadyInstalledError=(0,g.createCustomErrorClass)("ManagerAppAlreadyInstalled"),r.ManagerAppRelyOnBTCError=(0,g.createCustomErrorClass)("ManagerAppRelyOnBTC"),r.ManagerAppDepInstallRequired=(0,g.createCustomErrorClass)("ManagerAppDepInstallRequired"),r.ManagerAppDepUninstallRequired=(0,g.createCustomErrorClass)("ManagerAppDepUninstallRequired"),r.ManagerDeviceLockedError=(0,g.createCustomErrorClass)("ManagerDeviceLocked"),r.ManagerFirmwareNotEnoughSpaceError=(0,g.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),r.ManagerNotEnoughSpaceError=(0,g.createCustomErrorClass)("ManagerNotEnoughSpace"),r.ManagerUninstallBTCDep=(0,g.createCustomErrorClass)("ManagerUninstallBTCDep"),r.NetworkDown=(0,g.createCustomErrorClass)("NetworkDown"),r.NoAddressesFound=(0,g.createCustomErrorClass)("NoAddressesFound"),r.NotEnoughBalance=(0,g.createCustomErrorClass)("NotEnoughBalance"),r.NotEnoughBalanceToDelegate=(0,g.createCustomErrorClass)("NotEnoughBalanceToDelegate"),r.NotEnoughBalanceInParentAccount=(0,g.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),r.NotEnoughSpendableBalance=(0,g.createCustomErrorClass)("NotEnoughSpendableBalance"),r.NotEnoughBalanceBecauseDestinationNotCreated=(0,g.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),r.NoAccessToCamera=(0,g.createCustomErrorClass)("NoAccessToCamera"),r.NotEnoughGas=(0,g.createCustomErrorClass)("NotEnoughGas"),r.NotSupportedLegacyAddress=(0,g.createCustomErrorClass)("NotSupportedLegacyAddress"),r.GasLessThanEstimate=(0,g.createCustomErrorClass)("GasLessThanEstimate"),r.PasswordsDontMatchError=(0,g.createCustomErrorClass)("PasswordsDontMatch"),r.PasswordIncorrectError=(0,g.createCustomErrorClass)("PasswordIncorrect"),r.RecommendSubAccountsToEmpty=(0,g.createCustomErrorClass)("RecommendSubAccountsToEmpty"),r.RecommendUndelegation=(0,g.createCustomErrorClass)("RecommendUndelegation"),r.TimeoutTagged=(0,g.createCustomErrorClass)("TimeoutTagged"),r.UnexpectedBootloader=(0,g.createCustomErrorClass)("UnexpectedBootloader"),r.MCUNotGenuineToDashboard=(0,g.createCustomErrorClass)("MCUNotGenuineToDashboard"),r.RecipientRequired=(0,g.createCustomErrorClass)("RecipientRequired"),r.UnavailableTezosOriginatedAccountReceive=(0,g.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),r.UnavailableTezosOriginatedAccountSend=(0,g.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),r.UpdateYourApp=(0,g.createCustomErrorClass)("UpdateYourApp"),r.UserRefusedDeviceNameChange=(0,g.createCustomErrorClass)("UserRefusedDeviceNameChange"),r.UserRefusedAddress=(0,g.createCustomErrorClass)("UserRefusedAddress"),r.UserRefusedFirmwareUpdate=(0,g.createCustomErrorClass)("UserRefusedFirmwareUpdate"),r.UserRefusedAllowManager=(0,g.createCustomErrorClass)("UserRefusedAllowManager"),r.UserRefusedOnDevice=(0,g.createCustomErrorClass)("UserRefusedOnDevice"),r.TransportOpenUserCancelled=(0,g.createCustomErrorClass)("TransportOpenUserCancelled"),r.TransportInterfaceNotAvailable=(0,g.createCustomErrorClass)("TransportInterfaceNotAvailable"),r.TransportWebUSBGestureRequired=(0,g.createCustomErrorClass)("TransportWebUSBGestureRequired"),r.DeviceShouldStayInApp=(0,g.createCustomErrorClass)("DeviceShouldStayInApp"),r.WebsocketConnectionError=(0,g.createCustomErrorClass)("WebsocketConnectionError"),r.WebsocketConnectionFailed=(0,g.createCustomErrorClass)("WebsocketConnectionFailed"),r.WrongDeviceForAccount=(0,g.createCustomErrorClass)("WrongDeviceForAccount"),r.WrongAppForCurrency=(0,g.createCustomErrorClass)("WrongAppForCurrency"),r.ETHAddressNonEIP=(0,g.createCustomErrorClass)("ETHAddressNonEIP"),r.CantScanQRCode=(0,g.createCustomErrorClass)("CantScanQRCode"),r.FeeNotLoaded=(0,g.createCustomErrorClass)("FeeNotLoaded"),r.FeeRequired=(0,g.createCustomErrorClass)("FeeRequired"),r.FeeTooHigh=(0,g.createCustomErrorClass)("FeeTooHigh"),r.SyncError=(0,g.createCustomErrorClass)("SyncError"),r.PairingFailed=(0,g.createCustomErrorClass)("PairingFailed"),r.GenuineCheckFailed=(0,g.createCustomErrorClass)("GenuineCheckFailed"),r.LedgerAPI4xx=(0,g.createCustomErrorClass)("LedgerAPI4xx"),r.LedgerAPI5xx=(0,g.createCustomErrorClass)("LedgerAPI5xx"),r.FirmwareOrAppUpdateRequired=(0,g.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),r.NoDBPathGiven=(0,g.createCustomErrorClass)("NoDBPathGiven"),r.DBWrongPassword=(0,g.createCustomErrorClass)("DBWrongPassword"),r.DBNotReset=(0,g.createCustomErrorClass)("DBNotReset");function t(e,r){this.name="TransportError",this.message=e,this.stack=(new Error).stack,this.id=r}t.prototype=new Error,(0,g.addCustomErrorDeserializer)("TransportError",function(e){return new t(e.message,e.id)});var n=r.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function o(e){switch(e){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=e&&e<=28671)return"Internal error, please report"}function a(e){this.name="TransportStatusError";var r=Object.keys(n).find(function(r){return n[r]===e})||"UNKNOWN_ERROR",t=o(e)||r,a=e.toString(16);this.message="Ledger device: "+t+" (0x"+a+")",this.stack=(new Error).stack,this.statusCode=e,this.statusText=r}a.prototype=new Error,(0,g.addCustomErrorDeserializer)("TransportStatusError",function(e){return new a(e.statusCode)})});t(m);m.StatusCodes,m.DBNotReset,m.DBWrongPassword,m.NoDBPathGiven,m.FirmwareOrAppUpdateRequired,m.LedgerAPI5xx,m.LedgerAPI4xx,m.GenuineCheckFailed,m.PairingFailed,m.SyncError,m.FeeTooHigh,m.FeeRequired,m.FeeNotLoaded,m.CantScanQRCode,m.ETHAddressNonEIP,m.WrongAppForCurrency,m.WrongDeviceForAccount,m.WebsocketConnectionFailed,m.WebsocketConnectionError,m.DeviceShouldStayInApp,m.TransportWebUSBGestureRequired,m.TransportInterfaceNotAvailable,m.TransportOpenUserCancelled,m.UserRefusedOnDevice,m.UserRefusedAllowManager,m.UserRefusedFirmwareUpdate,m.UserRefusedAddress,m.UserRefusedDeviceNameChange,m.UpdateYourApp,m.UnavailableTezosOriginatedAccountSend,m.UnavailableTezosOriginatedAccountReceive,m.RecipientRequired,m.MCUNotGenuineToDashboard,m.UnexpectedBootloader,m.TimeoutTagged,m.RecommendUndelegation,m.RecommendSubAccountsToEmpty,m.PasswordIncorrectError,m.PasswordsDontMatchError,m.GasLessThanEstimate,m.NotSupportedLegacyAddress,m.NotEnoughGas,m.NoAccessToCamera,m.NotEnoughBalanceBecauseDestinationNotCreated,m.NotEnoughSpendableBalance,m.NotEnoughBalanceInParentAccount,m.NotEnoughBalanceToDelegate,m.NotEnoughBalance,m.NoAddressesFound,m.NetworkDown,m.ManagerUninstallBTCDep,m.ManagerNotEnoughSpaceError,m.ManagerFirmwareNotEnoughSpaceError,m.ManagerDeviceLockedError,m.ManagerAppDepUninstallRequired,m.ManagerAppDepInstallRequired,m.ManagerAppRelyOnBTCError,m.ManagerAppAlreadyInstalledError,m.LedgerAPINotAvailable,m.LedgerAPIErrorWithMessage,m.LedgerAPIError,m.UnknownMCU,m.LatestMCUInstalledError,m.InvalidAddressBecauseDestinationIsAlsoSource,m.InvalidAddress,m.InvalidXRPTag,m.HardResetFail,m.FeeEstimationFailed,m.EthAppPleaseEnableContractData,m.EnpointConfigError,m.DisconnectedDeviceDuringOperation,m.DisconnectedDevice,m.DeviceSocketNoBulkStatus,m.DeviceSocketFail,m.DeviceNameInvalid,m.DeviceHalted,m.DeviceInOSUExpected,m.DeviceOnDashboardUnexpected,m.DeviceOnDashboardExpected,m.DeviceNotGenuineError,m.DeviceGenuineSocketEarlyClose,m.DeviceAppVerifyNotSupported,m.CurrencyNotSupported,m.CashAddrNotSupported,m.CantOpenDevice,m.BtcUnmatchedApp,m.BluetoothRequired,m.AmountRequired,m.AccountNotSupported,m.AccountNameRequiredError,m.addCustomErrorDeserializer,m.createCustomErrorClass,m.deserializeError,m.serializeError,m.TransportError,m.getAltStatusMessage,m.TransportStatusError;var E=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.getAltStatusMessage=r.StatusCodes=r.TransportStatusError=r.TransportError=void 0;var t,n=function(){function e(e,r){for(var t=0;t4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[m.StatusCodes.OK];return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(u.length>=256)){e.next=2;break}throw new m.TransportError("data.length exceed 256 bytes limit. Got: "+u.length,"DataLengthTooBig");case 2:return e.next=4,n.exchange(Buffer.concat([Buffer.from([r,t,o,a]),Buffer.from([u.length]),u]));case 4:if(i=e.sent,s=i.readUInt16BE(i.length-2),c.some(function(e){return e===s})){e.next=8;break}throw new m.TransportStatusError(s);case 8:return e.abrupt("return",i);case 9:case"end":return e.stop()}},e,n)})),function(e,t,n,o){return r.apply(this,arguments)}),this.exchangeAtomicImpl=(t=a(regeneratorRuntime.mark(function e(r){var t,o,a;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.exchangeBusyPromise){e.next=2;break}throw new m.TransportError("Transport race condition","RaceCondition");case 2:return t=void 0,o=new Promise(function(e){t=e}),n.exchangeBusyPromise=o,e.prev=5,e.next=8,r();case 8:return a=e.sent,e.abrupt("return",a);case 10:return e.prev=10,t&&t(),n.exchangeBusyPromise=null,e.finish(10);case 14:case"end":return e.stop()}},e,n,[[5,,10,14]])})),function(e){return t.apply(this,arguments)}),this._appAPIlock=null}return n(e,[{key:"on",value:function(e,r){this._events.on(e,r)}},{key:"off",value:function(e,r){this._events.removeListener(e,r)}},{key:"emit",value:function(e){for(var r,t=arguments.length,n=Array(t>1?t-1:0),o=1;o0&&void 0!==arguments[0]?arguments[0]:3e3,t=arguments[1];return new Promise(function(n,o){var a=!1,i=e.listen({next:function(t){a=!0,i&&i.unsubscribe(),s&&clearTimeout(s),e.open(t.descriptor,r).then(n,o)},error:function(e){s&&clearTimeout(s),o(e)},complete:function(){s&&clearTimeout(s),a||o(new m.TransportError(e.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),s=t?setTimeout(function(){i.unsubscribe(),o(new m.TransportError(e.ErrorMessage_ListenTimeout,"ListenTimeout"))},t):null})}}]),e}();i.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",i.ErrorMessage_NoDeviceFound="No Ledger device found",r.default=i});t(E);E.getAltStatusMessage,E.StatusCodes,E.TransportStatusError,E.TransportError;var y=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t={data:Buffer.alloc(0),dataLength:0,sequence:0};r.default=function(e,r){return{makeBlocks:function(t){var n,o,a=Buffer.concat([(n=t.length,o=Buffer.alloc(2),o.writeUInt16BE(n,0),o),t]),i=r-5,s=Math.ceil(a.length/i);a=Buffer.concat([a,Buffer.alloc(s*i-a.length+1).fill(0)]);for(var u=[],c=0;ci&&(a=a.slice(0,i)),{data:a,dataLength:i,sequence:s}},getReducedResult:function(e){if(e&&e.dataLength===e.data.length)return e.data}}}});t(y);var C=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=Object.assign||function(e){for(var r=1;r>8;return a.find(function(e){return e.productIdMM===t})},r.identifyProductName=function(e){var r=o[e];return a.find(function(e){return e.id===r})},[]),s={};for(var u in n){var c=n[u],l=c.bluetoothSpec;if(l)for(var f=0;f0)){e.next=5;break}return e.abrupt("return",r[0]);case 5:return e.abrupt("return",a());case 6:case"end":return e.stop()}},e,this)})),function(){return o.apply(this,arguments)});function s(e){return function(){var r=e.apply(this,arguments);return new Promise(function(e,t){return function n(o,a){try{var i=r[o](a),s=i.value}catch(e){return void t(e)}if(!i.done)return Promise.resolve(s).then(function(e){n("next",e)},function(e){n("throw",e)});e(s)}("next")})}}var u=[{vendorId:C.ledgerUSBVendorId}];r.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)}});t(I);I.isSupported,I.getFirstLedgerDevice,I.getLedgerDevices,I.requestLedgerDevice;var b=n(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});var t=function(){function e(e,r){for(var t=0;t "+r.toString("hex")),i=(0,o.default)(n,a),s=i.makeBlocks(r),u=0;case 5:if(!(u "+s[u].toString("hex")),t.next=9,e.device.transferOut(3,s[u]);case 9:u++,t.next=5;break;case 12:c=void 0,l=void 0;case 14:if(c=i.getReducedResult(l)){t.next=23;break}return t.next=17,e.device.transferIn(3,a);case 17:f=t.sent,d=Buffer.from(f.data.buffer),(0,w.log)("hid-frame","<= "+d.toString("hex")),l=i.reduceResponse(l,d),t.next=14;break;case 23:return(0,w.log)("apdu","<= "+c.toString("hex")),t.abrupt("return",c);case 25:case"end":return t.stop()}},t,e)}))).catch(function(r){if(r&&r.message&&r.message.includes("disconnected"))throw e._emitDisconnect(r),new m.DisconnectedDeviceDuringOperation(r.message);throw r})}};r.default=s}),B=t(b),D=Object.freeze({default:B,__moduleExports:b});e.Btc=u,e.TransportWebUSB=D,Object.defineProperty(e,"__esModule",{value:!0})}); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("crypto"),require("buffer"),require("stream"),require("events"),require("util")):"function"==typeof define&&define.amd?define(["exports","crypto","buffer","stream","events","util"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={},t.require$$0$1,t.require$$0$2,t.require$$0$3,t.require$$0$4,t.require$$1)}(this,(function(t,e,r,n,i,o){"use strict";function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function u(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var a=s(e),h=s(r),f=s(n),c=s(i),l=s(o),p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof g?e:g,o=Object.create(i.prototype),s=new k(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return M()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===y)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===y)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",y={};function g(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(A([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=g.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return y;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return y}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,y;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,y):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function P(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function A(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),P(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;P(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:A(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),y}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const d=2147483648;var y=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=d)throw new Error("Invalid child index");if("h"===o[2]||"H"===o[2]||"'"===o[2])n[i]+=d;else if(0!=o[2].length)throw new Error("Invalid modifier")}return new y(n)},y.prototype.toPathArray=function(){return this.path},y.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var g=y,v=a.default.createHash,m={exports:{}}; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +!function(t,e){var r=h.default,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(m,m.exports);var w=m.exports.Buffer;var b=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=w.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var y=n;p!==o;)d[y++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=w.from(e)),!w.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var y=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var y=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?y+n:h[l-y.length]+y+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,y=p>>>13,g=0|s[2],v=8191&g,m=g>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,P=T>>>13,k=0|s[6],A=8191&k,M=k>>>13,x=0|s[7],N=8191&x,R=x>>>13,B=0|s[8],C=8191&B,U=B>>>13,L=0|s[9],D=8191&L,H=L>>>13,F=0|u[0],q=8191&F,j=F>>>13,G=0|u[1],K=8191&G,V=G>>>13,W=0|u[2],$=8191&W,z=W>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Q=0|u[4],Z=8191&Q,tt=Q>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,yt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var gt=(h+(n=Math.imul(c,q))|0)+((8191&(i=(i=Math.imul(c,j))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,j))+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,j))+Math.imul(y,q)|0,o=Math.imul(y,j);var vt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,V)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,j))+Math.imul(m,q)|0,o=Math.imul(m,j),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,V)|0)+Math.imul(y,K)|0,o=o+Math.imul(y,V)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,j))+Math.imul(E,q)|0,o=Math.imul(E,j),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,V)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,V)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(y,$)|0,o=o+Math.imul(y,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,j))+Math.imul(I,q)|0,o=Math.imul(I,j),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,V)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,V)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(y,Y)|0,o=o+Math.imul(y,J)|0;var bt=(h+(n=n+Math.imul(c,Z)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Z)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,j))+Math.imul(P,q)|0,o=Math.imul(P,j),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,V)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Z)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(A,q),i=(i=Math.imul(A,j))+Math.imul(M,q)|0,o=Math.imul(M,j),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Z)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Z)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(y,rt)|0,o=o+Math.imul(y,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,j))+Math.imul(R,q)|0,o=Math.imul(R,j),n=n+Math.imul(A,K)|0,i=(i=i+Math.imul(A,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(P,$)|0,o=o+Math.imul(P,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Z)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Z)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(y,ot)|0,o=o+Math.imul(y,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,q),i=(i=Math.imul(C,j))+Math.imul(U,q)|0,o=Math.imul(U,j),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(A,$)|0,i=(i=i+Math.imul(A,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(P,Y)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(y,at)|0,o=o+Math.imul(y,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,q),i=(i=Math.imul(D,j))+Math.imul(H,q)|0,o=Math.imul(H,j),n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(R,$)|0,o=o+Math.imul(R,z)|0,n=n+Math.imul(A,Y)|0,i=(i=i+Math.imul(A,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(y,ct)|0,o=o+Math.imul(y,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,yt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,yt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,V))+Math.imul(H,K)|0,o=Math.imul(H,V),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Y)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,tt)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(P,rt)|0,o=o+Math.imul(P,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,yt)|0)+Math.imul(y,dt)|0))<<13)|0;h=((o=o+Math.imul(y,yt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,tt)|0,n=n+Math.imul(A,rt)|0,i=(i=i+Math.imul(A,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(P,ot)|0,o=o+Math.imul(P,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var Pt=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,yt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,yt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(R,rt)|0,o=o+Math.imul(R,nt)|0,n=n+Math.imul(A,ot)|0,i=(i=i+Math.imul(A,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(P,at)|0,o=o+Math.imul(P,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,yt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,yt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Z),i=(i=Math.imul(D,tt))+Math.imul(H,Z)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(R,ot)|0,o=o+Math.imul(R,st)|0,n=n+Math.imul(A,at)|0,i=(i=i+Math.imul(A,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(P,ct)|0,o=o+Math.imul(P,lt)|0;var At=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,yt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,yt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(R,at)|0,o=o+Math.imul(R,ht)|0,n=n+Math.imul(A,ct)|0,i=(i=i+Math.imul(A,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,yt)|0)+Math.imul(P,dt)|0))<<13)|0;h=((o=o+Math.imul(P,yt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(R,ct)|0,o=o+Math.imul(R,lt)|0;var xt=(h+(n=n+Math.imul(A,dt)|0)|0)+((8191&(i=(i=i+Math.imul(A,yt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,yt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,yt)|0)+Math.imul(R,dt)|0))<<13)|0;h=((o=o+Math.imul(R,yt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Rt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,yt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,yt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,yt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,yt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=gt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=Pt,a[12]=kt,a[13]=At,a[14]=Mt,a[15]=xt,a[16]=Nt,a[17]=Rt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new y).mulp(t,e,r)}function y(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},y.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},y.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,y=1;0==(n.words[0]&y)&&d<26;++d,y<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var y=p,g=0;0!==y.cmp(u);g++)y=y.redSqr();r(g=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,p)}(q);var j={},G="6.5.4",K={},V=W;function W(t,e){if(!t)throw new Error(e||"Assertion failed")}W.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var $={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}($),function(t){var e=t,r=q.exports,n=V,i=$;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(K);var z,X={exports:{}};function Y(t){this.rand=t}if(X.exports=function(t){return z||(z=new Y(null)),z.generate(t)},X.exports.Rand=Y,Y.prototype.generate=function(t){return this._rand(t)},Y.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ot=it;function st(t,e){this.curve=t,this.type=e,this.precomputed=null}it.prototype.point=function(){throw new Error("Not implemented")},it.prototype.validate=function(){throw new Error("Not implemented")},it.prototype._fixedNafMul=function(t,e){nt(t.precomputed);var r=t._getDoubles(),n=et(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];nt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},it.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var y=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(y[1]=e[p].add(e[d]),y[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(y[1]=e[p].toJ().mixedAdd(e[d]),y[2]=e[p].add(e[d].neg())):(y[1]=e[p].toJ().mixedAdd(e[d]),y[2]=e[p].toJ().mixedAdd(e[d].neg()));var g=[-3,-1,-5,-7,0,7,5,1,3],v=rt(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},st.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},yt.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},yt.prototype.pointFromX=function(t,e){(t=new ct(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},yt.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},yt.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},vt.prototype.isInfinity=function(){return this.inf},vt.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},vt.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},vt.prototype.getX=function(){return this.x.fromRed()},vt.prototype.getY=function(){return this.y.fromRed()},vt.prototype.mul=function(t){return t=new ct(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},vt.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},vt.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},vt.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},vt.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},vt.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},lt(mt,pt.BasePoint),yt.prototype.jpoint=function(t,e,r){return new mt(this,t,e,r)},mt.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},mt.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},mt.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},mt.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},mt.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},mt.prototype.inspect=function(){return this.isInfinity()?"":""},mt.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var wt=q.exports,bt=ut.exports,Et=ot,_t=K;function St(t){Et.call(this,"mont",t),this.a=new wt(t.a,16).toRed(this.red),this.b=new wt(t.b,16).toRed(this.red),this.i4=new wt(4).toRed(this.red).redInvm(),this.two=new wt(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}bt(St,Et);var It=St;function Tt(t,e,r){Et.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new wt(e,16),this.z=new wt(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}St.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},bt(Tt,Et.BasePoint),St.prototype.decodePoint=function(t,e){return this.point(_t.toArray(t,e),1)},St.prototype.point=function(t,e){return new Tt(this,t,e)},St.prototype.pointFromJSON=function(t){return Tt.fromJSON(this,t)},Tt.prototype.precompute=function(){},Tt.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Tt.fromJSON=function(t,e){return new Tt(t,e[0],e[1]||t.one)},Tt.prototype.inspect=function(){return this.isInfinity()?"":""},Tt.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Tt.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},Tt.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},Tt.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},Tt.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},Tt.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Tt.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Ot=K,Pt=q.exports,kt=ut.exports,At=ot,Mt=Ot.assert;function xt(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,At.call(this,"edwards",t),this.a=new Pt(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new Pt(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new Pt(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Mt(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}kt(xt,At);var Nt=xt;function Rt(t,e,r,n,i){At.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new Pt(e,16),this.y=new Pt(r,16),this.z=n?new Pt(n,16):this.curve.one,this.t=i&&new Pt(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}xt.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},xt.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},xt.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},xt.prototype.pointFromX=function(t,e){(t=new Pt(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},xt.prototype.pointFromY=function(t,e){(t=new Pt(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},xt.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},kt(Rt,At.BasePoint),xt.prototype.pointFromJSON=function(t){return Rt.fromJSON(this,t)},xt.prototype.point=function(t,e,r,n){return new Rt(this,t,e,r,n)},Rt.fromJSON=function(t,e){return new Rt(t,e[0],e[1],e[2])},Rt.prototype.inspect=function(){return this.isInfinity()?"":""},Rt.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Rt.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Rt.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Rt.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Rt.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Rt.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Rt.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Rt.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Rt.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Rt.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Rt.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Rt.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Rt.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Rt.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Rt.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Rt.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Rt.prototype.toP=Rt.prototype.normalize,Rt.prototype.mixedAdd=Rt.prototype.add,function(t){var e=t;e.base=ot,e.short=gt,e.mont=It,e.edwards=Nt}(Q);var Bt={},Ct={},Ut={},Lt=V,Dt=ut.exports;function Ht(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function Ft(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function qt(t){return 1===t.length?"0"+t:t}function jt(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ut.inherits=Dt,Ut.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Ht(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ut.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ut.rotr32=function(t,e){return t>>>e|t<<32-e},Ut.rotl32=function(t,e){return t<>>32-e},Ut.sum32=function(t,e){return t+e>>>0},Ut.sum32_3=function(t,e,r){return t+e+r>>>0},Ut.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ut.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ut.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ut.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ut.sum64_lo=function(t,e,r,n){return e+n>>>0},Ut.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ut.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ut.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ut.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ut.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ut.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ut.shr64_hi=function(t,e,r){return t>>>r},Ut.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Gt={},Kt=Ut,Vt=V;function Wt(){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}Gt.BlockHash=Wt,Wt.prototype.update=function(t,e){if(t=Kt.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Kt.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},zt.g1_256=function(t){return Xt(t,17)^Xt(t,19)^t>>>10};var Zt=Ut,te=Gt,ee=zt,re=Zt.rotl32,ne=Zt.sum32,ie=Zt.sum32_5,oe=ee.ft_1,se=te.BlockHash,ue=[1518500249,1859775393,2400959708,3395469782];function ae(){if(!(this instanceof ae))return new ae;se.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Zt.inherits(ae,se);var he=ae;ae.blockSize=512,ae.outSize=160,ae.hmacStrength=80,ae.padLength=64,ae.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),kr(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Cr=Br;Br.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},Br.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Nr.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Fr=q.exports,qr=K,jr=qr.assert;function Gr(t,e){if(t instanceof Gr)return t;this._importDER(t,e)||(jr(t.r&&t.s,"Signature without r or s"),this.r=new Fr(t.r,16),this.s=new Fr(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Kr=Gr;function Vr(){this.place=0}function Wr(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function $r(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Gr.prototype._importDER=function(t,e){t=qr.toArray(t,e);var r=new Vr;if(48!==t[r.place++])return!1;var n=Wr(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Wr(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Wr(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Fr(o),this.s=new Fr(u),this.recoveryParam=null,!0},Gr.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=$r(e),r=$r(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];zr(n,e.length),(n=n.concat(e)).push(2),zr(n,r.length);var i=n.concat(r),o=[48];return zr(o,i.length),o=o.concat(i),qr.encode(o,t)};var Xr=q.exports,Yr=Cr,Jr=K,Qr=Bt,Zr=X.exports,tn=Jr.assert,en=Hr,rn=Kr;function nn(t){if(!(this instanceof nn))return new nn(t);"string"==typeof t&&(tn(Object.prototype.hasOwnProperty.call(Qr,t),"Unknown curve "+t),t=Qr[t]),t instanceof Qr.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var on=nn;nn.prototype.keyPair=function(t){return new en(this,t)},nn.prototype.keyFromPrivate=function(t,e){return en.fromPrivate(this,t,e)},nn.prototype.keyFromPublic=function(t,e){return en.fromPublic(this,t,e)},nn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Yr({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Zr(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Xr(2));;){var i=new Xr(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},nn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},nn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Xr(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Yr({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Xr(1)),h=0;;h++){var f=n.k?n.k(h):new Xr(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var y=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),y^=1),new rn({r:p,s:d,recoveryParam:y})}}}}}},nn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Xr(t,16)),r=this.keyFromPublic(r,n);var i=(e=new rn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},nn.prototype.recoverPubKey=function(t,e,r,n){tn((3&r)===r,"The recovery param is more than two bits"),e=new rn(e,n);var i=this.n,o=new Xr(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},nn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new rn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var sn=K,un=sn.assert,an=sn.parseBytes,hn=sn.cachedProperty;function fn(t,e){this.eddsa=t,this._secret=an(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=an(e.pub)}fn.fromPublic=function(t,e){return e instanceof fn?e:new fn(t,{pub:e})},fn.fromSecret=function(t,e){return e instanceof fn?e:new fn(t,{secret:e})},fn.prototype.secret=function(){return this._secret},hn(fn,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),hn(fn,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),hn(fn,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),hn(fn,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),hn(fn,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),hn(fn,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),fn.prototype.sign=function(t){return un(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},fn.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},fn.prototype.getSecret=function(t){return un(this._secret,"KeyPair is public only"),sn.encode(this.secret(),t)},fn.prototype.getPublic=function(t){return sn.encode(this.pubBytes(),t)};var cn=fn,ln=q.exports,pn=K,dn=pn.assert,yn=pn.cachedProperty,gn=pn.parseBytes;function vn(t,e){this.eddsa=t,"object"!=typeof e&&(e=gn(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),dn(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ln&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}yn(vn,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),yn(vn,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),yn(vn,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),yn(vn,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),vn.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},vn.prototype.toHex=function(){return pn.encode(this.toBytes(),"hex").toUpperCase()};var mn=vn,wn=Ct,bn=Bt,En=K,_n=En.assert,Sn=En.parseBytes,In=cn,Tn=mn;function On(t){if(_n("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof On))return new On(t);t=bn[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=wn.sha512}var Pn=On;On.prototype.sign=function(t,e){t=Sn(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},On.prototype.verify=function(t,e,r){t=Sn(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},On.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Zn(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Cn)&&(!(n.compare(Ln)>=0)&&(4===e&&65===t.length))}function zn(t){return 4!==t[0]}function Xn(t){return!!Vn(t)&&(t.compare(Cn)>0&&t.compare(Un)<0)}function Yn(t,e){return void 0===t&&void 0!==e?zn(e):void 0===t||t}function Jn(t){return new Nn(t)}function Qn(t){return t.toArrayLike(Buffer,"be",32)}function Zn(t){return Rn.curve.decodePoint(t)}function ti(t,e){return Buffer.from(t._encode(e))}function ei(t,e,r){if(!Vn(t))throw new TypeError(Kn);if(!Xn(e))throw new TypeError(qn);if(void 0!==r&&!Vn(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Jn(e),i=Jn(t);let o,s;Bn(t,e,(function(t){const e=Jn(t),r=Fn.mul(e);return!r.isInfinity()&&(o=r.x.umod(Dn),0!==o.isZero()&&(s=e.invm(Dn).mul(i.add(n.mul(o))).umod(Dn),0!==s.isZero()))}),Xn,r),s.cmp(Hn)>0&&(s=Dn.sub(s));const u=Buffer.allocUnsafe(64);return Qn(o).copy(u,0),Qn(s).copy(u,32),u}var ri={isPoint:$n,isPointCompressed:function(t){return!!$n(t)&&zn(t)},isPrivate:Xn,pointAdd:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!$n(e))throw new TypeError(jn);const n=Zn(t),i=Zn(e),o=n.add(i);return o.isInfinity()?null:ti(o,Yn(r,t))},pointAddScalar:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!Wn(e))throw new TypeError(Gn);const n=Yn(r,t),i=Zn(t);if(0===e.compare(Cn))return ti(i,n);const o=Jn(e),s=Fn.mul(o),u=i.add(s);return u.isInfinity()?null:ti(u,n)},pointCompress:function(t,e){if(!$n(t))throw new TypeError(jn);const r=Zn(t);if(r.isInfinity())throw new TypeError(jn);return ti(r,Yn(e,t))},pointFromScalar:function(t,e){if(!Xn(t))throw new TypeError(qn);const r=Jn(t),n=Fn.mul(r);return n.isInfinity()?null:ti(n,Yn(e))},pointMultiply:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!Wn(e))throw new TypeError(Gn);const n=Yn(r,t),i=Zn(t),o=Jn(e),s=i.mul(o);return s.isInfinity()?null:ti(s,n)},privateAdd:function(t,e){if(!Xn(t))throw new TypeError(qn);if(!Wn(e))throw new TypeError(Gn);const r=Jn(t),n=Jn(e),i=Qn(r.add(n).umod(Dn));return Xn(i)?i:null},privateSub:function(t,e){if(!Xn(t))throw new TypeError(qn);if(!Wn(e))throw new TypeError(Gn);const r=Jn(t),n=Jn(e),i=Qn(r.sub(n).umod(Dn));return Xn(i)?i:null},sign:function(t,e){return ei(t,e)},signWithEntropy:function(t,e,r){return ei(t,e,r)},verify:function(t,e,r,n){if(!Vn(t))throw new TypeError(Kn);if(!$n(e))throw new TypeError(jn);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Un)<0&&r.compare(Un)<0}(r))throw new TypeError("Expected Signature");const i=Zn(e),o=Jn(r.slice(0,32)),s=Jn(r.slice(32,64));if(n&&s.cmp(Hn)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Jn(t),a=s.invm(Dn),h=u.mul(a).umod(Dn),f=o.mul(a).umod(Dn),c=Fn.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Dn).eq(o)}};try{F.exports=require("./native")}catch(t){F.exports=ri}var ni={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var ii in ni.Null=ni.Nil,ni)ni[ii].toJSON=function(t){return t}.bind(null,ii);var oi=ni,si=oi;function ui(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function ai(t){return si.Nil(t)?"":ui(t.constructor)}function hi(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function fi(t){return si.Function(t)?t.toJSON?t.toJSON():ui(t):si.Array(t)?"Array":t&&si.Object(t)?"Object":void 0!==t?t:""}function ci(t,e,r){var n=function(t){return si.Function(t)?"":si.String(t)?JSON.stringify(t):t&&si.Object(t)?"":t}(e);return"Expected "+fi(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function li(t,e,r){r=r||ai(e),this.message=ci(t,e,r),hi(this,li),this.__type=t,this.__value=e,this.__valueTypeName=r}function pi(t,e,r,n,i){t?(i=i||ai(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ci('property "'+fi(r)+o+fi(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',hi(this,li),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}li.prototype=Object.create(Error.prototype),li.prototype.constructor=li,pi.prototype=Object.create(Error.prototype),pi.prototype.constructor=li;var di={TfTypeError:li,TfPropertyTypeError:pi,tfCustomError:function(t,e){return new li(t,{},e)},tfSubError:function(t,e,r){return t instanceof pi?(e=e+"."+t.__property,t=new pi(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof li&&(t=new pi(t.__type,e,r,t.__value,t.__valueTypeName)),hi(t),t},tfJSON:fi,getValueTypeName:ai},yi=oi,gi=di;function vi(t){return Buffer.isBuffer(t)}function mi(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function wi(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw gi.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var bi=wi.bind(null,yi.Array),Ei=wi.bind(null,vi),_i=wi.bind(null,mi),Si=wi.bind(null,yi.String);var Ii=Math.pow(2,53)-1;var Ti={ArrayN:bi,Buffer:vi,BufferN:Ei,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:mi,HexN:_i,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-Ii&&t<=Ii&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=Ii&&Math.floor(t)===t}};for(var Oi in Ti)Ti[Oi].toJSON=function(t){return t}.bind(null,Oi);var Pi=Ti,ki=oi,Ai=di.tfJSON,Mi=di.TfTypeError,xi=di.TfPropertyTypeError,Ni=di.tfSubError,Ri=di.getValueTypeName,Bi={arrayOf:function(t,e){function r(r,n){return!!ki.Array(r)&&(!ki.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return Ui(t,e,n)}catch(t){throw Ni(t,r)}}))))))}return t=Ci(t),e=e||{},r.toJSON=function(){var r="["+Ai(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return ki.Nil(r)||e(r,n,t)}return e=Ci(e),r.toJSON=function(){return"?"+Ai(e)},r},map:function(t,e){function r(r,n){if(!ki.Object(r))return!1;if(ki.Nil(r))return!1;for(var i in r){try{e&&Ui(e,i,n)}catch(t){throw Ni(t,i,"key")}try{var o=r[i];Ui(t,o,n)}catch(t){throw Ni(t,i)}}return!0}return t=Ci(t),e&&(e=Ci(e)),r.toJSON=e?function(){return"{"+Ai(e)+": "+Ai(t)+"}"}:function(){return"{"+Ai(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ci(t[r]);function n(t,r){if(!ki.Object(t))return!1;if(ki.Nil(t))return!1;var n;try{for(n in e){Ui(e[n],t[n],r)}}catch(t){throw Ni(t,n)}if(r)for(n in t)if(!e[n])throw new xi(void 0,n);return!0}return n.toJSON=function(){return Ai(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return t.some((function(t){try{return Ui(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Ai).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return t.every((function(t){try{return Ui(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Ai).join(" & ")},e},quacksLike:function(t){function e(e){return t===Ri(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return!ki.Nil(e)&&(!ki.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return Ui(t,e[n],r)}catch(t){throw Ni(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Ai).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ci(t){if(ki.String(t))return"?"===t[0]?Bi.maybe(t.slice(1)):ki[t]||Bi.quacksLike(t);if(t&&ki.Object(t)){if(ki.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Bi.arrayOf(t[0])}return Bi.object(t)}return ki.Function(t)?t:Bi.value(t)}function Ui(t,e,r,n){if(ki.Function(t)){if(t(e,r))return!0;throw new Mi(n||t,e)}return Ui(Ci(t),e,r)}for(var Li in Bi.oneOf=Bi.anyOf,ki)Ui[Li]=ki[Li];for(Li in Bi)Ui[Li]=Bi[Li];var Di=Pi;for(Li in Di)Ui[Li]=Di[Li];Ui.compile=Ci,Ui.TfTypeError=Mi,Ui.TfPropertyTypeError=xi;var Hi=Ui,Fi=O;function qi(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function ji(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Gi={decode:function(t,e){return qi(Fi.decode(t),e)},decodeRaw:qi,encode:function(t,e,r){return"number"==typeof t?Fi.encode(ji(t,e,r)):Fi.encode(ji(t.version,t.privateKey,t.compressed))},encodeRaw:ji};Object.defineProperty(C,"__esModule",{value:!0});const Ki=U,Vi=O,Wi=F.exports,$i=Hi,zi=Gi,Xi=$i.BufferN(32),Yi=$i.compile({wif:$i.UInt8,bip32:{public:$i.UInt32,private:$i.UInt32}}),Ji={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Qi=2147483648,Zi=Math.pow(2,31)-1;function to(t){return $i.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function eo(t){return $i.UInt32(t)&&t<=Zi}class ro{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,$i(Yi,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Wi.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Ki.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return oo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Vi.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return zi.encode(this.network.wif,this.privateKey,!0)}derive(t){$i($i.UInt32,t);const e=t>=Qi,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Ki.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Wi.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Wi.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=oo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Wi.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=io(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return $i(eo,t),this.derive(t+Qi)}derivePath(t){$i(to,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Wi.sign(t,this.privateKey);{let e=Wi.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Wi.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Wi.verify(t,this.publicKey,e)}}function no(t,e,r){return io(t,e,r)}function io(t,e,r,n,i,o){if($i({privateKey:Xi,chainCode:Xi},{privateKey:t,chainCode:e}),r=r||Ji,!Wi.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new ro(t,void 0,e,r,n,i,o)}function oo(t,e,r,n,i,o){if($i({publicKey:$i.BufferN(33),chainCode:Xi},{publicKey:t,chainCode:e}),r=r||Ji,!Wi.isPoint(t))throw new TypeError("Point is not on the curve");return new ro(void 0,t,e,r,n,i,o)}C.fromBase58=function(t,e){const r=Vi.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Ji;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=io(r.slice(46,78),u,e,i,s,o)}else{a=oo(r.slice(45,78),u,e,i,s,o)}return a},C.fromPrivateKey=no,C.fromPublicKey=function(t,e,r){return oo(t,e,r)},C.fromSeed=function(t,e){if($i($i.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Ji;const r=Ki.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return no(r.slice(0,32),r.slice(32),e)},Object.defineProperty(B,"__esModule",{value:!0});var so=C;B.fromSeed=so.fromSeed,B.fromBase58=so.fromBase58,B.fromPublicKey=so.fromPublicKey,B.fromPrivateKey=so.fromPrivateKey;var uo={},ao={};Object.defineProperty(ao,"__esModule",{value:!0}),ao.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ao.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ao.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ho={},fo={},co={},lo={};Object.defineProperty(lo,"__esModule",{value:!0}),lo.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var po={},yo={};Object.defineProperty(yo,"__esModule",{value:!0});const go=Hi,vo=Math.pow(2,31)-1;function mo(t){return go.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}yo.UInt31=function(t){return go.UInt32(t)&&t<=vo},yo.BIP32Path=mo,mo.toJSON=()=>"BIP32 derivation path",yo.Signer=function(t){return(go.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};yo.Satoshi=function(t){return go.UInt53(t)&&t<=21e14},yo.ECPoint=go.quacksLike("Point"),yo.Network=go.compile({messagePrefix:go.oneOf(go.Buffer,go.String),bip32:{public:go.UInt32,private:go.UInt32},pubKeyHash:go.UInt8,scriptHash:go.UInt8,wif:go.UInt8}),yo.Buffer256bit=go.BufferN(32),yo.Hash160bit=go.BufferN(20),yo.Hash256bit=go.BufferN(32),yo.Number=go.Number,yo.Array=go.Array,yo.Boolean=go.Boolean,yo.String=go.String,yo.Buffer=go.Buffer,yo.Hex=go.Hex,yo.maybe=go.maybe,yo.tuple=go.tuple,yo.UInt8=go.UInt8,yo.UInt32=go.UInt32,yo.Function=go.Function,yo.BufferN=go.BufferN,yo.Null=go.Null,yo.oneOf=go.oneOf;var wo=m.exports.Buffer;var bo={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=wo.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(po,"__esModule",{value:!0});const Eo=yo,_o=bo,So=Hi,Io=Buffer.alloc(1,0);function To(t){let e=0;for(;0===t[e];)++e;return e===t.length?Io:128&(t=t.slice(e))[0]?Buffer.concat([Io,t],1+t.length):t}function Oo(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}po.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=_o.decode(t.slice(0,-1)),i=Oo(n.r),o=Oo(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},po.encode=function(t,e){So({signature:Eo.BufferN(64),hashType:Eo.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=To(t.slice(0,32)),o=To(t.slice(32,64));return Buffer.concat([_o.encode(i,o),n])};var Po={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ko=Po;function Ao(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ko.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ko.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},xo=Po,No={};for(var Ro in xo){No[xo[Ro]]=Ro}var Bo=No;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=lo,r=po,n=yo,i=bo,o=F.exports,s=Mo,u=Hi;t.OPS=Po;const a=Bo,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function y(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function g(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=y,t.decompile=g,t.toASM=function(t){return p(t)&&(t=g(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),y(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=g(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(co);var Co={};Object.defineProperty(Co,"__esModule",{value:!0}),Co.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Co.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(fo,"__esModule",{value:!0});const Uo=ao,Lo=co,Do=Co,Ho=Hi,Fo=Lo.OPS;fo.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ho({network:Ho.maybe(Ho.Object),output:Ho.maybe(Ho.Buffer),data:Ho.maybe(Ho.arrayOf(Ho.Buffer))},t);const r={name:"embed",network:t.network||Uo.bitcoin};if(Do.prop(r,"output",(()=>{if(t.data)return Lo.compile([Fo.OP_RETURN].concat(t.data))})),Do.prop(r,"data",(()=>{if(t.output)return Lo.decompile(t.output).slice(1)})),e.validate&&t.output){const e=Lo.decompile(t.output);if(e[0]!==Fo.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ho.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var qo={};Object.defineProperty(qo,"__esModule",{value:!0});const jo=ao,Go=co,Ko=Co,Vo=Go.OPS,Wo=Hi,$o=F.exports,zo=Vo.OP_RESERVED;function Xo(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}qo.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Go.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Vo.OP_0)}e=Object.assign({validate:!0},e||{}),Wo({network:Wo.maybe(Wo.Object),m:Wo.maybe(Wo.Number),n:Wo.maybe(Wo.Number),output:Wo.maybe(Wo.Buffer),pubkeys:Wo.maybe(Wo.arrayOf($o.isPoint)),signatures:Wo.maybe(Wo.arrayOf(r)),input:Wo.maybe(Wo.Buffer)},t);const n={network:t.network||jo.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Go.decompile(t),n.m=i[0]-zo,n.n=i[i.length-2]-zo,n.pubkeys=i.slice(1,-2))}if(Ko.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Go.compile([].concat(zo+t.m,t.pubkeys,zo+n.n,Vo.OP_CHECKMULTISIG))})),Ko.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Ko.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Ko.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Ko.prop(n,"signatures",(()=>{if(t.input)return Go.decompile(t.input).slice(1)})),Ko.prop(n,"input",(()=>{if(t.signatures)return Go.compile([Vo.OP_0].concat(t.signatures))})),Ko.prop(n,"witness",(()=>{if(n.input)return[]})),Ko.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Wo.Number(i[0]))throw new TypeError("Output is invalid");if(!Wo.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Vo.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>$o.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!Xo(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Vo.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!Xo(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0});const Jo=ao,Qo=co,Zo=Co,ts=Hi,es=Qo.OPS,rs=F.exports;Yo.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ts({network:ts.maybe(ts.Object),output:ts.maybe(ts.Buffer),pubkey:ts.maybe(rs.isPoint),signature:ts.maybe(Qo.isCanonicalScriptSignature),input:ts.maybe(ts.Buffer)},t);const r=Zo.value((()=>Qo.decompile(t.input))),n={name:"p2pk",network:t.network||Jo.bitcoin};if(Zo.prop(n,"output",(()=>{if(t.pubkey)return Qo.compile([t.pubkey,es.OP_CHECKSIG])})),Zo.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Zo.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Zo.prop(n,"input",(()=>{if(t.signature)return Qo.compile([t.signature])})),Zo.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==es.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!rs.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Qo.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var ns={},is={};Object.defineProperty(is,"__esModule",{value:!0});const os=v;function ss(t){try{return os("rmd160").update(t).digest()}catch(e){return os("ripemd160").update(t).digest()}}function us(t){return os("sha256").update(t).digest()}is.ripemd160=ss,is.sha1=function(t){return os("sha1").update(t).digest()},is.sha256=us,is.hash160=function(t){return ss(us(t))},is.hash256=function(t){return us(us(t))},Object.defineProperty(ns,"__esModule",{value:!0});const as=is,hs=ao,fs=co,cs=Co,ls=Hi,ps=fs.OPS,ds=F.exports,ys=O;ns.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ls({network:ls.maybe(ls.Object),address:ls.maybe(ls.String),hash:ls.maybe(ls.BufferN(20)),output:ls.maybe(ls.BufferN(25)),pubkey:ls.maybe(ds.isPoint),signature:ls.maybe(fs.isCanonicalScriptSignature),input:ls.maybe(ls.Buffer)},t);const r=cs.value((()=>{const e=ys.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=cs.value((()=>fs.decompile(t.input))),i=t.network||hs.bitcoin,o={name:"p2pkh",network:i};if(cs.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),ys.encode(t)})),cs.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?as.hash160(t.pubkey||o.pubkey):void 0)),cs.prop(o,"output",(()=>{if(o.hash)return fs.compile([ps.OP_DUP,ps.OP_HASH160,o.hash,ps.OP_EQUALVERIFY,ps.OP_CHECKSIG])})),cs.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),cs.prop(o,"signature",(()=>{if(t.input)return n()[0]})),cs.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return fs.compile([t.signature,t.pubkey])})),cs.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==ps.OP_DUP||t.output[1]!==ps.OP_HASH160||20!==t.output[2]||t.output[23]!==ps.OP_EQUALVERIFY||t.output[24]!==ps.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=as.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!fs.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ds.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=as.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var gs={};Object.defineProperty(gs,"__esModule",{value:!0});const vs=is,ms=ao,ws=co,bs=Co,Es=Hi,_s=ws.OPS,Ss=O;gs.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Es({network:Es.maybe(Es.Object),address:Es.maybe(Es.String),hash:Es.maybe(Es.BufferN(20)),output:Es.maybe(Es.BufferN(23)),redeem:Es.maybe({network:Es.maybe(Es.Object),output:Es.maybe(Es.Buffer),input:Es.maybe(Es.Buffer),witness:Es.maybe(Es.arrayOf(Es.Buffer))}),input:Es.maybe(Es.Buffer),witness:Es.maybe(Es.arrayOf(Es.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||ms.bitcoin);const n={network:r},i=bs.value((()=>{const e=Ss.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=bs.value((()=>ws.decompile(t.input))),s=bs.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:ws.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(bs.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),Ss.encode(t)})),bs.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?vs.hash160(n.redeem.output):void 0)),bs.prop(n,"output",(()=>{if(n.hash)return ws.compile([_s.OP_HASH160,n.hash,_s.OP_EQUAL])})),bs.prop(n,"redeem",(()=>{if(t.input)return s()})),bs.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return ws.compile([].concat(ws.decompile(t.redeem.input),t.redeem.output))})),bs.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),bs.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==_s.OP_HASH160||20!==t.output[1]||t.output[22]!==_s.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=ws.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=vs.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=ws.decompile(t.input);if(!ws.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var Is={},Ts="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Os={},Ps=0;Ps>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Ms(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=As(e)^n>>5}for(e=As(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Ms(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Ns(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Ms(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=As(n)^s,i+=Ts.charAt(s)}for(o=0;o<6;++o)n=As(n);for(n^=1,o=0;o<6;++o){i+=Ts.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Ns(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Ns(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Ns(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Ns(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(Is,"__esModule",{value:!0});const Bs=is,Cs=ao,Us=co,Ls=Co,Ds=Hi,Hs=Us.OPS,Fs=F.exports,qs=Rs,js=Buffer.alloc(0);Is.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ds({address:Ds.maybe(Ds.String),hash:Ds.maybe(Ds.BufferN(20)),input:Ds.maybe(Ds.BufferN(0)),network:Ds.maybe(Ds.Object),output:Ds.maybe(Ds.BufferN(22)),pubkey:Ds.maybe(Fs.isPoint),signature:Ds.maybe(Us.isCanonicalScriptSignature),witness:Ds.maybe(Ds.arrayOf(Ds.Buffer))},t);const r=Ls.value((()=>{const e=qs.decode(t.address),r=e.words.shift(),n=qs.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Cs.bitcoin,i={name:"p2wpkh",network:n};if(Ls.prop(i,"address",(()=>{if(!i.hash)return;const t=qs.toWords(i.hash);return t.unshift(0),qs.encode(n.bech32,t)})),Ls.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Bs.hash160(t.pubkey||i.pubkey):void 0)),Ls.prop(i,"output",(()=>{if(i.hash)return Us.compile([Hs.OP_0,i.hash])})),Ls.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),Ls.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),Ls.prop(i,"input",(()=>{if(i.witness)return js})),Ls.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Hs.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Bs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!Fs.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Us.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!Fs.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Bs.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});const Ks=is,Vs=ao,Ws=co,$s=Co,zs=Hi,Xs=Ws.OPS,Ys=F.exports,Js=Rs,Qs=Buffer.alloc(0);function Zs(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Ys.isPoint(t))}Gs.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),zs({network:zs.maybe(zs.Object),address:zs.maybe(zs.String),hash:zs.maybe(zs.BufferN(32)),output:zs.maybe(zs.BufferN(34)),redeem:zs.maybe({input:zs.maybe(zs.Buffer),network:zs.maybe(zs.Object),output:zs.maybe(zs.Buffer),witness:zs.maybe(zs.arrayOf(zs.Buffer))}),input:zs.maybe(zs.BufferN(0)),witness:zs.maybe(zs.arrayOf(zs.Buffer))},t);const r=$s.value((()=>{const e=Js.decode(t.address),r=e.words.shift(),n=Js.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=$s.value((()=>Ws.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Vs.bitcoin);const o={network:i};if($s.prop(o,"address",(()=>{if(!o.hash)return;const t=Js.toWords(o.hash);return t.unshift(0),Js.encode(i.bech32,t)})),$s.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Ks.sha256(o.redeem.output):void 0)),$s.prop(o,"output",(()=>{if(o.hash)return Ws.compile([Xs.OP_0,o.hash])})),$s.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Qs,witness:t.witness.slice(0,-1)}})),$s.prop(o,"input",(()=>{if(o.witness)return Qs})),$s.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Ws.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Qs,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),$s.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==Xs.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Ws.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Ks.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Ws.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Zs)||t.redeem.output&&(Ws.decompile(t.redeem.output)||[]).some(Zs))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Zs)||(Ws.decompile(e)||[]).some(Zs))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(ho,"__esModule",{value:!0});const tu=fo;ho.embed=tu.p2data;const eu=qo;ho.p2ms=eu.p2ms;const ru=Yo;ho.p2pk=ru.p2pk;const nu=ns;ho.p2pkh=nu.p2pkh;const iu=gs;ho.p2sh=iu.p2sh;const ou=Is;ho.p2wpkh=ou.p2wpkh;const su=Gs;ho.p2wsh=su.p2wsh,Object.defineProperty(uo,"__esModule",{value:!0});const uu=ao,au=ho,hu=co,fu=yo,cu=Rs,lu=O,pu=Hi;function du(t){const e=lu.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function yu(t){const e=cu.decode(t),r=cu.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}uo.fromBase58Check=du,uo.fromBech32=yu,uo.toBase58Check=function(t,e){pu(fu.tuple(fu.Hash160bit,fu.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),lu.encode(r)},uo.toBech32=function(t,e,r){const n=cu.toWords(t);return n.unshift(e),cu.encode(r,n)},uo.fromOutputScript=function(t,e){e=e||uu.bitcoin;try{return au.p2pkh({output:t,network:e}).address}catch(t){}try{return au.p2sh({output:t,network:e}).address}catch(t){}try{return au.p2wpkh({output:t,network:e}).address}catch(t){}try{return au.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(hu.toASM(t)+" has no matching Address")},uo.toOutputScript=function(t,e){let r,n;e=e||uu.bitcoin;try{r=du(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return au.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return au.p2sh({hash:r.hash}).output}else{try{n=yu(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return au.p2wpkh({hash:n.data}).output;if(32===n.data.length)return au.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var gu={},vu=a.default.randomBytes;Object.defineProperty(gu,"__esModule",{value:!0});const mu=ao,wu=yo,bu=F.exports,Eu=vu,_u=Hi,Su=Gi,Iu=_u.maybe(_u.compile({compressed:wu.maybe(wu.Boolean),network:wu.maybe(wu.Network)}));class Tu{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||mu.bitcoin,void 0!==e&&(this.__Q=bu.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=bu.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return Su.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return bu.sign(t,this.__D);{let e=bu.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=bu.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return bu.verify(t,this.publicKey,e)}}function Ou(t,e){if(_u(wu.Buffer256bit,t),!bu.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return _u(Iu,e),new Tu(t,void 0,e)}gu.fromPrivateKey=Ou,gu.fromPublicKey=function(t,e){return _u(bu.isPoint,t),_u(Iu,e),new Tu(void 0,t,e)},gu.fromWIF=function(t,e){const r=Su.decode(t),n=r.version;if(wu.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||mu.bitcoin,n!==e.wif)throw new Error("Invalid network version");return Ou(r.privateKey,{compressed:r.compressed,network:e})},gu.makeRandom=function(t){_u(Iu,t),void 0===t&&(t={});const e=t.rng||Eu;let r;do{r=e(32),_u(wu.Buffer256bit,r)}while(!bu.isPrivate(r));return Ou(r,t)};var Pu={},ku={},Au=m.exports.Buffer;function Mu(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function xu(t){return Mu(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Nu={encode:function t(e,r,n){if(Mu(e),r||(r=Au.allocUnsafe(xu(e))),!Au.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Au.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Mu(o),o},encodingLength:xu};Object.defineProperty(ku,"__esModule",{value:!0});const Ru=yo,Bu=Hi,Cu=Nu;function Uu(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function Lu(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Uu(n+r,9007199254740991),n+r}function Du(t,e,r){return Uu(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}ku.readUInt64LE=Lu,ku.writeUInt64LE=Du,ku.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};ku.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Bu(Ru.tuple(Ru.Buffer,Ru.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Lu(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Cu.decode(this.buffer,this.offset);return this.offset+=Cu.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Wu.encodingLength(this.ins.length)+Wu.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+$u(e.script)),0)+this.outs.reduce(((t,e)=>t+8+$u(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Wu.encodingLength(e)+t.reduce(((t,e)=>t+$u(e)),0)}(e.witness)),0):0)}clone(){const t=new ta;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Vu(Ku.tuple(Ku.UInt32,Ku.Buffer,Ku.Number),arguments),t>=this.ins.length)return Ju;const n=ju.compile(ju.decompile(e).filter((t=>t!==Gu.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===ta.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===ta.SIGHASH_SINGLE){if(t>=this.outs.length)return Ju;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&ta.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=zu})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),qu.hash256(o)}hashForWitnessV0(t,e,r,n){Vu(Ku.tuple(Ku.UInt32,Ku.Buffer,Ku.Satoshi,Ku.UInt32),arguments);let i,o=Buffer.from([]),s=Yu,u=Yu,a=Yu;if(n&ta.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new Fu.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=qu.hash256(o)),n&ta.SIGHASH_ANYONECANPAY||(31&n)===ta.SIGHASH_SINGLE||(31&n)===ta.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new Fu.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=qu.hash256(o)),(31&n)!==ta.SIGHASH_SINGLE&&(31&n)!==ta.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+$u(e.script)),0);o=Buffer.allocUnsafe(t),i=new Fu.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=qu.hash256(o)}else if((31&n)===ta.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}ta.DEFAULT_SEQUENCE=4294967295,ta.SIGHASH_ALL=1,ta.SIGHASH_NONE=2,ta.SIGHASH_SINGLE=3,ta.SIGHASH_ANYONECANPAY=128,ta.ADVANCED_TRANSACTION_MARKER=0,ta.ADVANCED_TRANSACTION_FLAG=1,Hu.Transaction=ta;Object.defineProperty(Pu,"__esModule",{value:!0});const ea=ku,ra=is,na=Hu,ia=yo,oa=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=na.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(sa([{getHash:ia.Function}],t),0===t.length)throw aa;if(e&&!ca(t))throw ha;const r=t.map((t=>t.getHash(e))),n=oa(r,ra.hash256);return e?ra.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ca(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+ua.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return ra.hash256(this.toBuffer(!0))}getId(){return ea.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new ea.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(ua.encode(this.transactions.length,e,r.offset),r.offset+=ua.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=ea.reverseBuffer(this.getHash()),e=fa.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw aa;const t=fa.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw aa;if(!this.hasWitnessCommit())throw ha;const t=fa.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ca(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}Pu.Block=fa;var la={},pa={},da={},ya={},ga={},va={},ma={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(ma);var wa={};Object.defineProperty(wa,"__esModule",{value:!0});const ba=ma;wa.decode=function(t){if(t.key[0]!==ba.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},wa.encode=function(t){const e=Buffer.from([ba.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},wa.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",wa.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},wa.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});const _a=ma;Ea.encode=function(t){return{key:Buffer.from([_a.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var Sa={};Object.defineProperty(Sa,"__esModule",{value:!0});const Ia=ma;Sa.decode=function(t){if(t.key[0]!==Ia.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},Sa.encode=function(t){return{key:Buffer.from([Ia.InputTypes.FINAL_SCRIPTSIG]),value:t}},Sa.expected="Buffer",Sa.check=function(t){return Buffer.isBuffer(t)},Sa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var Ta={};Object.defineProperty(Ta,"__esModule",{value:!0});const Oa=ma;Ta.decode=function(t){if(t.key[0]!==Oa.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},Ta.encode=function(t){return{key:Buffer.from([Oa.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},Ta.expected="Buffer",Ta.check=function(t){return Buffer.isBuffer(t)},Ta.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var Pa={};Object.defineProperty(Pa,"__esModule",{value:!0});const ka=ma;Pa.decode=function(t){if(t.key[0]!==ka.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},Pa.encode=function(t){return{key:Buffer.from([ka.InputTypes.NON_WITNESS_UTXO]),value:t}},Pa.expected="Buffer",Pa.check=function(t){return Buffer.isBuffer(t)},Pa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Aa={};Object.defineProperty(Aa,"__esModule",{value:!0});const Ma=ma;Aa.decode=function(t){if(t.key[0]!==Ma.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Aa.encode=function(t){const e=Buffer.from([Ma.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},Aa.expected="{ pubkey: Buffer; signature: Buffer; }",Aa.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Aa.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var xa={};Object.defineProperty(xa,"__esModule",{value:!0});const Na=ma;xa.decode=function(t){if(t.key[0]!==Na.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},xa.encode=function(t){return{key:Buffer.from([Na.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},xa.expected="string",xa.check=function(t){return"string"==typeof t},xa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0});const Ba=ma;Ra.decode=function(t){if(t.key[0]!==Ba.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ra.encode=function(t){const e=Buffer.from([Ba.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ra.expected="number",Ra.check=function(t){return"number"==typeof t},Ra.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ca={},Ua={},La={};Object.defineProperty(La,"__esModule",{value:!0});function Da(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Ha(t){return Da(t),t<253?1:t<=65535?3:t<=4294967295?5:9}La.encode=function t(e,r,n){if(Da(e),r||(r=Buffer.allocUnsafe(Ha(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},La.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Da(i),i}},La.encodingLength=Ha,Object.defineProperty(Ua,"__esModule",{value:!0});const Fa=La;function qa(t){const e=t.key.length,r=t.value.length,n=Fa.encodingLength(e),i=Fa.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return Fa.encode(e,o,0),t.key.copy(o,n),Fa.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function ja(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ua.range=t=>[...Array(t).keys()],Ua.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var $a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var za={};Object.defineProperty(za,"__esModule",{value:!0}),za.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(va,"__esModule",{value:!0});const Ya=ma,Ja=Sa,Qa=Ta,Za=Pa,th=Aa,eh=xa,rh=Ra,nh=Ca,ih=Wa,oh=$a,sh=za,uh=Xa,ah={unsignedTx:Ea,globalXpub:wa,checkPubkey:oh.makeChecker([])};va.globals=ah;const hh={nonWitnessUtxo:Za,partialSig:th,sighashType:rh,finalScriptSig:Ja,finalScriptWitness:Qa,porCommitment:eh,witnessUtxo:nh,bip32Derivation:ih.makeConverter(Ya.InputTypes.BIP32_DERIVATION),redeemScript:sh.makeConverter(Ya.InputTypes.REDEEM_SCRIPT),witnessScript:uh.makeConverter(Ya.InputTypes.WITNESS_SCRIPT),checkPubkey:oh.makeChecker([Ya.InputTypes.PARTIAL_SIG,Ya.InputTypes.BIP32_DERIVATION])};va.inputs=hh;const fh={bip32Derivation:ih.makeConverter(Ya.OutputTypes.BIP32_DERIVATION),redeemScript:sh.makeConverter(Ya.OutputTypes.REDEEM_SCRIPT),witnessScript:uh.makeConverter(Ya.OutputTypes.WITNESS_SCRIPT),checkPubkey:oh.makeChecker([Ya.OutputTypes.BIP32_DERIVATION])};va.outputs=fh,Object.defineProperty(ga,"__esModule",{value:!0});const ch=va,lh=Ua,ph=La,dh=ma;function yh(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function gh(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case dh.GlobalTypes.UNSIGNED_TX:if(yh("global",t.key,dh.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case dh.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(ch.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of lh.range(s)){const e={};for(const n of r[t])switch(ch.inputs.checkPubkey(n),n.key[0]){case dh.InputTypes.NON_WITNESS_UTXO:if(yh("input",n.key,dh.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=ch.inputs.nonWitnessUtxo.decode(n);break;case dh.InputTypes.WITNESS_UTXO:if(yh("input",n.key,dh.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=ch.inputs.witnessUtxo.decode(n);break;case dh.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(ch.inputs.partialSig.decode(n));break;case dh.InputTypes.SIGHASH_TYPE:if(yh("input",n.key,dh.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=ch.inputs.sighashType.decode(n);break;case dh.InputTypes.REDEEM_SCRIPT:if(yh("input",n.key,dh.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=ch.inputs.redeemScript.decode(n);break;case dh.InputTypes.WITNESS_SCRIPT:if(yh("input",n.key,dh.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=ch.inputs.witnessScript.decode(n);break;case dh.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(ch.inputs.bip32Derivation.decode(n));break;case dh.InputTypes.FINAL_SCRIPTSIG:yh("input",n.key,dh.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=ch.inputs.finalScriptSig.decode(n);break;case dh.InputTypes.FINAL_SCRIPTWITNESS:yh("input",n.key,dh.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=ch.inputs.finalScriptWitness.decode(n);break;case dh.InputTypes.POR_COMMITMENT:yh("input",n.key,dh.InputTypes.POR_COMMITMENT),e.porCommitment=ch.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of lh.range(u)){const e={};for(const r of n[t])switch(ch.outputs.checkPubkey(r),r.key[0]){case dh.OutputTypes.REDEEM_SCRIPT:if(yh("output",r.key,dh.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=ch.outputs.redeemScript.decode(r);break;case dh.OutputTypes.WITNESS_SCRIPT:if(yh("output",r.key,dh.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=ch.outputs.witnessScript.decode(r);break;case dh.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(ch.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}ga.psbtFromBuffer=function(t,e){let r=0;function n(){const e=ph.decode(t,r);r+=ph.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===dh.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of lh.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of lh.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return gh(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},ga.checkKeyBuffer=yh,ga.psbtFromKeyVals=gh;var vh={};Object.defineProperty(vh,"__esModule",{value:!0});const mh=va,wh=Ua;vh.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=_h({globalMap:t,inputs:e,outputs:r}),s=wh.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(wh.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const bh=(t,e)=>t.key.compare(e.key);function Eh(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(bh)}function _h({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:Eh(t,mh.globals),inputKeyVals:e.map((t=>Eh(t,mh.inputs))),outputKeyVals:r.map((t=>Eh(t,mh.outputs)))}}vh.psbtToKeyVals=_h,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(ga),e(vh)}(ya),Object.defineProperty(da,"__esModule",{value:!0});const Sh=ya;function Ih(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function Th(t){return t.globalMap.unsignedTx}function Oh(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}da.combine=function(t){const e=t[0],r=Sh.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=Th(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=Oh(r.globalKeyVals),s=r.inputKeyVals.map(Oh),u=r.outputKeyVals.map(Oh);for(const t of n){const e=Th(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=Sh.psbtToKeyVals(t);Oh(n.globalKeyVals).forEach(Ih(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(Oh).forEach(((t,e)=>t.forEach(Ih(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(Oh).forEach(((t,e)=>t.forEach(Ih(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return Sh.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var Ph={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=va;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(Ph),Object.defineProperty(pa,"__esModule",{value:!0});const kh=da,Ah=ya,Mh=ma,xh=Ph;pa.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ah.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ah.psbtToBuffer(this)}updateGlobal(t){return xh.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=xh.checkForInput(this.inputs,t);return xh.updateInput(e,r),this}updateOutput(t,e){const r=xh.checkForOutput(this.outputs,t);return xh.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return xh.checkHasKey(t,this.globalMap.unknownKeyVals,xh.getEnumLength(Mh.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=xh.checkForInput(this.inputs,t);return xh.checkHasKey(e,r.unknownKeyVals,xh.getEnumLength(Mh.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=xh.checkForOutput(this.outputs,t);return xh.checkHasKey(e,r.unknownKeyVals,xh.getEnumLength(Mh.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),xh.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),xh.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=xh.checkForInput(this.inputs,t);xh.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=kh.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(la,"__esModule",{value:!0});const Nh=pa,Rh=La,Bh=Ph,Ch=uo,Uh=ku,Lh=is,Dh=gu,Hh=ho,Fh=co,qh=Hu,jh={network:ao.bitcoin,maximumFeeRate:5e3};class Gh{constructor(t={},e=new Nh.Psbt(new Vh)){this.data=e,this.opts=Object.assign({},jh,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=Nh.Psbt.fromBuffer(t,Kh),n=new Gh(e,r);return function(t,e){t.ins.forEach((t=>{uf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:Uh.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Ch.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:Uh.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Gh.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){nf(t),this.opts.maximumFeeRate=t}setVersion(t){nf(t),of(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){nf(t),of(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){nf(e),of(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");of(this.data.inputs,"addInput"),t.witnessScript&&If(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);uf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&mf(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");of(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Ch.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(zh))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return wf(this.data.inputs,r,e,!0),r}getFeeRate(){return cf("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return cf("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Bh.checkForInput(this.data.inputs,0),Pf(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=lf){const r=Bh.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=bf(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Zh(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Fh.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Bh.checkForInput(this.data.inputs,t),r=Sf(Ef(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Fh.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||_f(r)||(n=r,Fh.isCanonicalScriptSignature(n)))return;var n;if(!Fh.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=gf(t),r=e[e.length-1];if(_f(r))return;if(!Fh.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+Of(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=Ef(r,e,n),{meaningfulScript:o}=Sf(i,r,"input",e.redeemScript,e.witnessScript);return Tf(t,o)}(e,Bh.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Bh.checkForInput(this.data.inputs,t),n=rf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=Sf(i,r,"output",e.redeemScript,e.witnessScript);return Tf(t,o)}(e,Bh.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Bh.checkForOutput(this.data.outputs,t),n=rf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Bh.checkForInput(this.data.inputs,0);return Pf(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Fh.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?df(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,sf(e.pubkey,h,"verify");const f=Dh.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[qh.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of Pf(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[qh.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of Pf(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[qh.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return yf(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[qh.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=yf(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[qh.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of Pf(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[qh.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[qh.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=pf(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Fh.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[qh.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=pf(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Fh.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Wh(this.__CACHE),this.data.toBuffer()}toHex(){return Wh(this.__CACHE),this.data.toHex()}toBase64(){return Wh(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&If(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&mf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}la.Psbt=Gh;const Kh=t=>new Vh(t);class Vh{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=qh.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?Uh.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Wh(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function $h(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Dh.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function zh(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Xh(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Yh=Xh(Hh.p2ms),Jh=Xh(Hh.p2pk),Qh=Xh(Hh.p2pkh),Zh=Xh(Hh.p2wpkh),tf=Xh(Hh.p2wsh),ef=Xh(Hh.p2sh);function rf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function nf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function of(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Fh.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Fh.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Fh.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Fh.signature.decode(t.signature),i=[];n&qh.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case qh.Transaction.SIGHASH_ALL:break;case qh.Transaction.SIGHASH_SINGLE:case qh.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function sf(t,e,r){if(!Tf(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function uf(t,e){const r=Uh.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function af(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const hf=af(Hh.p2sh,"Redeem script"),ff=af(Hh.p2wsh,"Witness script");function cf(t,e,r,n){if(!r.every(zh))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),wf(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function lf(t,e,r,n,i,o){const s=Of(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return $h(1,t.partialSig);case"multisig":const r=Hh.p2ms({output:e});return $h(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return Hh.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=Hh.p2ms({output:t,signatures:e});break;case"pubkey":n=Hh.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=Hh.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=Hh.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?Hh.p2wsh({redeem:a}):null,f=i?Hh.p2sh({redeem:h||a}):null;n?(u=vf(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function pf(t,e,r,n,i){const o=Bh.checkForInput(t,e),{hash:s,sighashType:u,script:a}=df(e,o,n,!1,i);return sf(r,a,"sign"),{hash:s,sighashType:u}}function df(t,e,r,n,i){const o=r.__TX,s=e.sighashType||qh.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&qh.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case qh.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case qh.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case qh.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=bf(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=Sf(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Zh(h)){const e=Hh.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function yf(t,e,r){const n=Bh.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function gf(t){let e=0;function r(){const r=Rh.decode(t,e);return e+=Rh.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=gf(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=bf(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function bf(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||mf(t,e,r),n[r]}function Ef(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return bf(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function _f(t){return 33===t.length&&Fh.isCanonicalPubKey(t)}function Sf(t,e,r,n,i){const o=ef(t),s=o&&n&&tf(n),u=tf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,hf(e,t,n,r),ff(e,n,i,r),If(a)):u?(a=i,ff(e,t,i,r),If(a)):o?(a=n,hf(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function If(t){if(Zh(t)||ef(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Tf(t,e){const r=Lh.hash160(t),n=Fh.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function Of(t){return Zh(t)?"witnesspubkeyhash":Qh(t)?"pubkeyhash":Yh(t)?"multisig":Jh(t)?"pubkey":"nonstandard"}function Pf(t){return[...Array(t).keys()]}var kf={},Af={},Mf={},xf={};Object.defineProperty(xf,"__esModule",{value:!0});const Nf=co,Rf=co;function Bf(t){return t===Rf.OPS.OP_0||Nf.isCanonicalScriptSignature(t)}function Cf(t,e){const r=Nf.decompile(t);return!(r.length<2)&&(r[0]===Rf.OPS.OP_0&&(e?r.slice(1).every(Bf):r.slice(1).every(Nf.isCanonicalScriptSignature)))}xf.check=Cf,Cf.toJSON=()=>"multisig input";var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0});const Lf=co,Df=co,Hf=yo,Ff=Df.OPS.OP_RESERVED;function qf(t,e){const r=Lf.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Df.OPS.OP_CHECKMULTISIG)return!1;if(!Hf.Number(r[0]))return!1;if(!Hf.Number(r[r.length-2]))return!1;const n=r[0]-Ff,i=r[r.length-2]-Ff;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(Lf.isCanonicalPubKey)}Uf.check=qf,qf.toJSON=()=>"multi-sig output",Object.defineProperty(Mf,"__esModule",{value:!0});const jf=xf;Mf.input=jf;const Gf=Uf;Mf.output=Gf;var Kf={};Object.defineProperty(Kf,"__esModule",{value:!0});const Vf=co,Wf=Vf.OPS;function $f(t){const e=Vf.compile(t);return e.length>1&&e[0]===Wf.OP_RETURN}Kf.check=$f,$f.toJSON=()=>"null data output";const zf={check:$f};Kf.output=zf;var Xf={},Yf={};Object.defineProperty(Yf,"__esModule",{value:!0});const Jf=co;function Qf(t){const e=Jf.decompile(t);return 1===e.length&&Jf.isCanonicalScriptSignature(e[0])}Yf.check=Qf,Qf.toJSON=()=>"pubKey input";var Zf={};Object.defineProperty(Zf,"__esModule",{value:!0});const tc=co,ec=co;function rc(t){const e=tc.decompile(t);return 2===e.length&&tc.isCanonicalPubKey(e[0])&&e[1]===ec.OPS.OP_CHECKSIG}Zf.check=rc,rc.toJSON=()=>"pubKey output",Object.defineProperty(Xf,"__esModule",{value:!0});const nc=Yf;Xf.input=nc;const ic=Zf;Xf.output=ic;var oc={},sc={};Object.defineProperty(sc,"__esModule",{value:!0});const uc=co;function ac(t){const e=uc.decompile(t);return 2===e.length&&uc.isCanonicalScriptSignature(e[0])&&uc.isCanonicalPubKey(e[1])}sc.check=ac,ac.toJSON=()=>"pubKeyHash input";var hc={};Object.defineProperty(hc,"__esModule",{value:!0});const fc=co,cc=co;function lc(t){const e=fc.compile(t);return 25===e.length&&e[0]===cc.OPS.OP_DUP&&e[1]===cc.OPS.OP_HASH160&&20===e[2]&&e[23]===cc.OPS.OP_EQUALVERIFY&&e[24]===cc.OPS.OP_CHECKSIG}hc.check=lc,lc.toJSON=()=>"pubKeyHash output",Object.defineProperty(oc,"__esModule",{value:!0});const pc=sc;oc.input=pc;const dc=hc;oc.output=dc;var yc={},gc={},vc={};Object.defineProperty(vc,"__esModule",{value:!0});const mc=co,wc=co;function bc(t){const e=mc.compile(t);return 22===e.length&&e[0]===wc.OPS.OP_0&&20===e[1]}vc.check=bc,bc.toJSON=()=>"Witness pubKeyHash output";var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});const _c=co,Sc=co;function Ic(t){const e=_c.compile(t);return 34===e.length&&e[0]===Sc.OPS.OP_0&&32===e[1]}Ec.check=Ic,Ic.toJSON=()=>"Witness scriptHash output",Object.defineProperty(gc,"__esModule",{value:!0});const Tc=co,Oc=Mf,Pc=Xf,kc=oc,Ac=vc,Mc=Ec;function xc(t,e){const r=Tc.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=Tc.decompile(Tc.compile(r.slice(0,-1))),o=Tc.decompile(n);return!!o&&(!!Tc.isPushOnly(i)&&(1===r.length?Mc.check(o)||Ac.check(o):!(!kc.input.check(i)||!kc.output.check(o))||(!(!Oc.input.check(i,e)||!Oc.output.check(o))||!(!Pc.input.check(i)||!Pc.output.check(o)))))}gc.check=xc,xc.toJSON=()=>"scriptHash input";var Nc={};Object.defineProperty(Nc,"__esModule",{value:!0});const Rc=co,Bc=co;function Cc(t){const e=Rc.compile(t);return 23===e.length&&e[0]===Bc.OPS.OP_HASH160&&20===e[1]&&e[22]===Bc.OPS.OP_EQUAL}Nc.check=Cc,Cc.toJSON=()=>"scriptHash output",Object.defineProperty(yc,"__esModule",{value:!0});const Uc=gc;yc.input=Uc;const Lc=Nc;yc.output=Lc;var Dc={},Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});const Fc=co,qc=co,jc=yo,Gc=Hi,Kc=Buffer.from("aa21a9ed","hex");function Vc(t){const e=Fc.compile(t);return e.length>37&&e[0]===qc.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Kc)}Hc.check=Vc,Vc.toJSON=()=>"Witness commitment output",Hc.encode=function(t){Gc(jc.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Kc.copy(e,0),t.copy(e,4),Fc.compile([qc.OPS.OP_RETURN,e])},Hc.decode=function(t){return Gc(Vc,t),Fc.decompile(t)[1].slice(4,36)},Object.defineProperty(Dc,"__esModule",{value:!0});const Wc=Hc;Dc.output=Wc;var $c={},zc={};Object.defineProperty(zc,"__esModule",{value:!0});const Xc=co;function Yc(t){const e=Xc.decompile(t);return 2===e.length&&Xc.isCanonicalScriptSignature(e[0])&&function(t){return Xc.isCanonicalPubKey(t)&&33===t.length}(e[1])}zc.check=Yc,Yc.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty($c,"__esModule",{value:!0});const Jc=zc;$c.input=Jc;const Qc=vc;$c.output=Qc;var Zc={},tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=co,rl=Hi,nl=Mf,il=Xf,ol=oc;function sl(t,e){if(rl(rl.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=el.decompile(r);if(!n||0===n.length)return!1;const i=el.compile(t.slice(0,-1));return!(!ol.input.check(i)||!ol.output.check(n))||(!(!nl.input.check(i,e)||!nl.output.check(n))||!(!il.input.check(i)||!il.output.check(n)))}tl.check=sl,sl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Zc,"__esModule",{value:!0});const ul=tl;Zc.input=ul;const al=Ec;Zc.output=al,Object.defineProperty(Af,"__esModule",{value:!0});const hl=co,fl=Mf,cl=Kf,ll=Xf,pl=oc,dl=yc,yl=Dc,gl=$c,vl=Zc,ml={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Af.types=ml,Af.output=function(t){if(gl.output.check(t))return ml.P2WPKH;if(vl.output.check(t))return ml.P2WSH;if(pl.output.check(t))return ml.P2PKH;if(dl.output.check(t))return ml.P2SH;const e=hl.decompile(t);if(!e)throw new TypeError("Invalid script");return fl.output.check(e)?ml.P2MS:ll.output.check(e)?ml.P2PK:yl.output.check(e)?ml.WITNESS_COMMITMENT:cl.output.check(e)?ml.NULLDATA:ml.NONSTANDARD},Af.input=function(t,e){const r=hl.decompile(t);if(!r)throw new TypeError("Invalid script");return pl.input.check(r)?ml.P2PKH:dl.input.check(r,e)?ml.P2SH:fl.input.check(r,e)?ml.P2MS:ll.input.check(r)?ml.P2PK:ml.NONSTANDARD},Af.witness=function(t,e){const r=hl.decompile(t);if(!r)throw new TypeError("Invalid script");return gl.input.check(r)?ml.P2WPKH:vl.input.check(r,e)?ml.P2WSH:ml.NONSTANDARD},Object.defineProperty(kf,"__esModule",{value:!0});const wl=uo,bl=ku,El=Af,_l=is,Sl=gu,Il=ao,Tl=ho,Ol=co,Pl=co,kl=Hu,Al=yo,Ml=Hi,xl=El.types,Nl=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Rl(t,e,r){try{Ml(t,e)}catch(t){throw new Error(r)}}class Bl{constructor(t=Il.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new kl.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Bl(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==xl.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=Sl.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=Ol.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ml(Ml.maybe(Ml.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ml(Al.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ml(Al.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=bl.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof kl.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=wl.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=Ol.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Nl.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Rl(Ml.Number,e.vin,"sign must include vin parameter as Number (input index)"),Rl(Al.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Rl(Ml.maybe(Ml.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.Buffer,e.witnessScript,`${n} requires witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.Buffer,e.witnessScript,`${n} requires witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires witnessScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||kl.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Dl(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ml(Al.Satoshi,a),l.value=a}if(!Dl(l)){const t=function(t,e,r,n){if(r&&n){const i=Tl.p2wsh({redeem:{output:n}}),o=Tl.p2wsh({output:r}),s=Tl.p2sh({redeem:{output:r}}),u=Tl.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ul(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+Ol.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===xl.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:xl.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:xl.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=Tl.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=Tl.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ul(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+Ol.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===xl.P2WPKH&&(o=Tl.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:xl.P2SH,prevOutScript:n.output,hasWitness:i.type===xl.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=Tl.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=Tl.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ul(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+Ol.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===xl.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:xl.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===xl.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===xl.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ul(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+Ol.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===xl.P2WPKH&&(n=Tl.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===xl.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=Tl.p2pkh({pubkey:e}).output;return{prevOutType:xl.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:xl.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Dl(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(kl.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Cl(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ul(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||El.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=Ll(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===xl.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Hl(t)&kl.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===kl.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Hl(t)&kl.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Hl(r);return n===kl.Transaction.SIGHASH_NONE||n===kl.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Cl(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=El.input(t,!0),i=El.witness(e,!0);n===xl.NONSTANDARD&&(n=void 0),i===xl.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case xl.P2WPKH:{const{output:t,pubkey:r,signature:n}=Tl.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:xl.P2WPKH,pubkeys:[r],signatures:[n]}}case xl.P2PKH:{const{output:e,pubkey:r,signature:n}=Tl.p2pkh({input:t});return{prevOutScript:e,prevOutType:xl.P2PKH,pubkeys:[r],signatures:[n]}}case xl.P2PK:{const{signature:e}=Tl.p2pk({input:t});return{prevOutType:xl.P2PK,pubkeys:[void 0],signatures:[e]}}case xl.P2MS:{const{m:e,pubkeys:r,signatures:i}=Tl.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:xl.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===xl.P2SH){const{output:r,redeem:n}=Tl.p2sh({input:t,witness:e}),i=El.output(n.output),o=Cl(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:xl.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===xl.P2WSH){const{output:r,redeem:n}=Tl.p2wsh({input:t,witness:e}),i=El.output(n.output);let o;return o=i===xl.P2WPKH?Cl(n.input,n.witness,i):Cl(Ol.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:xl.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:xl.NONSTANDARD,prevOutScript:t}}function Ul(t,e){Ml(Al.Buffer,t);const r=El.output(t);switch(r){case xl.P2PKH:{if(!e)return{type:r};const n=Tl.p2pkh({output:t}).hash,i=_l.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case xl.P2WPKH:{if(!e)return{type:r};const n=Tl.p2wpkh({output:t}).hash,i=_l.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case xl.P2PK:return{type:r,pubkeys:[Tl.p2pk({output:t}).pubkey],signatures:[void 0]};case xl.P2MS:{const e=Tl.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function Ll(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case xl.P2PKH:if(0===n.length)break;if(0===i.length)break;return Tl.p2pkh({pubkey:n[0],signature:i[0]});case xl.P2WPKH:if(0===n.length)break;if(0===i.length)break;return Tl.p2wpkh({pubkey:n[0],signature:i[0]});case xl.P2PK:if(0===n.length)break;if(0===i.length)break;return Tl.p2pk({signature:i[0]});case xl.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||Pl.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return Tl.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case xl.P2SH:{const t=Ll(e.redeemScriptType,e,r);if(!t)return;return Tl.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case xl.P2WSH:{const t=Ll(e.witnessScriptType,e,r);if(!t)return;return Tl.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Dl(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Hl(t){return t.readUInt8(t.length-1)}kf.TransactionBuilder=Bl,Object.defineProperty(R,"__esModule",{value:!0});const Fl=B;R.bip32=Fl;const ql=uo;R.address=ql;const jl=is;var Gl=R.crypto=jl;const Kl=gu;R.ECPair=Kl;const Vl=ao;R.networks=Vl;const Wl=ho;R.payments=Wl;const $l=co;R.script=$l;var zl=Pu;R.Block=zl.Block;var Xl=la;R.Psbt=Xl.Psbt;var Yl=co;R.opcodes=Yl.OPS;var Jl=Hu;R.Transaction=Jl.Transaction;var Ql=kf;R.TransactionBuilder=Ql.TransactionBuilder;var Zl={exports:{}};var tp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var ep="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=tp,n=ep,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Zl,Zl.exports);const rp=["includePrerelease","loose","rtl"];var np=t=>t?"object"!=typeof t?{loose:!0}:rp.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const ip=/^[0-9]+$/,op=(t,e)=>{const r=ip.test(t),n=ip.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:top(e,t)};const up=ep,{MAX_LENGTH:ap,MAX_SAFE_INTEGER:hp}=tp,{re:fp,t:cp}=Zl.exports,lp=np,{compareIdentifiers:pp}=sp;class dp{constructor(t,e){if(e=lp(e),t instanceof dp){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>ap)throw new TypeError(`version is longer than ${ap} characters`);up("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?fp[cp.LOOSE]:fp[cp.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>hp||this.major<0)throw new TypeError("Invalid major version");if(this.minor>hp||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>hp||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var yp=dp;const{MAX_LENGTH:gp}=tp,{re:vp,t:mp}=Zl.exports,wp=yp,bp=np;var Ep=(t,e)=>{if(e=bp(e),t instanceof wp)return t;if("string"!=typeof t)return null;if(t.length>gp)return null;if(!(e.loose?vp[mp.LOOSE]:vp[mp.FULL]).test(t))return null;try{return new wp(t,e)}catch(t){return null}};const _p=Ep;var Sp=(t,e)=>{const r=_p(t,e);return r?r.version:null};const Ip=Ep;var Tp=(t,e)=>{const r=Ip(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const Op=yp;var Pp=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new Op(t,r).inc(e,n).version}catch(t){return null}};const kp=yp;var Ap=(t,e,r)=>new kp(t,r).compare(new kp(e,r));const Mp=Ap;var xp=(t,e,r)=>0===Mp(t,e,r);const Np=Ep,Rp=xp;var Bp=(t,e)=>{if(Rp(t,e))return null;{const r=Np(t),n=Np(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Cp=yp;var Up=(t,e)=>new Cp(t,e).major;const Lp=yp;var Dp=(t,e)=>new Lp(t,e).minor;const Hp=yp;var Fp=(t,e)=>new Hp(t,e).patch;const qp=Ep;var jp=(t,e)=>{const r=qp(t,e);return r&&r.prerelease.length?r.prerelease:null};const Gp=Ap;var Kp=(t,e,r)=>Gp(e,t,r);const Vp=Ap;var Wp=(t,e)=>Vp(t,e,!0);const $p=yp;var zp=(t,e,r)=>{const n=new $p(t,r),i=new $p(e,r);return n.compare(i)||n.compareBuild(i)};const Xp=zp;var Yp=(t,e)=>t.sort(((t,r)=>Xp(t,r,e)));const Jp=zp;var Qp=(t,e)=>t.sort(((t,r)=>Jp(r,t,e)));const Zp=Ap;var td=(t,e,r)=>Zp(t,e,r)>0;const ed=Ap;var rd=(t,e,r)=>ed(t,e,r)<0;const nd=Ap;var id=(t,e,r)=>0!==nd(t,e,r);const od=Ap;var sd=(t,e,r)=>od(t,e,r)>=0;const ud=Ap;var ad=(t,e,r)=>ud(t,e,r)<=0;const hd=xp,fd=id,cd=td,ld=sd,pd=rd,dd=ad;var yd=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return hd(t,r,n);case"!=":return fd(t,r,n);case">":return cd(t,r,n);case">=":return ld(t,r,n);case"<":return pd(t,r,n);case"<=":return dd(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const gd=yp,vd=Ep,{re:md,t:wd}=Zl.exports;var bd=(t,e)=>{if(t instanceof gd)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=md[wd.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),md[wd.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;md[wd.COERCERTL].lastIndex=-1}else r=t.match(md[wd.COERCE]);return null===r?null:vd(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},Ed=_d;function _d(t){var e=this;if(e instanceof _d||(e=new _d),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},_d.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},_d.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},_d.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},_d.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new _d;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},_d.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Hd=(t,e,r)=>{const n=t[Ud].get(e);if(n){const e=n.value;if(Fd(t,e)){if(jd(t,n),!t[xd])return}else r&&(t[Ld]&&(n.value.now=Date.now()),t[Cd].unshiftNode(n));return e.value}},Fd=(t,e)=>{if(!e||!e.maxAge&&!t[Nd])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Nd]&&r>t[Nd]},qd=t=>{if(t[Ad]>t[kd])for(let e=t[Cd].tail;t[Ad]>t[kd]&&null!==e;){const r=e.prev;jd(t,e),e=r}},jd=(t,e)=>{if(e){const r=e.value;t[Rd]&&t[Rd](r.key,r.value),t[Ad]-=r.length,t[Ud].delete(r.key),t[Cd].removeNode(e)}};class Gd{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Kd=(t,e,r,n)=>{let i=r.value;Fd(t,i)&&(jd(t,r),t[xd]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Vd=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[kd]=t.max||1/0;const e=t.length||Dd;if(this[Md]="function"!=typeof e?Dd:e,this[xd]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Nd]=t.maxAge||0,this[Rd]=t.dispose,this[Bd]=t.noDisposeOnSet||!1,this[Ld]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[kd]=t||1/0,qd(this)}get max(){return this[kd]}set allowStale(t){this[xd]=!!t}get allowStale(){return this[xd]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Nd]=t,qd(this)}get maxAge(){return this[Nd]}set lengthCalculator(t){"function"!=typeof t&&(t=Dd),t!==this[Md]&&(this[Md]=t,this[Ad]=0,this[Cd].forEach((t=>{t.length=this[Md](t.value,t.key),this[Ad]+=t.length}))),qd(this)}get lengthCalculator(){return this[Md]}get length(){return this[Ad]}get itemCount(){return this[Cd].length}rforEach(t,e){e=e||this;for(let r=this[Cd].tail;null!==r;){const n=r.prev;Kd(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Cd].head;null!==r;){const n=r.next;Kd(this,t,r,e),r=n}}keys(){return this[Cd].toArray().map((t=>t.key))}values(){return this[Cd].toArray().map((t=>t.value))}reset(){this[Rd]&&this[Cd]&&this[Cd].length&&this[Cd].forEach((t=>this[Rd](t.key,t.value))),this[Ud]=new Map,this[Cd]=new Pd,this[Ad]=0}dump(){return this[Cd].map((t=>!Fd(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Cd]}set(t,e,r){if((r=r||this[Nd])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Md](e,t);if(this[Ud].has(t)){if(i>this[kd])return jd(this,this[Ud].get(t)),!1;const o=this[Ud].get(t).value;return this[Rd]&&(this[Bd]||this[Rd](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Ad]+=i-o.length,o.length=i,this.get(t),qd(this),!0}const o=new Gd(t,e,i,n,r);return o.length>this[kd]?(this[Rd]&&this[Rd](t,e),!1):(this[Ad]+=o.length,this[Cd].unshift(o),this[Ud].set(t,this[Cd].head),qd(this),!0)}has(t){if(!this[Ud].has(t))return!1;const e=this[Ud].get(t).value;return!Fd(this,e)}get(t){return Hd(this,t,!0)}peek(t){return Hd(this,t,!1)}pop(){const t=this[Cd].tail;return t?(jd(this,t),t.value):null}del(t){jd(this,this[Ud].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ud].forEach(((t,e)=>Hd(this,e,!1)))}};class Wd{constructor(t,e){if(e=Xd(e),t instanceof Wd)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Wd(t.raw,e);if(t instanceof Yd)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!iy(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&oy(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=zd.get(e);if(r)return r;const n=this.options.loose,i=n?Zd[ty.HYPHENRANGELOOSE]:Zd[ty.HYPHENRANGE];t=t.replace(i,vy(this.options.includePrerelease)),Jd("hyphen replace",t),t=t.replace(Zd[ty.COMPARATORTRIM],ey),Jd("comparator trim",t,Zd[ty.COMPARATORTRIM]),t=(t=(t=t.replace(Zd[ty.TILDETRIM],ry)).replace(Zd[ty.CARETTRIM],ny)).split(/\s+/).join(" ");const o=n?Zd[ty.COMPARATORLOOSE]:Zd[ty.COMPARATOR],s=t.split(" ").map((t=>uy(t,this.options))).join(" ").split(/\s+/).map((t=>gy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Yd(t,this.options)));s.length;const u=new Map;for(const t of s){if(iy(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return zd.set(e,a),a}intersects(t,e){if(!(t instanceof Wd))throw new TypeError("a Range is required");return this.set.some((r=>sy(r,e)&&t.set.some((t=>sy(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Qd(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,oy=t=>""===t.value,sy=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},uy=(t,e)=>(Jd("comp",t,e),t=cy(t,e),Jd("caret",t),t=hy(t,e),Jd("tildes",t),t=py(t,e),Jd("xrange",t),t=yy(t,e),Jd("stars",t),t),ay=t=>!t||"x"===t.toLowerCase()||"*"===t,hy=(t,e)=>t.trim().split(/\s+/).map((t=>fy(t,e))).join(" "),fy=(t,e)=>{const r=e.loose?Zd[ty.TILDELOOSE]:Zd[ty.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Jd("tilde",t,e,r,n,i,o),ay(r)?s="":ay(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:ay(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Jd("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Jd("tilde return",s),s}))},cy=(t,e)=>t.trim().split(/\s+/).map((t=>ly(t,e))).join(" "),ly=(t,e)=>{Jd("caret",t,e);const r=e.loose?Zd[ty.CARETLOOSE]:Zd[ty.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Jd("caret",t,e,r,i,o,s),ay(r)?u="":ay(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:ay(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Jd("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Jd("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Jd("caret return",u),u}))},py=(t,e)=>(Jd("replaceXRanges",t,e),t.split(/\s+/).map((t=>dy(t,e))).join(" ")),dy=(t,e)=>{t=t.trim();const r=e.loose?Zd[ty.XRANGELOOSE]:Zd[ty.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Jd("xRange",t,r,n,i,o,s,u);const a=ay(i),h=a||ay(o),f=h||ay(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Jd("xRange return",r),r}))},yy=(t,e)=>(Jd("replaceStars",t,e),t.trim().replace(Zd[ty.STAR],"")),gy=(t,e)=>(Jd("replaceGTE0",t,e),t.trim().replace(Zd[e.includePrerelease?ty.GTE0PRE:ty.GTE0],"")),vy=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=ay(n)?"":ay(i)?`>=${n}.0.0${t?"-0":""}`:ay(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=ay(h)?"":ay(f)?`<${+h+1}.0.0-0`:ay(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),my=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},wy=Symbol("SemVer ANY");class by{static get ANY(){return wy}constructor(t,e){if(e=_y(e),t instanceof by){if(t.loose===!!e.loose)return t;t=t.value}Oy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===wy?this.value="":this.value=this.operator+this.semver.version,Oy("comp",this)}parse(t){const e=this.options.loose?Sy[Iy.COMPARATORLOOSE]:Sy[Iy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new Py(r[2],this.options.loose):this.semver=wy}toString(){return this.value}test(t){if(Oy("Comparator.test",t,this.options.loose),this.semver===wy||t===wy)return!0;if("string"==typeof t)try{t=new Py(t,this.options)}catch(t){return!1}return Ty(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof by))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new ky(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new ky(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=Ty(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=Ty(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var Ey=by;const _y=np,{re:Sy,t:Iy}=Zl.exports,Ty=yd,Oy=ep,Py=yp,ky=$d,Ay=$d;var My=(t,e,r)=>{try{e=new Ay(e,r)}catch(t){return!1}return e.test(t)};const xy=$d;var Ny=(t,e)=>new xy(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Ry=yp,By=$d;var Cy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new By(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Ry(n,r)))})),n};const Uy=yp,Ly=$d;var Dy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ly(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Uy(n,r)))})),n};const Hy=yp,Fy=$d,qy=td;var jy=(t,e)=>{t=new Fy(t,e);let r=new Hy("0.0.0");if(t.test(r))return r;if(r=new Hy("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new Hy(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!qy(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!qy(r,i)||(r=i)}return r&&t.test(r)?r:null};const Gy=$d;var Ky=(t,e)=>{try{return new Gy(t,e).range||"*"}catch(t){return null}};const Vy=yp,Wy=Ey,{ANY:$y}=Wy,zy=$d,Xy=My,Yy=td,Jy=rd,Qy=ad,Zy=sd;var tg=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Vy(t,n),e=new zy(e,n),r){case">":i=Yy,o=Qy,s=Jy,u=">",a=">=";break;case"<":i=Jy,o=Zy,s=Yy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Xy(t,e,n))return!1;for(let r=0;r{t.semver===$y&&(t=new Wy(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const eg=tg;var rg=(t,e,r)=>eg(t,e,">",r);const ng=tg;var ig=(t,e,r)=>ng(t,e,"<",r);const og=$d;var sg=(t,e,r)=>(t=new og(t,r),e=new og(e,r),t.intersects(e));const ug=My,ag=Ap;const hg=$d,fg=Ey,{ANY:cg}=fg,lg=My,pg=Ap,dg=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===cg){if(1===e.length&&e[0].semver===cg)return!0;t=r.includePrerelease?[new fg(">=0.0.0-0")]:[new fg(">=0.0.0")]}if(1===e.length&&e[0].semver===cg){if(r.includePrerelease)return!0;e=[new fg(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=yg(i,e,r):"<"===e.operator||"<="===e.operator?o=gg(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=pg(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!lg(t,String(i),r))return null;if(o&&!lg(t,String(o),r))return null;for(const n of e)if(!lg(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=yg(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!lg(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=gg(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!lg(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},yg=(t,e,r)=>{if(!t)return e;const n=pg(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},gg=(t,e,r)=>{if(!t)return e;const n=pg(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var vg=(t,e,r={})=>{if(t===e)return!0;t=new hg(t,r),e=new hg(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=dg(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const mg=Zl.exports;var wg={re:mg.re,src:mg.src,tokens:mg.t,SEMVER_SPEC_VERSION:tp.SEMVER_SPEC_VERSION,SemVer:yp,compareIdentifiers:sp.compareIdentifiers,rcompareIdentifiers:sp.rcompareIdentifiers,parse:Ep,valid:Sp,clean:Tp,inc:Pp,diff:Bp,major:Up,minor:Dp,patch:Fp,prerelease:jp,compare:Ap,rcompare:Kp,compareLoose:Wp,compareBuild:zp,sort:Yp,rsort:Qp,gt:td,lt:rd,eq:xp,neq:id,gte:sd,lte:ad,cmp:yd,coerce:bd,Comparator:Ey,Range:$d,satisfies:My,toComparators:Ny,maxSatisfying:Cy,minSatisfying:Dy,minVersion:jy,validRange:Ky,outside:tg,gtr:rg,ltr:ig,intersects:sg,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>ag(t,e,r)));for(const t of s){ug(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Ag.alloc(0);for(var e=Ag.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ng(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Ag.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:xg,value:function(t,e){return Mg(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Fg("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Fg("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${qg(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${qg(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Fg("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Fg("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Fg("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Fg("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Fg("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Fg("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Fg("ERR_STREAM_WRITE_AFTER_END","write after end"),Fg("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Fg("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Fg("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Dg.codes=Hg;var jg=Dg.codes.ERR_INVALID_OPT_VALUE;var Gg,Kg={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new jg(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Vg=l.default.deprecate,Wg=pv;function $g(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}pv.WritableState=lv;var zg={deprecate:Vg},Xg=Tg,Yg=h.default.Buffer,Jg=p.Uint8Array||function(){};var Qg,Zg=Lg,tv=Kg.getHighWaterMark,ev=Dg.codes,rv=ev.ERR_INVALID_ARG_TYPE,nv=ev.ERR_METHOD_NOT_IMPLEMENTED,iv=ev.ERR_MULTIPLE_CALLBACK,ov=ev.ERR_STREAM_CANNOT_PIPE,sv=ev.ERR_STREAM_DESTROYED,uv=ev.ERR_STREAM_NULL_VALUES,av=ev.ERR_STREAM_WRITE_AFTER_END,hv=ev.ERR_UNKNOWN_ENCODING,fv=Zg.errorOrDestroy;function cv(){}function lv(t,e,r){Gg=Gg||Ev,t=t||{},"boolean"!=typeof r&&(r=e instanceof Gg),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=tv(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new iv;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(wv,t,e),t._writableState.errorEmitted=!0,fv(t,n)):(i(n),t._writableState.errorEmitted=!0,fv(t,n),wv(t,e))}(t,r,n,e,i);else{var o=vv(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||gv(t,r),n?process.nextTick(yv,t,r,o,i):yv(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $g(this)}function pv(t){var e=this instanceof(Gg=Gg||Ev);if(!e&&!Qg.call(pv,this))return new pv(t);this._writableState=new lv(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Xg.call(this)}function dv(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new sv("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function yv(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),wv(t,e)}function gv(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,dv(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new $g(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(dv(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function vv(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function mv(t,e){t._final((function(r){e.pendingcb--,r&&fv(t,r),e.prefinished=!0,t.emit("prefinish"),wv(t,e)}))}function wv(t,e){var r=vv(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(mv,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}ut.exports(pv,Xg),lv.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(lv.prototype,"buffer",{get:zg.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Qg=Function.prototype[Symbol.hasInstance],Object.defineProperty(pv,Symbol.hasInstance,{value:function(t){return!!Qg.call(this,t)||this===pv&&(t&&t._writableState instanceof lv)}})):Qg=function(t){return t instanceof this},pv.prototype.pipe=function(){fv(this,new ov)},pv.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Yg.isBuffer(n)||n instanceof Jg);return s&&!Yg.isBuffer(t)&&(t=function(t){return Yg.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=cv),i.ending?function(t,e){var r=new av;fv(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new uv:"string"==typeof r||e.objectMode||(i=new rv("chunk",["string","Buffer"],r)),!i||(fv(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Yg.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new hv(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(pv.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(pv.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),pv.prototype._write=function(t,e,r){r(new nv("_write()"))},pv.prototype._writev=null,pv.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,wv(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(pv.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(pv.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),pv.prototype.destroy=Zg.destroy,pv.prototype._undestroy=Zg.undestroy,pv.prototype._destroy=function(t,e){e(t)};var bv=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},Ev=Pv,_v=dm,Sv=Wg;ut.exports(Pv,_v);for(var Iv=bv(Sv.prototype),Tv=0;Tv>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Cv(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Uv(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function Lv(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Dv(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Hv(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Fv(t){return t.toString(this.encoding)}function qv(t){return t&&t.length?this.write(t):""}Mv.StringDecoder=Rv,Rv.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Rv.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var jv=Dg.codes.ERR_STREAM_PREMATURE_CLOSE;function Gv(){}var Kv,Vv=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===vm.prototype||(e=function(t){return vm.from(t)}(e)),n)s.endEmitted?Nm(t,new xm):Lm(t,s,e,!0);else if(s.ended)Nm(t,new Am);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?Lm(t,s,e,!1):jm(t,s)):Lm(t,s,e,!1)}else n||(s.reading=!1,jm(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Dm?t=Dm:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Fm(t){var e=t._readableState;wm("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(wm("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(qm,t))}function qm(t){var e=t._readableState;wm("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$m(t)}function jm(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(Gm,t,e))}function Gm(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Vm(t){wm("readable nexttick read 0"),t.read(0)}function Wm(t,e){wm("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$m(t),e.flowing&&!e.reading&&t.read(0)}function $m(t){var e=t._readableState;for(wm("flow",e.flowing);e.flowing&&null!==t.read(););}function zm(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function Xm(t){var e=t._readableState;wm("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(Ym,e,t))}function Ym(t,e){if(wm("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function Jm(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return wm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Xm(this):Fm(this),null;if(0===(t=Hm(t,e))&&e.ended)return 0===e.length&&Xm(this),null;var n,i=e.needReadable;return wm("need readable",i),(0===e.length||e.length-t0?zm(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Xm(this)),null!==n&&this.emit("data",n),n},Cm.prototype._read=function(t){Nm(this,new Mm("_read()"))},Cm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,wm("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){wm("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,wm("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){wm("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;wm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&ym(t,"data")&&(e.flowing=!0,$m(t))}}(r);t.on("drain",u);var a=!1;function h(e){wm("ondata");var i=t.write(e);wm("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Jm(n.pipes,t))&&!a&&(wm("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){wm("onerror",e),p(),t.removeListener("error",f),0===ym(t,"error")&&Nm(t,e)}function c(){t.removeListener("finish",l),p()}function l(){wm("onfinish"),t.removeListener("close",c),p()}function p(){wm("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(wm("pipe resume"),r.resume()),t},Cm.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,wm("on readable",n.length,n.reading),n.length?Fm(this):n.reading||process.nextTick(Vm,this))),r},Cm.prototype.addListener=Cm.prototype.on,Cm.prototype.removeListener=function(t,e){var r=gm.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(Km,this),r},Cm.prototype.removeAllListeners=function(t){var e=gm.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(Km,this),e},Cm.prototype.resume=function(){var t=this._readableState;return t.flowing||(wm("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(Wm,t,e))}(this,t)),t.paused=!1,this},Cm.prototype.pause=function(){return wm("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(wm("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Cm.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(wm("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(wm("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(mw),s||(o.forEach(mw),i(n))}))}));return e.reduce(ww)};!function(t,e){var r=f.default;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=dm).Stream=r||e,e.Readable=e,e.Writable=Wg,e.Duplex=Ev,e.Transform=Qm,e.PassThrough=fw,e.finished=Vv,e.pipeline=Ew)}(Ig,Ig.exports);var _w=m.exports.Buffer,Sw=Ig.exports.Transform;function Iw(t){Sw.call(this),this._block=_w.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,ut.exports)(Iw,Sw),Iw.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},Iw.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},Iw.prototype.update=function(t,e){if(function(t,e){if(!_w.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");_w.isBuffer(t)||(t=_w.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},Iw.prototype._update=function(){throw new Error("_update is not implemented")},Iw.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},Iw.prototype._digest=function(){throw new Error("_digest is not implemented")};var Tw=Iw,Ow=h.default.Buffer,Pw=ut.exports,kw=Tw,Aw=new Array(16),Mw=[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],xw=[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],Nw=[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],Rw=[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],Bw=[0,1518500249,1859775393,2400959708,2840853838],Cw=[1352829926,1548603684,1836072691,2053994217,0];function Uw(){kw.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function Lw(t,e){return t<>>32-e}function Dw(t,e,r,n,i,o,s,u){return Lw(t+(e^r^n)+o+s|0,u)+i|0}function Hw(t,e,r,n,i,o,s,u){return Lw(t+(e&r|~e&n)+o+s|0,u)+i|0}function Fw(t,e,r,n,i,o,s,u){return Lw(t+((e|~r)^n)+o+s|0,u)+i|0}function qw(t,e,r,n,i,o,s,u){return Lw(t+(e&n|r&~n)+o+s|0,u)+i|0}function jw(t,e,r,n,i,o,s,u){return Lw(t+(e^(r|~n))+o+s|0,u)+i|0}Pw(Uw,kw),Uw.prototype._update=function(){for(var t=Aw,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=Dw(r,n,i,o,s,t[Mw[l]],Bw[0],Nw[l]),d=jw(u,a,h,f,c,t[xw[l]],Cw[0],Rw[l])):l<32?(p=Hw(r,n,i,o,s,t[Mw[l]],Bw[1],Nw[l]),d=qw(u,a,h,f,c,t[xw[l]],Cw[1],Rw[l])):l<48?(p=Fw(r,n,i,o,s,t[Mw[l]],Bw[2],Nw[l]),d=Fw(u,a,h,f,c,t[xw[l]],Cw[2],Rw[l])):l<64?(p=qw(r,n,i,o,s,t[Mw[l]],Bw[3],Nw[l]),d=Hw(u,a,h,f,c,t[xw[l]],Cw[3],Rw[l])):(p=jw(r,n,i,o,s,t[Mw[l]],Bw[4],Nw[l]),d=Dw(u,a,h,f,c,t[xw[l]],Cw[4],Rw[l])),r=s,s=o,o=Lw(i,10),i=n,n=p,u=c,c=f,f=Lw(h,10),h=a,a=d}var y=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=y},Uw.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=Ow.alloc?Ow.alloc(20):new Ow(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var Gw=Uw,Kw={exports:{}},Vw=m.exports.Buffer;function Ww(t,e){this._block=Vw.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}Ww.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=Vw.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},Ww.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var $w=Ww,zw=ut.exports,Xw=$w,Yw=m.exports.Buffer,Jw=[1518500249,1859775393,-1894007588,-899497514],Qw=new Array(80);function Zw(){this.init(),this._w=Qw,Xw.call(this,64,56)}function tb(t){return t<<30|t>>>2}function eb(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}zw(Zw,Xw),Zw.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Zw.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+eb(f,i,o,s)+u+r[h]+Jw[f];u=s,s=o,o=tb(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},Zw.prototype._hash=function(){var t=Yw.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var rb=Zw,nb=ut.exports,ib=$w,ob=m.exports.Buffer,sb=[1518500249,1859775393,-1894007588,-899497514],ub=new Array(80);function ab(){this.init(),this._w=ub,ib.call(this,64,56)}function hb(t){return t<<5|t>>>27}function fb(t){return t<<30|t>>>2}function cb(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}nb(ab,ib),ab.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},ab.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=hb(n)+cb(f,i,o,s)+u+r[h]+sb[f]|0;u=s,s=o,o=fb(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},ab.prototype._hash=function(){var t=ob.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var lb=ab,pb=ut.exports,db=$w,yb=m.exports.Buffer,gb=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],vb=new Array(64);function mb(){this.init(),this._w=vb,db.call(this,64,56)}function wb(t,e,r){return r^t&(e^r)}function bb(t,e,r){return t&e|r&(t|e)}function Eb(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function _b(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function Sb(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function Ib(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}pb(mb,db),mb.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},mb.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=Ib(e[f-2])+e[f-7]+Sb(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+_b(s)+wb(s,u,a)+gb[c]+e[c]|0,p=Eb(r)+bb(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},mb.prototype._hash=function(){var t=yb.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var Tb=mb,Ob=ut.exports,Pb=Tb,kb=$w,Ab=m.exports.Buffer,Mb=new Array(64);function xb(){this.init(),this._w=Mb,kb.call(this,64,56)}Ob(xb,Pb),xb.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},xb.prototype._hash=function(){var t=Ab.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var Nb=xb,Rb=ut.exports,Bb=$w,Cb=m.exports.Buffer,Ub=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Lb=new Array(160);function Db(){this.init(),this._w=Lb,Bb.call(this,128,112)}function Hb(t,e,r){return r^t&(e^r)}function Fb(t,e,r){return t&e|r&(t|e)}function qb(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function jb(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function Gb(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function Kb(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function Vb(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function Wb(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function $b(t,e){return t>>>0>>0?1:0}Rb(Db,Bb),Db.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Db.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,y=0|this._fl,g=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=Gb(w,b),_=Kb(b,w),S=Vb(w=e[m-4],b=e[m-4+1]),I=Wb(b,w),T=e[m-14],O=e[m-14+1],P=e[m-32],k=e[m-32+1],A=_+O|0,M=E+T+$b(A,_)|0;M=(M=M+S+$b(A=A+I|0,I)|0)+P+$b(A=A+k|0,k)|0,e[m]=M,e[m+1]=A}for(var x=0;x<160;x+=2){M=e[x],A=e[x+1];var N=Fb(r,n,i),R=Fb(f,c,l),B=qb(r,f),C=qb(f,r),U=jb(s,d),L=jb(d,s),D=Ub[x],H=Ub[x+1],F=Hb(s,u,a),q=Hb(d,y,g),j=v+L|0,G=h+U+$b(j,v)|0;G=(G=(G=G+F+$b(j=j+q|0,q)|0)+D+$b(j=j+H|0,H)|0)+M+$b(j=j+A|0,A)|0;var K=C+R|0,V=B+N+$b(K,C)|0;h=a,v=g,a=u,g=y,u=s,y=d,s=o+G+$b(d=p+j|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+V+$b(f=j+K|0,j)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+y|0,this._gl=this._gl+g|0,this._hl=this._hl+v|0,this._ah=this._ah+r+$b(this._al,f)|0,this._bh=this._bh+n+$b(this._bl,c)|0,this._ch=this._ch+i+$b(this._cl,l)|0,this._dh=this._dh+o+$b(this._dl,p)|0,this._eh=this._eh+s+$b(this._el,d)|0,this._fh=this._fh+u+$b(this._fl,y)|0,this._gh=this._gh+a+$b(this._gl,g)|0,this._hh=this._hh+h+$b(this._hl,v)|0},Db.prototype._hash=function(){var t=Cb.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var zb=Db,Xb=ut.exports,Yb=zb,Jb=$w,Qb=m.exports.Buffer,Zb=new Array(160);function tE(){this.init(),this._w=Zb,Jb.call(this,128,112)}Xb(tE,Yb),tE.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},tE.prototype._hash=function(){var t=Qb.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var eE=tE,rE=Kw.exports=function(t){t=t.toLowerCase();var e=rE[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};rE.sha=rb,rE.sha1=lb,rE.sha224=Nb,rE.sha256=Tb,rE.sha384=eE,rE.sha512=zb;var nE=Kw.exports;function iE(t){return(new Gw).update(nE("sha256").update(t).digest()).digest()}var oE,sE=(oE=function(t,e){return oE=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},oE(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}oE(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),uE=function(t,e){this.psbt=t,this.masterFp=e},aE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(uE),hE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=iE(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(aE),fE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new bg,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Gl.sha256(Buffer.from("TapTweak","utf-8"));return Gl.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(F.exports.pointAddScalar(e,r)).slice(1)},e}(aE),cE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=this.createRedeemScript(t),n=iE(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=iE(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(aE),lE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=iE(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(aE),pE=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},dE=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return mE(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new vE(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new vE(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function GE(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,jE(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,jE(t.script.length),t.script])}))),r}function KE(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,jE(t.script.length),t.script,t.sequence])}));var a=GE(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),jE(t.inputs.length),s,a])}var VE=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},WE=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new wE(e,bE(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return VE(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I;return WE(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new kE,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new fE(e,r):t.additionals.includes("bech32")?new lE(e,r):t.segwit?new cE(e,r):new hE(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],y=0,T.label=2;case 2:return y0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new bg).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new bg;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new bg;FE(h,f),FE(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new bg).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}HE(t,r)}}(r),I=function(t){var e,r,n=new bg;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new bg,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function h_(t,e,r){return s_(this,void 0,void 0,(function(){var n,i,o,s;return u_(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function f_(t,e,r,n){return void 0===n&&(n=[]),s_(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N=this;return u_(this,(function(R){switch(R.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return s_(N,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return u_(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>_g?_g:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=a_(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,h_(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return h_(t,e)},[4,h_(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),jE(o.length)]),e)];case 1:R.sent(),R.label=2;case 2:R.trys.push([2,8,9,10]),d=a_(o),y=d.next(),R.label=3;case 3:return y.done?[3,7]:(g=y.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?g.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([g.prevout,m,v?Buffer.from([0]):jE(g.script.length)]),[4,h_(t,O)]);case 4:return R.sent(),[4,f?p(Buffer.concat([g.script,g.sequence])):v?p(g.sequence):l(g.script,g.sequence)];case 5:R.sent(),R.label=6;case 6:return y=d.next(),[3,3];case 7:return[3,10];case 8:return w=R.sent(),k={error:w},[3,10];case 9:try{y&&!y.done&&(A=d.return)&&A.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,h_(t,jE(s.length))];case 11:R.sent(),R.label=12;case 12:R.trys.push([12,17,18,19]),b=a_(s),E=b.next(),R.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),jE(_.script.length),_.script]),[4,h_(t,O)]);case 14:R.sent(),R.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=R.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([jE(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return P=R.sent(),o_(P,"missing result in processScriptBlocks"),[2,P]}}))}))}var c_=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},l_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function d_(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function y_(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),c_(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P;return l_(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),jE(r.inputs.length)]),[4,d_(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=p_(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,y=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,y.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,y,f?Buffer.from([0]):Buffer.alloc(0),jE(p.script.length)]),[4,d_(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),g=[],v=0,0===p.script.length)g.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>_g?_g:p.script.length-v,v+m!==p.script.length?g.push(p.script.slice(v,v+m)):g.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=p_(g),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,d_(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(P=w.return)&&P.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function g_(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=nE("sha256").update(nE("sha256").update(KE(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function v_(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=k(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var m_=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},w_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:_g,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var __=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},S_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A_={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function M_(t,e){return O_(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N,R,B,C,U,L,D,H,F,q,j,G,K,V,W,$,z,X,Y,J,Q,Z,tt,et,rt,nt,it,ot,st,ut,at;return P_(this,(function(ht){switch(ht.label){case 0:if(r=T_(T_({},A_),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,y=r.onDeviceSignatureRequested,void 0!==(g=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,I_(t)];case 2:return v=ht.sent(),g=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||wg.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return g=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),P=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),A=[],M=[],x=[],N=[],R=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},U=T&&!g?g_:f_,L=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=k_(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:F=ht.sent(),QE("hw","got trustedInput="+F),(q=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:Sg,0),A.push({trustedInput:!0,value:Buffer.from(F,"hex"),sequence:q}),ht.label=8;case 8:j=$[0].outputs,G=$[1],j&&G<=j.length-1&&M.push(j[G]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:Sg,0),{script:O,prevout:P,sequence:e}})),B)return[3,18];V=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),iE(N[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[A[it]]:A,T?X.inputs=[T_(T_({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,y_(t,!T&&R,X,Y,T,!!l&&!b,c,g)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,b_(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,E_(t,L,c)];case 30:ht.sent(),ht.label=31;case 31:return R&&(d(),w(1,0)),[4,v_(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,R&&(R=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},L_={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function D_(t,e){return B_(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N,R,B,C;return C_(this,(function(U){switch(U.label){case 0:r=R_(R_({},L_),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],y=[],g=!0,v=!1,m={inputs:[],version:l},w=a?g_:f_,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),E=U_(n),_=E.next(),U.label=2;case 2:return _.done?[3,6]:(A=_.value,v?[3,4]:[4,w(t,A[1],A[0])]);case 3:S=U.sent(),(P=Buffer.alloc(4)).writeUInt32LE(A.length>=4&&"number"==typeof A[3]?A[3]:Sg,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:P}),U.label=4;case 4:I=A[0].outputs,T=A[1],I&&T<=I.length-1&&d.push(I[T]),U.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=U.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:Sg,0),m.inputs.push({script:f,prevout:c,sequence:P});return a?[4,y_(t,!0,m,p,!0)]:[3,12];case 10:return U.sent(),[4,E_(t,b)];case 11:U.sent(),U.label=12;case 12:k=0,U.label=13;case 13:return k=3&&"string"==typeof A[2]?Buffer.from(A[2],"hex"):d[k].script,x=Object.assign({},m),N=a?[p[k]]:p,a?x.inputs=[R_(R_({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,y_(t,!a&&g,x,N,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,E_(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,v_(t,i[k],s,u)];case 17:R=U.sent(),y.push(a?R.toString("hex"):R.slice(0,R.length-1).toString("hex")),m.inputs[k].script=f,g&&(g=!1),U.label=18;case 18:return k++,[3,13];case 19:return[2,y]}}))}))}var H_=function(){return H_=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},c.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return c.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return u=c.sent(),a=u[0]-48,0===(h=u.slice(4,4+u[3]))[0]&&(h=h.slice(1)),h=h.toString("hex"),o=4+u[3]+2,0===(f=u.slice(o,o+u[o-1]))[0]&&(f=f.slice(1)),f=f.toString("hex"),[2,{v:a,r:h,s:f}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),M_(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),D_(this.transport,t)},t}();function G_(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var K_=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function V_(t){return nE("sha256").update(t).digest()}var W_,$_=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new yE(t.map((function(t){return gE(t)}))),this.values=e,this.valuesTree=new yE(e.map((function(t){return gE(t)})))}return t.prototype.commitment=function(){return Buffer.concat([jE(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),z_=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),X_=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},Y_=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},tS=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(W_||(W_={}));var rS,nS,iS=function(){},oS=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=W_.YIELD,n.results=e,n}return Q_(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(iS),sS=function(t){function e(e,r){var n=t.call(this)||this;return n.code=W_.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return Q_(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=jE(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,tS([],Z_(a.slice(-f)),!1)),Buffer.concat(tS([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],Z_(a.slice(0,h)),!1))},e}(iS),aS=function(t){function e(e){var r=t.call(this)||this;return r.code=W_.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return Q_(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(rS||(rS={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(nS||(nS={}));var dS=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return cS(this,void 0,void 0,(function(){var n,i,o;return lS(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,nS.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return cS(this,void 0,void 0,(function(){return lS(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(rS.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),P(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return cS(this,void 0,void 0,(function(){var o,s;return lS(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new fS((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(rS.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return cS(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S;return lS(this,(function(I){switch(I.label){case 0:if(i=new J_(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new fS(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=pS(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=pS(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new yE(i.inputMapCommitments.map((function(t){return gE(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new yE(i.outputMapCommitments.map((function(t){return gE(t)}))).getRoot(),[4,this.makeRequest(rS.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),jE(i.getGlobalInputCount()),c,jE(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(y=pS(p),g=y.next();!g.done;g=y.next())v=g.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{g&&!g.done&&(S=y.return)&&S.call(y)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return cS(this,void 0,void 0,(function(){return lS(this,(function(t){return[2,this.makeRequest(rS.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var yS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},gS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof zE&&"bech32m"!=r.format)||r.verify&&0!=r.verify||mS(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),y=Buffer.from(t,"hex"),g=y.slice(a,a+4),v=g.equals(Buffer.from([3,0,0,128]))||g.equals(Buffer.from([4,0,0,128])),m=g.equals(Buffer.from([1,0,0,0]))||g.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===y[a]&&0!==y[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=y.slice(a,4+a),a+=4),v&&(c=y.slice(a,4+a),a+=4);var w=qE(y,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new j_(this.transport)},t.prototype.new=function(){return new zE(new dS(this.transport))},t}();function mS(t){var e=2147483648,r=M(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var wS=Object.freeze({__proto__:null,default:vS}),bS={},ES={},_S={},SS={};Object.defineProperty(SS,"__esModule",{value:!0});var IS="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},TS={},OS={};SS.addCustomErrorDeserializer=function(t,e){OS[t]=e};var PS=SS.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,TS[t]=e,e};function kS(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":IS(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=kS(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}SS.deserializeError=function t(e){if("object"===(void 0===e?"undefined":IS(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=OS[i];if(o)n=o(e);else{var s="Error"===i?Error:TS[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=PS(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},SS.serializeError=function(t){return t?"object"===(void 0===t?"undefined":IS(t))?kS(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(_S,"__esModule",{value:!0}),_S.StatusCodes=_S.DBNotReset=_S.DBWrongPassword=_S.NoDBPathGiven=_S.FirmwareOrAppUpdateRequired=_S.LedgerAPI5xx=_S.LedgerAPI4xx=_S.GenuineCheckFailed=_S.PairingFailed=_S.SyncError=_S.FeeTooHigh=_S.FeeRequired=_S.FeeNotLoaded=_S.CantScanQRCode=_S.ETHAddressNonEIP=_S.WrongAppForCurrency=_S.WrongDeviceForAccount=_S.WebsocketConnectionFailed=_S.WebsocketConnectionError=_S.DeviceShouldStayInApp=_S.TransportWebUSBGestureRequired=_S.TransportInterfaceNotAvailable=_S.TransportOpenUserCancelled=_S.UserRefusedOnDevice=_S.UserRefusedAllowManager=_S.UserRefusedFirmwareUpdate=_S.UserRefusedAddress=_S.UserRefusedDeviceNameChange=_S.UpdateYourApp=_S.UnavailableTezosOriginatedAccountSend=_S.UnavailableTezosOriginatedAccountReceive=_S.RecipientRequired=_S.MCUNotGenuineToDashboard=_S.UnexpectedBootloader=_S.TimeoutTagged=_S.RecommendUndelegation=_S.RecommendSubAccountsToEmpty=_S.PasswordIncorrectError=_S.PasswordsDontMatchError=_S.GasLessThanEstimate=_S.NotSupportedLegacyAddress=_S.NotEnoughGas=_S.NoAccessToCamera=_S.NotEnoughBalanceBecauseDestinationNotCreated=_S.NotEnoughSpendableBalance=_S.NotEnoughBalanceInParentAccount=_S.NotEnoughBalanceToDelegate=_S.NotEnoughBalance=_S.NoAddressesFound=_S.NetworkDown=_S.ManagerUninstallBTCDep=_S.ManagerNotEnoughSpaceError=_S.ManagerFirmwareNotEnoughSpaceError=_S.ManagerDeviceLockedError=_S.ManagerAppDepUninstallRequired=_S.ManagerAppDepInstallRequired=_S.ManagerAppRelyOnBTCError=_S.ManagerAppAlreadyInstalledError=_S.LedgerAPINotAvailable=_S.LedgerAPIErrorWithMessage=_S.LedgerAPIError=_S.UnknownMCU=_S.LatestMCUInstalledError=_S.InvalidAddressBecauseDestinationIsAlsoSource=_S.InvalidAddress=_S.InvalidXRPTag=_S.HardResetFail=_S.FeeEstimationFailed=_S.EthAppPleaseEnableContractData=_S.EnpointConfigError=_S.DisconnectedDeviceDuringOperation=_S.DisconnectedDevice=_S.DeviceSocketNoBulkStatus=_S.DeviceSocketFail=_S.DeviceNameInvalid=_S.DeviceHalted=_S.DeviceInOSUExpected=_S.DeviceOnDashboardUnexpected=_S.DeviceOnDashboardExpected=_S.DeviceNotGenuineError=_S.DeviceGenuineSocketEarlyClose=_S.DeviceAppVerifyNotSupported=_S.CurrencyNotSupported=_S.CashAddrNotSupported=_S.CantOpenDevice=_S.BtcUnmatchedApp=_S.BluetoothRequired=_S.AmountRequired=_S.AccountNotSupported=_S.AccountNameRequiredError=_S.addCustomErrorDeserializer=_S.createCustomErrorClass=_S.deserializeError=_S.serializeError=void 0,_S.TransportError=MS,_S.getAltStatusMessage=NS,_S.TransportStatusError=RS;var AS=SS;function MS(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}_S.serializeError=AS.serializeError,_S.deserializeError=AS.deserializeError,_S.createCustomErrorClass=AS.createCustomErrorClass,_S.addCustomErrorDeserializer=AS.addCustomErrorDeserializer,_S.AccountNameRequiredError=(0,AS.createCustomErrorClass)("AccountNameRequired"),_S.AccountNotSupported=(0,AS.createCustomErrorClass)("AccountNotSupported"),_S.AmountRequired=(0,AS.createCustomErrorClass)("AmountRequired"),_S.BluetoothRequired=(0,AS.createCustomErrorClass)("BluetoothRequired"),_S.BtcUnmatchedApp=(0,AS.createCustomErrorClass)("BtcUnmatchedApp"),_S.CantOpenDevice=(0,AS.createCustomErrorClass)("CantOpenDevice"),_S.CashAddrNotSupported=(0,AS.createCustomErrorClass)("CashAddrNotSupported"),_S.CurrencyNotSupported=(0,AS.createCustomErrorClass)("CurrencyNotSupported"),_S.DeviceAppVerifyNotSupported=(0,AS.createCustomErrorClass)("DeviceAppVerifyNotSupported"),_S.DeviceGenuineSocketEarlyClose=(0,AS.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),_S.DeviceNotGenuineError=(0,AS.createCustomErrorClass)("DeviceNotGenuine"),_S.DeviceOnDashboardExpected=(0,AS.createCustomErrorClass)("DeviceOnDashboardExpected"),_S.DeviceOnDashboardUnexpected=(0,AS.createCustomErrorClass)("DeviceOnDashboardUnexpected"),_S.DeviceInOSUExpected=(0,AS.createCustomErrorClass)("DeviceInOSUExpected"),_S.DeviceHalted=(0,AS.createCustomErrorClass)("DeviceHalted"),_S.DeviceNameInvalid=(0,AS.createCustomErrorClass)("DeviceNameInvalid"),_S.DeviceSocketFail=(0,AS.createCustomErrorClass)("DeviceSocketFail"),_S.DeviceSocketNoBulkStatus=(0,AS.createCustomErrorClass)("DeviceSocketNoBulkStatus"),_S.DisconnectedDevice=(0,AS.createCustomErrorClass)("DisconnectedDevice"),_S.DisconnectedDeviceDuringOperation=(0,AS.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),_S.EnpointConfigError=(0,AS.createCustomErrorClass)("EnpointConfig"),_S.EthAppPleaseEnableContractData=(0,AS.createCustomErrorClass)("EthAppPleaseEnableContractData"),_S.FeeEstimationFailed=(0,AS.createCustomErrorClass)("FeeEstimationFailed"),_S.HardResetFail=(0,AS.createCustomErrorClass)("HardResetFail"),_S.InvalidXRPTag=(0,AS.createCustomErrorClass)("InvalidXRPTag"),_S.InvalidAddress=(0,AS.createCustomErrorClass)("InvalidAddress"),_S.InvalidAddressBecauseDestinationIsAlsoSource=(0,AS.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),_S.LatestMCUInstalledError=(0,AS.createCustomErrorClass)("LatestMCUInstalledError"),_S.UnknownMCU=(0,AS.createCustomErrorClass)("UnknownMCU"),_S.LedgerAPIError=(0,AS.createCustomErrorClass)("LedgerAPIError"),_S.LedgerAPIErrorWithMessage=(0,AS.createCustomErrorClass)("LedgerAPIErrorWithMessage"),_S.LedgerAPINotAvailable=(0,AS.createCustomErrorClass)("LedgerAPINotAvailable"),_S.ManagerAppAlreadyInstalledError=(0,AS.createCustomErrorClass)("ManagerAppAlreadyInstalled"),_S.ManagerAppRelyOnBTCError=(0,AS.createCustomErrorClass)("ManagerAppRelyOnBTC"),_S.ManagerAppDepInstallRequired=(0,AS.createCustomErrorClass)("ManagerAppDepInstallRequired"),_S.ManagerAppDepUninstallRequired=(0,AS.createCustomErrorClass)("ManagerAppDepUninstallRequired"),_S.ManagerDeviceLockedError=(0,AS.createCustomErrorClass)("ManagerDeviceLocked"),_S.ManagerFirmwareNotEnoughSpaceError=(0,AS.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),_S.ManagerNotEnoughSpaceError=(0,AS.createCustomErrorClass)("ManagerNotEnoughSpace"),_S.ManagerUninstallBTCDep=(0,AS.createCustomErrorClass)("ManagerUninstallBTCDep"),_S.NetworkDown=(0,AS.createCustomErrorClass)("NetworkDown"),_S.NoAddressesFound=(0,AS.createCustomErrorClass)("NoAddressesFound"),_S.NotEnoughBalance=(0,AS.createCustomErrorClass)("NotEnoughBalance"),_S.NotEnoughBalanceToDelegate=(0,AS.createCustomErrorClass)("NotEnoughBalanceToDelegate"),_S.NotEnoughBalanceInParentAccount=(0,AS.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),_S.NotEnoughSpendableBalance=(0,AS.createCustomErrorClass)("NotEnoughSpendableBalance"),_S.NotEnoughBalanceBecauseDestinationNotCreated=(0,AS.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),_S.NoAccessToCamera=(0,AS.createCustomErrorClass)("NoAccessToCamera"),_S.NotEnoughGas=(0,AS.createCustomErrorClass)("NotEnoughGas"),_S.NotSupportedLegacyAddress=(0,AS.createCustomErrorClass)("NotSupportedLegacyAddress"),_S.GasLessThanEstimate=(0,AS.createCustomErrorClass)("GasLessThanEstimate"),_S.PasswordsDontMatchError=(0,AS.createCustomErrorClass)("PasswordsDontMatch"),_S.PasswordIncorrectError=(0,AS.createCustomErrorClass)("PasswordIncorrect"),_S.RecommendSubAccountsToEmpty=(0,AS.createCustomErrorClass)("RecommendSubAccountsToEmpty"),_S.RecommendUndelegation=(0,AS.createCustomErrorClass)("RecommendUndelegation"),_S.TimeoutTagged=(0,AS.createCustomErrorClass)("TimeoutTagged"),_S.UnexpectedBootloader=(0,AS.createCustomErrorClass)("UnexpectedBootloader"),_S.MCUNotGenuineToDashboard=(0,AS.createCustomErrorClass)("MCUNotGenuineToDashboard"),_S.RecipientRequired=(0,AS.createCustomErrorClass)("RecipientRequired"),_S.UnavailableTezosOriginatedAccountReceive=(0,AS.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),_S.UnavailableTezosOriginatedAccountSend=(0,AS.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),_S.UpdateYourApp=(0,AS.createCustomErrorClass)("UpdateYourApp"),_S.UserRefusedDeviceNameChange=(0,AS.createCustomErrorClass)("UserRefusedDeviceNameChange"),_S.UserRefusedAddress=(0,AS.createCustomErrorClass)("UserRefusedAddress"),_S.UserRefusedFirmwareUpdate=(0,AS.createCustomErrorClass)("UserRefusedFirmwareUpdate"),_S.UserRefusedAllowManager=(0,AS.createCustomErrorClass)("UserRefusedAllowManager"),_S.UserRefusedOnDevice=(0,AS.createCustomErrorClass)("UserRefusedOnDevice"),_S.TransportOpenUserCancelled=(0,AS.createCustomErrorClass)("TransportOpenUserCancelled"),_S.TransportInterfaceNotAvailable=(0,AS.createCustomErrorClass)("TransportInterfaceNotAvailable"),_S.TransportWebUSBGestureRequired=(0,AS.createCustomErrorClass)("TransportWebUSBGestureRequired"),_S.DeviceShouldStayInApp=(0,AS.createCustomErrorClass)("DeviceShouldStayInApp"),_S.WebsocketConnectionError=(0,AS.createCustomErrorClass)("WebsocketConnectionError"),_S.WebsocketConnectionFailed=(0,AS.createCustomErrorClass)("WebsocketConnectionFailed"),_S.WrongDeviceForAccount=(0,AS.createCustomErrorClass)("WrongDeviceForAccount"),_S.WrongAppForCurrency=(0,AS.createCustomErrorClass)("WrongAppForCurrency"),_S.ETHAddressNonEIP=(0,AS.createCustomErrorClass)("ETHAddressNonEIP"),_S.CantScanQRCode=(0,AS.createCustomErrorClass)("CantScanQRCode"),_S.FeeNotLoaded=(0,AS.createCustomErrorClass)("FeeNotLoaded"),_S.FeeRequired=(0,AS.createCustomErrorClass)("FeeRequired"),_S.FeeTooHigh=(0,AS.createCustomErrorClass)("FeeTooHigh"),_S.SyncError=(0,AS.createCustomErrorClass)("SyncError"),_S.PairingFailed=(0,AS.createCustomErrorClass)("PairingFailed"),_S.GenuineCheckFailed=(0,AS.createCustomErrorClass)("GenuineCheckFailed"),_S.LedgerAPI4xx=(0,AS.createCustomErrorClass)("LedgerAPI4xx"),_S.LedgerAPI5xx=(0,AS.createCustomErrorClass)("LedgerAPI5xx"),_S.FirmwareOrAppUpdateRequired=(0,AS.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),_S.NoDBPathGiven=(0,AS.createCustomErrorClass)("NoDBPathGiven"),_S.DBWrongPassword=(0,AS.createCustomErrorClass)("DBWrongPassword"),_S.DBNotReset=(0,AS.createCustomErrorClass)("DBNotReset"),MS.prototype=new Error,(0,AS.addCustomErrorDeserializer)("TransportError",(function(t){return new MS(t.message,t.id)}));var xS=_S.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function NS(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function RS(t){this.name="TransportStatusError";var e=Object.keys(xS).find((function(e){return xS[e]===t}))||"UNKNOWN_ERROR",r=NS(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}RS.prototype=new Error,(0,AS.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new RS(t.statusCode)})),Object.defineProperty(ES,"__esModule",{value:!0}),ES.getAltStatusMessage=ES.StatusCodes=ES.TransportStatusError=ES.TransportError=void 0;var BS,CS=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[DS.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new DS.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new DS.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=FS(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new DS.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return CS(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new DS.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new DS.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();qS.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",qS.ErrorMessage_NoDeviceFound="No Ledger device found",ES.default=qS;var jS={};Object.defineProperty(jS,"__esModule",{value:!0});var GS=_S;function KS(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var VS={data:Buffer.alloc(0),dataLength:0,sequence:0};jS.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([KS(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var WS={};Object.defineProperty(WS,"__esModule",{value:!0});var $S=Object.assign||function(t){for(var e=1;e>8;return YS.find((function(t){return t.productIdMM===r}))},WS.identifyProductName=function(t){var e=XS[t];return YS.find((function(t){return t.id===e}))};var JS=[],QS={};for(var ZS in zS){var tI=zS[ZS],eI=tI.bluetoothSpec;if(eI)for(var rI=0;rI0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",lI());case 6:case"end":return t.stop()}}),t,this)}))),function(){return cI.apply(this,arguments)});var dI=WS;function yI(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var gI=[{vendorId:dI.ledgerUSBVendorId}];aI.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(bS,"__esModule",{value:!0});var vI=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,wI.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,EI.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,EI.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new _I.DisconnectedDeviceDuringOperation(e.message);throw e}))}},kI=bS.default=OI,AI=Object.freeze(u({__proto__:null,default:kI},[bS]));t.Btc=wS,t.TransportWebUSB=AI,Object.defineProperty(t,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From e9088ea96bdc5bf83696ed4aabf687350684e054 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 14:30:31 +1100 Subject: [PATCH 09/78] ... --- js/ledger.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index b62b905a..c301047c 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,9 +2,9 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("crypto"),require("buffer"),require("stream"),require("events"),require("util")):"function"==typeof define&&define.amd?define(["exports","crypto","buffer","stream","events","util"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={},t.require$$0$1,t.require$$0$2,t.require$$0$3,t.require$$0$4,t.require$$1)}(this,(function(t,e,r,n,i,o){"use strict";function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function u(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var a=s(e),h=s(r),f=s(n),c=s(i),l=s(o),p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof g?e:g,o=Object.create(i.prototype),s=new k(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return M()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===y)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===y)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",y={};function g(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(A([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=g.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return y;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return y}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,y;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,y):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function P(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function A(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),P(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;P(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:A(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),y}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const d=2147483648;var y=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=d)throw new Error("Invalid child index");if("h"===o[2]||"H"===o[2]||"'"===o[2])n[i]+=d;else if(0!=o[2].length)throw new Error("Invalid modifier")}return new y(n)},y.prototype.toPathArray=function(){return this.path},y.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var g=y,v=a.default.createHash,m={exports:{}}; +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof y?e:y,o=Object.create(i.prototype),s=new k(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return M()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function y(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(P([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=y.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function A(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function P(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),A(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;A(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:P(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const i=2147483648;var o=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=i)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[s]+=i;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new o(n)},o.prototype.toPathArray=function(){return this.path},o.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var s=o,u=n(Object.freeze({__proto__:null,default:{}})),a=u.createHash,h={exports:{}},f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p=!1;function d(){p=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+f[i>>12&63]+f[i>>6&63]+f[63&i]);return o.join("")}function y(t){var e;p||d();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=f[e>>2],i+=f[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=f[e>>10],i+=f[e>>4&63],i+=f[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function m(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var w={}.toString,b=Array.isArray||function(t){return"[object Array]"==w.call(t)};I.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=_();function _(){return I.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function S(t,e){if(_()=_())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_().toString(16)+" bytes");return 0|t}function M(t){return!(null==t||!t._isBuffer)}function x(t,e){if(M(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return it(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ot(t).length;default:if(n)return it(t).length;e=(""+e).toLowerCase(),n=!0}}function R(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return $(this,e,r);case"utf8":case"utf-8":return G(this,e,r);case"ascii":return W(this,e,r);case"latin1":case"binary":return V(this,e,r);case"base64":return q(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function N(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=I.from(e,n)),M(e))return 0===e.length?-1:C(t,e,r,n,i);if("number"==typeof e)return e&=255,I.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):C(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function C(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function q(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function G(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=K)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},I.prototype.compare=function(t,e,r,n,i){if(!M(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return L(this,t,e,r);case"utf8":case"utf-8":return U(this,t,e,r);case"ascii":return D(this,t,e,r);case"latin1":case"binary":return H(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var K=4096;function W(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!M(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Z(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function Q(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function tt(t,e,r,n,i){return i||Q(t,0,r,4),m(t,e,r,n,23,4),r+4}function et(t,e,r,n,i){return i||Q(t,0,r,8),m(t,e,r,n,52,8),r+8}I.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},I.prototype.readUInt8=function(t,e){return e||X(t,1,this.length),this[t]},I.prototype.readUInt16LE=function(t,e){return e||X(t,2,this.length),this[t]|this[t+1]<<8},I.prototype.readUInt16BE=function(t,e){return e||X(t,2,this.length),this[t]<<8|this[t+1]},I.prototype.readUInt32LE=function(t,e){return e||X(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},I.prototype.readUInt32BE=function(t,e){return e||X(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},I.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},I.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},I.prototype.readInt8=function(t,e){return e||X(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},I.prototype.readInt16LE=function(t,e){e||X(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt16BE=function(t,e){e||X(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt32LE=function(t,e){return e||X(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},I.prototype.readInt32BE=function(t,e){return e||X(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},I.prototype.readFloatLE=function(t,e){return e||X(t,4,this.length),v(this,t,!0,23,4)},I.prototype.readFloatBE=function(t,e){return e||X(t,4,this.length),v(this,t,!1,23,4)},I.prototype.readDoubleLE=function(t,e){return e||X(t,8,this.length),v(this,t,!0,52,8)},I.prototype.readDoubleBE=function(t,e){return e||X(t,8,this.length),v(this,t,!1,52,8)},I.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},I.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},I.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Z(this,t,e,!0),e+4},I.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},I.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},I.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},I.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Z(this,t,e,!0),e+4},I.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeFloatLE=function(t,e,r){return tt(this,t,e,!0,r)},I.prototype.writeFloatBE=function(t,e,r){return tt(this,t,e,!1,r)},I.prototype.writeDoubleLE=function(t,e,r){return et(this,t,e,!0,r)},I.prototype.writeDoubleBE=function(t,e,r){return et(this,t,e,!1,r)},I.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!I.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ot(t){return function(t){var e,r,n,i,o,s;p||d();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new l(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(rt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function st(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ut(t){return null!=t&&(!!t._isBuffer||at(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&at(t.slice(0,0))}(t))}function at(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ht=n(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:I,SlowBuffer:function(t){return+t!=t&&(t=0),I.alloc(+t)},isBuffer:ut})); /*! safe-buffer. MIT License. Feross Aboukhadijeh */ -!function(t,e){var r=h.default,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(m,m.exports);var w=m.exports.Buffer;var b=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=w.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var y=n;p!==o;)d[y++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=w.from(e)),!w.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var y=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var y=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?y+n:h[l-y.length]+y+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,y=p>>>13,g=0|s[2],v=8191&g,m=g>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,P=T>>>13,k=0|s[6],A=8191&k,M=k>>>13,x=0|s[7],N=8191&x,R=x>>>13,B=0|s[8],C=8191&B,U=B>>>13,L=0|s[9],D=8191&L,H=L>>>13,F=0|u[0],q=8191&F,j=F>>>13,G=0|u[1],K=8191&G,V=G>>>13,W=0|u[2],$=8191&W,z=W>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Q=0|u[4],Z=8191&Q,tt=Q>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,yt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var gt=(h+(n=Math.imul(c,q))|0)+((8191&(i=(i=Math.imul(c,j))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,j))+(i>>>13)|0)+(gt>>>26)|0,gt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,j))+Math.imul(y,q)|0,o=Math.imul(y,j);var vt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,V)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,j))+Math.imul(m,q)|0,o=Math.imul(m,j),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,V)|0)+Math.imul(y,K)|0,o=o+Math.imul(y,V)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,j))+Math.imul(E,q)|0,o=Math.imul(E,j),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,V)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,V)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(y,$)|0,o=o+Math.imul(y,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,j))+Math.imul(I,q)|0,o=Math.imul(I,j),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,V)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,V)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(y,Y)|0,o=o+Math.imul(y,J)|0;var bt=(h+(n=n+Math.imul(c,Z)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Z)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,j))+Math.imul(P,q)|0,o=Math.imul(P,j),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,V)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Z)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(A,q),i=(i=Math.imul(A,j))+Math.imul(M,q)|0,o=Math.imul(M,j),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Z)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Z)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(y,rt)|0,o=o+Math.imul(y,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,j))+Math.imul(R,q)|0,o=Math.imul(R,j),n=n+Math.imul(A,K)|0,i=(i=i+Math.imul(A,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(P,$)|0,o=o+Math.imul(P,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Z)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Z)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(y,ot)|0,o=o+Math.imul(y,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,q),i=(i=Math.imul(C,j))+Math.imul(U,q)|0,o=Math.imul(U,j),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(A,$)|0,i=(i=i+Math.imul(A,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(P,Y)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Z)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(y,at)|0,o=o+Math.imul(y,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,q),i=(i=Math.imul(D,j))+Math.imul(H,q)|0,o=Math.imul(H,j),n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(R,$)|0,o=o+Math.imul(R,z)|0,n=n+Math.imul(A,Y)|0,i=(i=i+Math.imul(A,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Z)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(y,ct)|0,o=o+Math.imul(y,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,yt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,yt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,V))+Math.imul(H,K)|0,o=Math.imul(H,V),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Y)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,tt)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(P,rt)|0,o=o+Math.imul(P,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,yt)|0)+Math.imul(y,dt)|0))<<13)|0;h=((o=o+Math.imul(y,yt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,tt)|0,n=n+Math.imul(A,rt)|0,i=(i=i+Math.imul(A,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(P,ot)|0,o=o+Math.imul(P,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var Pt=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,yt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,yt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Z)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(R,rt)|0,o=o+Math.imul(R,nt)|0,n=n+Math.imul(A,ot)|0,i=(i=i+Math.imul(A,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(P,at)|0,o=o+Math.imul(P,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,yt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,yt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Z),i=(i=Math.imul(D,tt))+Math.imul(H,Z)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(R,ot)|0,o=o+Math.imul(R,st)|0,n=n+Math.imul(A,at)|0,i=(i=i+Math.imul(A,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(P,ct)|0,o=o+Math.imul(P,lt)|0;var At=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,yt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,yt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(R,at)|0,o=o+Math.imul(R,ht)|0,n=n+Math.imul(A,ct)|0,i=(i=i+Math.imul(A,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,yt)|0)+Math.imul(P,dt)|0))<<13)|0;h=((o=o+Math.imul(P,yt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(R,ct)|0,o=o+Math.imul(R,lt)|0;var xt=(h+(n=n+Math.imul(A,dt)|0)|0)+((8191&(i=(i=i+Math.imul(A,yt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,yt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,yt)|0)+Math.imul(R,dt)|0))<<13)|0;h=((o=o+Math.imul(R,yt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Rt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,yt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,yt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,yt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,yt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=gt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=Pt,a[12]=kt,a[13]=At,a[14]=Mt,a[15]=xt,a[16]=Nt,a[17]=Rt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new y).mulp(t,e,r)}function y(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},y.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},y.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,y=1;0==(n.words[0]&y)&&d<26;++d,y<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var y=p,g=0;0!==y.cmp(u);g++)y=y.redSqr();r(g=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,p)}(q);var j={},G="6.5.4",K={},V=W;function W(t,e){if(!t)throw new Error(e||"Assertion failed")}W.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var $={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}($),function(t){var e=t,r=q.exports,n=V,i=$;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(K);var z,X={exports:{}};function Y(t){this.rand=t}if(X.exports=function(t){return z||(z=new Y(null)),z.generate(t)},X.exports.Rand=Y,Y.prototype.generate=function(t){return this._rand(t)},Y.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ot=it;function st(t,e){this.curve=t,this.type=e,this.precomputed=null}it.prototype.point=function(){throw new Error("Not implemented")},it.prototype.validate=function(){throw new Error("Not implemented")},it.prototype._fixedNafMul=function(t,e){nt(t.precomputed);var r=t._getDoubles(),n=et(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];nt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},it.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var y=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(y[1]=e[p].add(e[d]),y[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(y[1]=e[p].toJ().mixedAdd(e[d]),y[2]=e[p].add(e[d].neg())):(y[1]=e[p].toJ().mixedAdd(e[d]),y[2]=e[p].toJ().mixedAdd(e[d].neg()));var g=[-3,-1,-5,-7,0,7,5,1,3],v=rt(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},st.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},yt.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},yt.prototype.pointFromX=function(t,e){(t=new ct(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},yt.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},yt.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},vt.prototype.isInfinity=function(){return this.inf},vt.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},vt.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},vt.prototype.getX=function(){return this.x.fromRed()},vt.prototype.getY=function(){return this.y.fromRed()},vt.prototype.mul=function(t){return t=new ct(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},vt.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},vt.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},vt.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},vt.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},vt.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},lt(mt,pt.BasePoint),yt.prototype.jpoint=function(t,e,r){return new mt(this,t,e,r)},mt.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},mt.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},mt.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},mt.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},mt.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},mt.prototype.inspect=function(){return this.isInfinity()?"":""},mt.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var wt=q.exports,bt=ut.exports,Et=ot,_t=K;function St(t){Et.call(this,"mont",t),this.a=new wt(t.a,16).toRed(this.red),this.b=new wt(t.b,16).toRed(this.red),this.i4=new wt(4).toRed(this.red).redInvm(),this.two=new wt(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}bt(St,Et);var It=St;function Tt(t,e,r){Et.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new wt(e,16),this.z=new wt(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}St.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},bt(Tt,Et.BasePoint),St.prototype.decodePoint=function(t,e){return this.point(_t.toArray(t,e),1)},St.prototype.point=function(t,e){return new Tt(this,t,e)},St.prototype.pointFromJSON=function(t){return Tt.fromJSON(this,t)},Tt.prototype.precompute=function(){},Tt.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Tt.fromJSON=function(t,e){return new Tt(t,e[0],e[1]||t.one)},Tt.prototype.inspect=function(){return this.isInfinity()?"":""},Tt.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Tt.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},Tt.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},Tt.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},Tt.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Tt.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},Tt.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Tt.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Ot=K,Pt=q.exports,kt=ut.exports,At=ot,Mt=Ot.assert;function xt(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,At.call(this,"edwards",t),this.a=new Pt(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new Pt(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new Pt(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Mt(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}kt(xt,At);var Nt=xt;function Rt(t,e,r,n,i){At.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new Pt(e,16),this.y=new Pt(r,16),this.z=n?new Pt(n,16):this.curve.one,this.t=i&&new Pt(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}xt.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},xt.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},xt.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},xt.prototype.pointFromX=function(t,e){(t=new Pt(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},xt.prototype.pointFromY=function(t,e){(t=new Pt(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},xt.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},kt(Rt,At.BasePoint),xt.prototype.pointFromJSON=function(t){return Rt.fromJSON(this,t)},xt.prototype.point=function(t,e,r,n){return new Rt(this,t,e,r,n)},Rt.fromJSON=function(t,e){return new Rt(t,e[0],e[1],e[2])},Rt.prototype.inspect=function(){return this.isInfinity()?"":""},Rt.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Rt.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Rt.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Rt.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Rt.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Rt.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Rt.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Rt.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Rt.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Rt.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Rt.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Rt.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Rt.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Rt.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Rt.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Rt.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Rt.prototype.toP=Rt.prototype.normalize,Rt.prototype.mixedAdd=Rt.prototype.add,function(t){var e=t;e.base=ot,e.short=gt,e.mont=It,e.edwards=Nt}(Q);var Bt={},Ct={},Ut={},Lt=V,Dt=ut.exports;function Ht(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function Ft(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function qt(t){return 1===t.length?"0"+t:t}function jt(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ut.inherits=Dt,Ut.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Ht(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ut.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ut.rotr32=function(t,e){return t>>>e|t<<32-e},Ut.rotl32=function(t,e){return t<>>32-e},Ut.sum32=function(t,e){return t+e>>>0},Ut.sum32_3=function(t,e,r){return t+e+r>>>0},Ut.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ut.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ut.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ut.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ut.sum64_lo=function(t,e,r,n){return e+n>>>0},Ut.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ut.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ut.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ut.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ut.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ut.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ut.shr64_hi=function(t,e,r){return t>>>r},Ut.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Gt={},Kt=Ut,Vt=V;function Wt(){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}Gt.BlockHash=Wt,Wt.prototype.update=function(t,e){if(t=Kt.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Kt.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},zt.g1_256=function(t){return Xt(t,17)^Xt(t,19)^t>>>10};var Zt=Ut,te=Gt,ee=zt,re=Zt.rotl32,ne=Zt.sum32,ie=Zt.sum32_5,oe=ee.ft_1,se=te.BlockHash,ue=[1518500249,1859775393,2400959708,3395469782];function ae(){if(!(this instanceof ae))return new ae;se.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Zt.inherits(ae,se);var he=ae;ae.blockSize=512,ae.outSize=160,ae.hmacStrength=80,ae.padLength=64,ae.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),kr(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Cr=Br;Br.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},Br.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Nr.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Fr=q.exports,qr=K,jr=qr.assert;function Gr(t,e){if(t instanceof Gr)return t;this._importDER(t,e)||(jr(t.r&&t.s,"Signature without r or s"),this.r=new Fr(t.r,16),this.s=new Fr(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Kr=Gr;function Vr(){this.place=0}function Wr(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function $r(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Gr.prototype._importDER=function(t,e){t=qr.toArray(t,e);var r=new Vr;if(48!==t[r.place++])return!1;var n=Wr(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Wr(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Wr(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Fr(o),this.s=new Fr(u),this.recoveryParam=null,!0},Gr.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=$r(e),r=$r(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];zr(n,e.length),(n=n.concat(e)).push(2),zr(n,r.length);var i=n.concat(r),o=[48];return zr(o,i.length),o=o.concat(i),qr.encode(o,t)};var Xr=q.exports,Yr=Cr,Jr=K,Qr=Bt,Zr=X.exports,tn=Jr.assert,en=Hr,rn=Kr;function nn(t){if(!(this instanceof nn))return new nn(t);"string"==typeof t&&(tn(Object.prototype.hasOwnProperty.call(Qr,t),"Unknown curve "+t),t=Qr[t]),t instanceof Qr.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var on=nn;nn.prototype.keyPair=function(t){return new en(this,t)},nn.prototype.keyFromPrivate=function(t,e){return en.fromPrivate(this,t,e)},nn.prototype.keyFromPublic=function(t,e){return en.fromPublic(this,t,e)},nn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Yr({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Zr(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Xr(2));;){var i=new Xr(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},nn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},nn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Xr(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Yr({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Xr(1)),h=0;;h++){var f=n.k?n.k(h):new Xr(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var y=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),y^=1),new rn({r:p,s:d,recoveryParam:y})}}}}}},nn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Xr(t,16)),r=this.keyFromPublic(r,n);var i=(e=new rn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},nn.prototype.recoverPubKey=function(t,e,r,n){tn((3&r)===r,"The recovery param is more than two bits"),e=new rn(e,n);var i=this.n,o=new Xr(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},nn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new rn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var sn=K,un=sn.assert,an=sn.parseBytes,hn=sn.cachedProperty;function fn(t,e){this.eddsa=t,this._secret=an(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=an(e.pub)}fn.fromPublic=function(t,e){return e instanceof fn?e:new fn(t,{pub:e})},fn.fromSecret=function(t,e){return e instanceof fn?e:new fn(t,{secret:e})},fn.prototype.secret=function(){return this._secret},hn(fn,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),hn(fn,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),hn(fn,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),hn(fn,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),hn(fn,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),hn(fn,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),fn.prototype.sign=function(t){return un(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},fn.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},fn.prototype.getSecret=function(t){return un(this._secret,"KeyPair is public only"),sn.encode(this.secret(),t)},fn.prototype.getPublic=function(t){return sn.encode(this.pubBytes(),t)};var cn=fn,ln=q.exports,pn=K,dn=pn.assert,yn=pn.cachedProperty,gn=pn.parseBytes;function vn(t,e){this.eddsa=t,"object"!=typeof e&&(e=gn(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),dn(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ln&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}yn(vn,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),yn(vn,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),yn(vn,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),yn(vn,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),vn.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},vn.prototype.toHex=function(){return pn.encode(this.toBytes(),"hex").toUpperCase()};var mn=vn,wn=Ct,bn=Bt,En=K,_n=En.assert,Sn=En.parseBytes,In=cn,Tn=mn;function On(t){if(_n("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof On))return new On(t);t=bn[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=wn.sha512}var Pn=On;On.prototype.sign=function(t,e){t=Sn(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},On.prototype.verify=function(t,e,r){t=Sn(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},On.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Zn(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Cn)&&(!(n.compare(Ln)>=0)&&(4===e&&65===t.length))}function zn(t){return 4!==t[0]}function Xn(t){return!!Vn(t)&&(t.compare(Cn)>0&&t.compare(Un)<0)}function Yn(t,e){return void 0===t&&void 0!==e?zn(e):void 0===t||t}function Jn(t){return new Nn(t)}function Qn(t){return t.toArrayLike(Buffer,"be",32)}function Zn(t){return Rn.curve.decodePoint(t)}function ti(t,e){return Buffer.from(t._encode(e))}function ei(t,e,r){if(!Vn(t))throw new TypeError(Kn);if(!Xn(e))throw new TypeError(qn);if(void 0!==r&&!Vn(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Jn(e),i=Jn(t);let o,s;Bn(t,e,(function(t){const e=Jn(t),r=Fn.mul(e);return!r.isInfinity()&&(o=r.x.umod(Dn),0!==o.isZero()&&(s=e.invm(Dn).mul(i.add(n.mul(o))).umod(Dn),0!==s.isZero()))}),Xn,r),s.cmp(Hn)>0&&(s=Dn.sub(s));const u=Buffer.allocUnsafe(64);return Qn(o).copy(u,0),Qn(s).copy(u,32),u}var ri={isPoint:$n,isPointCompressed:function(t){return!!$n(t)&&zn(t)},isPrivate:Xn,pointAdd:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!$n(e))throw new TypeError(jn);const n=Zn(t),i=Zn(e),o=n.add(i);return o.isInfinity()?null:ti(o,Yn(r,t))},pointAddScalar:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!Wn(e))throw new TypeError(Gn);const n=Yn(r,t),i=Zn(t);if(0===e.compare(Cn))return ti(i,n);const o=Jn(e),s=Fn.mul(o),u=i.add(s);return u.isInfinity()?null:ti(u,n)},pointCompress:function(t,e){if(!$n(t))throw new TypeError(jn);const r=Zn(t);if(r.isInfinity())throw new TypeError(jn);return ti(r,Yn(e,t))},pointFromScalar:function(t,e){if(!Xn(t))throw new TypeError(qn);const r=Jn(t),n=Fn.mul(r);return n.isInfinity()?null:ti(n,Yn(e))},pointMultiply:function(t,e,r){if(!$n(t))throw new TypeError(jn);if(!Wn(e))throw new TypeError(Gn);const n=Yn(r,t),i=Zn(t),o=Jn(e),s=i.mul(o);return s.isInfinity()?null:ti(s,n)},privateAdd:function(t,e){if(!Xn(t))throw new TypeError(qn);if(!Wn(e))throw new TypeError(Gn);const r=Jn(t),n=Jn(e),i=Qn(r.add(n).umod(Dn));return Xn(i)?i:null},privateSub:function(t,e){if(!Xn(t))throw new TypeError(qn);if(!Wn(e))throw new TypeError(Gn);const r=Jn(t),n=Jn(e),i=Qn(r.sub(n).umod(Dn));return Xn(i)?i:null},sign:function(t,e){return ei(t,e)},signWithEntropy:function(t,e,r){return ei(t,e,r)},verify:function(t,e,r,n){if(!Vn(t))throw new TypeError(Kn);if(!$n(e))throw new TypeError(jn);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Un)<0&&r.compare(Un)<0}(r))throw new TypeError("Expected Signature");const i=Zn(e),o=Jn(r.slice(0,32)),s=Jn(r.slice(32,64));if(n&&s.cmp(Hn)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Jn(t),a=s.invm(Dn),h=u.mul(a).umod(Dn),f=o.mul(a).umod(Dn),c=Fn.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Dn).eq(o)}};try{F.exports=require("./native")}catch(t){F.exports=ri}var ni={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var ii in ni.Null=ni.Nil,ni)ni[ii].toJSON=function(t){return t}.bind(null,ii);var oi=ni,si=oi;function ui(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function ai(t){return si.Nil(t)?"":ui(t.constructor)}function hi(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function fi(t){return si.Function(t)?t.toJSON?t.toJSON():ui(t):si.Array(t)?"Array":t&&si.Object(t)?"Object":void 0!==t?t:""}function ci(t,e,r){var n=function(t){return si.Function(t)?"":si.String(t)?JSON.stringify(t):t&&si.Object(t)?"":t}(e);return"Expected "+fi(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function li(t,e,r){r=r||ai(e),this.message=ci(t,e,r),hi(this,li),this.__type=t,this.__value=e,this.__valueTypeName=r}function pi(t,e,r,n,i){t?(i=i||ai(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ci('property "'+fi(r)+o+fi(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',hi(this,li),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}li.prototype=Object.create(Error.prototype),li.prototype.constructor=li,pi.prototype=Object.create(Error.prototype),pi.prototype.constructor=li;var di={TfTypeError:li,TfPropertyTypeError:pi,tfCustomError:function(t,e){return new li(t,{},e)},tfSubError:function(t,e,r){return t instanceof pi?(e=e+"."+t.__property,t=new pi(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof li&&(t=new pi(t.__type,e,r,t.__value,t.__valueTypeName)),hi(t),t},tfJSON:fi,getValueTypeName:ai},yi=oi,gi=di;function vi(t){return Buffer.isBuffer(t)}function mi(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function wi(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw gi.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var bi=wi.bind(null,yi.Array),Ei=wi.bind(null,vi),_i=wi.bind(null,mi),Si=wi.bind(null,yi.String);var Ii=Math.pow(2,53)-1;var Ti={ArrayN:bi,Buffer:vi,BufferN:Ei,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:mi,HexN:_i,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-Ii&&t<=Ii&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=Ii&&Math.floor(t)===t}};for(var Oi in Ti)Ti[Oi].toJSON=function(t){return t}.bind(null,Oi);var Pi=Ti,ki=oi,Ai=di.tfJSON,Mi=di.TfTypeError,xi=di.TfPropertyTypeError,Ni=di.tfSubError,Ri=di.getValueTypeName,Bi={arrayOf:function(t,e){function r(r,n){return!!ki.Array(r)&&(!ki.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return Ui(t,e,n)}catch(t){throw Ni(t,r)}}))))))}return t=Ci(t),e=e||{},r.toJSON=function(){var r="["+Ai(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return ki.Nil(r)||e(r,n,t)}return e=Ci(e),r.toJSON=function(){return"?"+Ai(e)},r},map:function(t,e){function r(r,n){if(!ki.Object(r))return!1;if(ki.Nil(r))return!1;for(var i in r){try{e&&Ui(e,i,n)}catch(t){throw Ni(t,i,"key")}try{var o=r[i];Ui(t,o,n)}catch(t){throw Ni(t,i)}}return!0}return t=Ci(t),e&&(e=Ci(e)),r.toJSON=e?function(){return"{"+Ai(e)+": "+Ai(t)+"}"}:function(){return"{"+Ai(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ci(t[r]);function n(t,r){if(!ki.Object(t))return!1;if(ki.Nil(t))return!1;var n;try{for(n in e){Ui(e[n],t[n],r)}}catch(t){throw Ni(t,n)}if(r)for(n in t)if(!e[n])throw new xi(void 0,n);return!0}return n.toJSON=function(){return Ai(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return t.some((function(t){try{return Ui(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Ai).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return t.every((function(t){try{return Ui(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Ai).join(" & ")},e},quacksLike:function(t){function e(e){return t===Ri(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ci);function e(e,r){return!ki.Nil(e)&&(!ki.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return Ui(t,e[n],r)}catch(t){throw Ni(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Ai).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ci(t){if(ki.String(t))return"?"===t[0]?Bi.maybe(t.slice(1)):ki[t]||Bi.quacksLike(t);if(t&&ki.Object(t)){if(ki.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Bi.arrayOf(t[0])}return Bi.object(t)}return ki.Function(t)?t:Bi.value(t)}function Ui(t,e,r,n){if(ki.Function(t)){if(t(e,r))return!0;throw new Mi(n||t,e)}return Ui(Ci(t),e,r)}for(var Li in Bi.oneOf=Bi.anyOf,ki)Ui[Li]=ki[Li];for(Li in Bi)Ui[Li]=Bi[Li];var Di=Pi;for(Li in Di)Ui[Li]=Di[Li];Ui.compile=Ci,Ui.TfTypeError=Mi,Ui.TfPropertyTypeError=xi;var Hi=Ui,Fi=O;function qi(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function ji(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Gi={decode:function(t,e){return qi(Fi.decode(t),e)},decodeRaw:qi,encode:function(t,e,r){return"number"==typeof t?Fi.encode(ji(t,e,r)):Fi.encode(ji(t.version,t.privateKey,t.compressed))},encodeRaw:ji};Object.defineProperty(C,"__esModule",{value:!0});const Ki=U,Vi=O,Wi=F.exports,$i=Hi,zi=Gi,Xi=$i.BufferN(32),Yi=$i.compile({wif:$i.UInt8,bip32:{public:$i.UInt32,private:$i.UInt32}}),Ji={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Qi=2147483648,Zi=Math.pow(2,31)-1;function to(t){return $i.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function eo(t){return $i.UInt32(t)&&t<=Zi}class ro{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,$i(Yi,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Wi.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Ki.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return oo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Vi.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return zi.encode(this.network.wif,this.privateKey,!0)}derive(t){$i($i.UInt32,t);const e=t>=Qi,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Ki.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Wi.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Wi.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=oo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Wi.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=io(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return $i(eo,t),this.derive(t+Qi)}derivePath(t){$i(to,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Wi.sign(t,this.privateKey);{let e=Wi.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Wi.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Wi.verify(t,this.publicKey,e)}}function no(t,e,r){return io(t,e,r)}function io(t,e,r,n,i,o){if($i({privateKey:Xi,chainCode:Xi},{privateKey:t,chainCode:e}),r=r||Ji,!Wi.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new ro(t,void 0,e,r,n,i,o)}function oo(t,e,r,n,i,o){if($i({publicKey:$i.BufferN(33),chainCode:Xi},{publicKey:t,chainCode:e}),r=r||Ji,!Wi.isPoint(t))throw new TypeError("Point is not on the curve");return new ro(void 0,t,e,r,n,i,o)}C.fromBase58=function(t,e){const r=Vi.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Ji;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=io(r.slice(46,78),u,e,i,s,o)}else{a=oo(r.slice(45,78),u,e,i,s,o)}return a},C.fromPrivateKey=no,C.fromPublicKey=function(t,e,r){return oo(t,e,r)},C.fromSeed=function(t,e){if($i($i.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Ji;const r=Ki.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return no(r.slice(0,32),r.slice(32),e)},Object.defineProperty(B,"__esModule",{value:!0});var so=C;B.fromSeed=so.fromSeed,B.fromBase58=so.fromBase58,B.fromPublicKey=so.fromPublicKey,B.fromPrivateKey=so.fromPrivateKey;var uo={},ao={};Object.defineProperty(ao,"__esModule",{value:!0}),ao.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ao.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ao.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ho={},fo={},co={},lo={};Object.defineProperty(lo,"__esModule",{value:!0}),lo.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var po={},yo={};Object.defineProperty(yo,"__esModule",{value:!0});const go=Hi,vo=Math.pow(2,31)-1;function mo(t){return go.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}yo.UInt31=function(t){return go.UInt32(t)&&t<=vo},yo.BIP32Path=mo,mo.toJSON=()=>"BIP32 derivation path",yo.Signer=function(t){return(go.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};yo.Satoshi=function(t){return go.UInt53(t)&&t<=21e14},yo.ECPoint=go.quacksLike("Point"),yo.Network=go.compile({messagePrefix:go.oneOf(go.Buffer,go.String),bip32:{public:go.UInt32,private:go.UInt32},pubKeyHash:go.UInt8,scriptHash:go.UInt8,wif:go.UInt8}),yo.Buffer256bit=go.BufferN(32),yo.Hash160bit=go.BufferN(20),yo.Hash256bit=go.BufferN(32),yo.Number=go.Number,yo.Array=go.Array,yo.Boolean=go.Boolean,yo.String=go.String,yo.Buffer=go.Buffer,yo.Hex=go.Hex,yo.maybe=go.maybe,yo.tuple=go.tuple,yo.UInt8=go.UInt8,yo.UInt32=go.UInt32,yo.Function=go.Function,yo.BufferN=go.BufferN,yo.Null=go.Null,yo.oneOf=go.oneOf;var wo=m.exports.Buffer;var bo={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=wo.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(po,"__esModule",{value:!0});const Eo=yo,_o=bo,So=Hi,Io=Buffer.alloc(1,0);function To(t){let e=0;for(;0===t[e];)++e;return e===t.length?Io:128&(t=t.slice(e))[0]?Buffer.concat([Io,t],1+t.length):t}function Oo(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}po.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=_o.decode(t.slice(0,-1)),i=Oo(n.r),o=Oo(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},po.encode=function(t,e){So({signature:Eo.BufferN(64),hashType:Eo.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=To(t.slice(0,32)),o=To(t.slice(32,64));return Buffer.concat([_o.encode(i,o),n])};var Po={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ko=Po;function Ao(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ko.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ko.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},xo=Po,No={};for(var Ro in xo){No[xo[Ro]]=Ro}var Bo=No;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=lo,r=po,n=yo,i=bo,o=F.exports,s=Mo,u=Hi;t.OPS=Po;const a=Bo,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function y(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function g(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=y,t.decompile=g,t.toASM=function(t){return p(t)&&(t=g(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),y(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=g(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(co);var Co={};Object.defineProperty(Co,"__esModule",{value:!0}),Co.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Co.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(fo,"__esModule",{value:!0});const Uo=ao,Lo=co,Do=Co,Ho=Hi,Fo=Lo.OPS;fo.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ho({network:Ho.maybe(Ho.Object),output:Ho.maybe(Ho.Buffer),data:Ho.maybe(Ho.arrayOf(Ho.Buffer))},t);const r={name:"embed",network:t.network||Uo.bitcoin};if(Do.prop(r,"output",(()=>{if(t.data)return Lo.compile([Fo.OP_RETURN].concat(t.data))})),Do.prop(r,"data",(()=>{if(t.output)return Lo.decompile(t.output).slice(1)})),e.validate&&t.output){const e=Lo.decompile(t.output);if(e[0]!==Fo.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ho.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var qo={};Object.defineProperty(qo,"__esModule",{value:!0});const jo=ao,Go=co,Ko=Co,Vo=Go.OPS,Wo=Hi,$o=F.exports,zo=Vo.OP_RESERVED;function Xo(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}qo.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Go.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Vo.OP_0)}e=Object.assign({validate:!0},e||{}),Wo({network:Wo.maybe(Wo.Object),m:Wo.maybe(Wo.Number),n:Wo.maybe(Wo.Number),output:Wo.maybe(Wo.Buffer),pubkeys:Wo.maybe(Wo.arrayOf($o.isPoint)),signatures:Wo.maybe(Wo.arrayOf(r)),input:Wo.maybe(Wo.Buffer)},t);const n={network:t.network||jo.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Go.decompile(t),n.m=i[0]-zo,n.n=i[i.length-2]-zo,n.pubkeys=i.slice(1,-2))}if(Ko.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Go.compile([].concat(zo+t.m,t.pubkeys,zo+n.n,Vo.OP_CHECKMULTISIG))})),Ko.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Ko.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Ko.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Ko.prop(n,"signatures",(()=>{if(t.input)return Go.decompile(t.input).slice(1)})),Ko.prop(n,"input",(()=>{if(t.signatures)return Go.compile([Vo.OP_0].concat(t.signatures))})),Ko.prop(n,"witness",(()=>{if(n.input)return[]})),Ko.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Wo.Number(i[0]))throw new TypeError("Output is invalid");if(!Wo.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Vo.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>$o.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!Xo(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Vo.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!Xo(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0});const Jo=ao,Qo=co,Zo=Co,ts=Hi,es=Qo.OPS,rs=F.exports;Yo.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ts({network:ts.maybe(ts.Object),output:ts.maybe(ts.Buffer),pubkey:ts.maybe(rs.isPoint),signature:ts.maybe(Qo.isCanonicalScriptSignature),input:ts.maybe(ts.Buffer)},t);const r=Zo.value((()=>Qo.decompile(t.input))),n={name:"p2pk",network:t.network||Jo.bitcoin};if(Zo.prop(n,"output",(()=>{if(t.pubkey)return Qo.compile([t.pubkey,es.OP_CHECKSIG])})),Zo.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Zo.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Zo.prop(n,"input",(()=>{if(t.signature)return Qo.compile([t.signature])})),Zo.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==es.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!rs.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Qo.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var ns={},is={};Object.defineProperty(is,"__esModule",{value:!0});const os=v;function ss(t){try{return os("rmd160").update(t).digest()}catch(e){return os("ripemd160").update(t).digest()}}function us(t){return os("sha256").update(t).digest()}is.ripemd160=ss,is.sha1=function(t){return os("sha1").update(t).digest()},is.sha256=us,is.hash160=function(t){return ss(us(t))},is.hash256=function(t){return us(us(t))},Object.defineProperty(ns,"__esModule",{value:!0});const as=is,hs=ao,fs=co,cs=Co,ls=Hi,ps=fs.OPS,ds=F.exports,ys=O;ns.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ls({network:ls.maybe(ls.Object),address:ls.maybe(ls.String),hash:ls.maybe(ls.BufferN(20)),output:ls.maybe(ls.BufferN(25)),pubkey:ls.maybe(ds.isPoint),signature:ls.maybe(fs.isCanonicalScriptSignature),input:ls.maybe(ls.Buffer)},t);const r=cs.value((()=>{const e=ys.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=cs.value((()=>fs.decompile(t.input))),i=t.network||hs.bitcoin,o={name:"p2pkh",network:i};if(cs.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),ys.encode(t)})),cs.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?as.hash160(t.pubkey||o.pubkey):void 0)),cs.prop(o,"output",(()=>{if(o.hash)return fs.compile([ps.OP_DUP,ps.OP_HASH160,o.hash,ps.OP_EQUALVERIFY,ps.OP_CHECKSIG])})),cs.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),cs.prop(o,"signature",(()=>{if(t.input)return n()[0]})),cs.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return fs.compile([t.signature,t.pubkey])})),cs.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==ps.OP_DUP||t.output[1]!==ps.OP_HASH160||20!==t.output[2]||t.output[23]!==ps.OP_EQUALVERIFY||t.output[24]!==ps.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=as.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!fs.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ds.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=as.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var gs={};Object.defineProperty(gs,"__esModule",{value:!0});const vs=is,ms=ao,ws=co,bs=Co,Es=Hi,_s=ws.OPS,Ss=O;gs.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Es({network:Es.maybe(Es.Object),address:Es.maybe(Es.String),hash:Es.maybe(Es.BufferN(20)),output:Es.maybe(Es.BufferN(23)),redeem:Es.maybe({network:Es.maybe(Es.Object),output:Es.maybe(Es.Buffer),input:Es.maybe(Es.Buffer),witness:Es.maybe(Es.arrayOf(Es.Buffer))}),input:Es.maybe(Es.Buffer),witness:Es.maybe(Es.arrayOf(Es.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||ms.bitcoin);const n={network:r},i=bs.value((()=>{const e=Ss.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=bs.value((()=>ws.decompile(t.input))),s=bs.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:ws.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(bs.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),Ss.encode(t)})),bs.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?vs.hash160(n.redeem.output):void 0)),bs.prop(n,"output",(()=>{if(n.hash)return ws.compile([_s.OP_HASH160,n.hash,_s.OP_EQUAL])})),bs.prop(n,"redeem",(()=>{if(t.input)return s()})),bs.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return ws.compile([].concat(ws.decompile(t.redeem.input),t.redeem.output))})),bs.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),bs.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==_s.OP_HASH160||20!==t.output[1]||t.output[22]!==_s.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=ws.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=vs.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=ws.decompile(t.input);if(!ws.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var Is={},Ts="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Os={},Ps=0;Ps>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Ms(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=As(e)^n>>5}for(e=As(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Ms(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Ns(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Ms(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=As(n)^s,i+=Ts.charAt(s)}for(o=0;o<6;++o)n=As(n);for(n^=1,o=0;o<6;++o){i+=Ts.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Ns(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Ns(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Ns(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Ns(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(Is,"__esModule",{value:!0});const Bs=is,Cs=ao,Us=co,Ls=Co,Ds=Hi,Hs=Us.OPS,Fs=F.exports,qs=Rs,js=Buffer.alloc(0);Is.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ds({address:Ds.maybe(Ds.String),hash:Ds.maybe(Ds.BufferN(20)),input:Ds.maybe(Ds.BufferN(0)),network:Ds.maybe(Ds.Object),output:Ds.maybe(Ds.BufferN(22)),pubkey:Ds.maybe(Fs.isPoint),signature:Ds.maybe(Us.isCanonicalScriptSignature),witness:Ds.maybe(Ds.arrayOf(Ds.Buffer))},t);const r=Ls.value((()=>{const e=qs.decode(t.address),r=e.words.shift(),n=qs.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Cs.bitcoin,i={name:"p2wpkh",network:n};if(Ls.prop(i,"address",(()=>{if(!i.hash)return;const t=qs.toWords(i.hash);return t.unshift(0),qs.encode(n.bech32,t)})),Ls.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Bs.hash160(t.pubkey||i.pubkey):void 0)),Ls.prop(i,"output",(()=>{if(i.hash)return Us.compile([Hs.OP_0,i.hash])})),Ls.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),Ls.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),Ls.prop(i,"input",(()=>{if(i.witness)return js})),Ls.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Hs.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Bs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!Fs.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Us.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!Fs.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Bs.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});const Ks=is,Vs=ao,Ws=co,$s=Co,zs=Hi,Xs=Ws.OPS,Ys=F.exports,Js=Rs,Qs=Buffer.alloc(0);function Zs(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Ys.isPoint(t))}Gs.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),zs({network:zs.maybe(zs.Object),address:zs.maybe(zs.String),hash:zs.maybe(zs.BufferN(32)),output:zs.maybe(zs.BufferN(34)),redeem:zs.maybe({input:zs.maybe(zs.Buffer),network:zs.maybe(zs.Object),output:zs.maybe(zs.Buffer),witness:zs.maybe(zs.arrayOf(zs.Buffer))}),input:zs.maybe(zs.BufferN(0)),witness:zs.maybe(zs.arrayOf(zs.Buffer))},t);const r=$s.value((()=>{const e=Js.decode(t.address),r=e.words.shift(),n=Js.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=$s.value((()=>Ws.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Vs.bitcoin);const o={network:i};if($s.prop(o,"address",(()=>{if(!o.hash)return;const t=Js.toWords(o.hash);return t.unshift(0),Js.encode(i.bech32,t)})),$s.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Ks.sha256(o.redeem.output):void 0)),$s.prop(o,"output",(()=>{if(o.hash)return Ws.compile([Xs.OP_0,o.hash])})),$s.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Qs,witness:t.witness.slice(0,-1)}})),$s.prop(o,"input",(()=>{if(o.witness)return Qs})),$s.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Ws.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Qs,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),$s.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==Xs.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Ws.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Ks.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Ws.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Zs)||t.redeem.output&&(Ws.decompile(t.redeem.output)||[]).some(Zs))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Zs)||(Ws.decompile(e)||[]).some(Zs))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(ho,"__esModule",{value:!0});const tu=fo;ho.embed=tu.p2data;const eu=qo;ho.p2ms=eu.p2ms;const ru=Yo;ho.p2pk=ru.p2pk;const nu=ns;ho.p2pkh=nu.p2pkh;const iu=gs;ho.p2sh=iu.p2sh;const ou=Is;ho.p2wpkh=ou.p2wpkh;const su=Gs;ho.p2wsh=su.p2wsh,Object.defineProperty(uo,"__esModule",{value:!0});const uu=ao,au=ho,hu=co,fu=yo,cu=Rs,lu=O,pu=Hi;function du(t){const e=lu.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function yu(t){const e=cu.decode(t),r=cu.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}uo.fromBase58Check=du,uo.fromBech32=yu,uo.toBase58Check=function(t,e){pu(fu.tuple(fu.Hash160bit,fu.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),lu.encode(r)},uo.toBech32=function(t,e,r){const n=cu.toWords(t);return n.unshift(e),cu.encode(r,n)},uo.fromOutputScript=function(t,e){e=e||uu.bitcoin;try{return au.p2pkh({output:t,network:e}).address}catch(t){}try{return au.p2sh({output:t,network:e}).address}catch(t){}try{return au.p2wpkh({output:t,network:e}).address}catch(t){}try{return au.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(hu.toASM(t)+" has no matching Address")},uo.toOutputScript=function(t,e){let r,n;e=e||uu.bitcoin;try{r=du(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return au.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return au.p2sh({hash:r.hash}).output}else{try{n=yu(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return au.p2wpkh({hash:n.data}).output;if(32===n.data.length)return au.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var gu={},vu=a.default.randomBytes;Object.defineProperty(gu,"__esModule",{value:!0});const mu=ao,wu=yo,bu=F.exports,Eu=vu,_u=Hi,Su=Gi,Iu=_u.maybe(_u.compile({compressed:wu.maybe(wu.Boolean),network:wu.maybe(wu.Network)}));class Tu{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||mu.bitcoin,void 0!==e&&(this.__Q=bu.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=bu.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return Su.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return bu.sign(t,this.__D);{let e=bu.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=bu.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return bu.verify(t,this.publicKey,e)}}function Ou(t,e){if(_u(wu.Buffer256bit,t),!bu.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return _u(Iu,e),new Tu(t,void 0,e)}gu.fromPrivateKey=Ou,gu.fromPublicKey=function(t,e){return _u(bu.isPoint,t),_u(Iu,e),new Tu(void 0,t,e)},gu.fromWIF=function(t,e){const r=Su.decode(t),n=r.version;if(wu.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||mu.bitcoin,n!==e.wif)throw new Error("Invalid network version");return Ou(r.privateKey,{compressed:r.compressed,network:e})},gu.makeRandom=function(t){_u(Iu,t),void 0===t&&(t={});const e=t.rng||Eu;let r;do{r=e(32),_u(wu.Buffer256bit,r)}while(!bu.isPrivate(r));return Ou(r,t)};var Pu={},ku={},Au=m.exports.Buffer;function Mu(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function xu(t){return Mu(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Nu={encode:function t(e,r,n){if(Mu(e),r||(r=Au.allocUnsafe(xu(e))),!Au.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Au.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Mu(o),o},encodingLength:xu};Object.defineProperty(ku,"__esModule",{value:!0});const Ru=yo,Bu=Hi,Cu=Nu;function Uu(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function Lu(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Uu(n+r,9007199254740991),n+r}function Du(t,e,r){return Uu(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}ku.readUInt64LE=Lu,ku.writeUInt64LE=Du,ku.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};ku.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Bu(Ru.tuple(Ru.Buffer,Ru.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Lu(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Cu.decode(this.buffer,this.offset);return this.offset+=Cu.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Wu.encodingLength(this.ins.length)+Wu.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+$u(e.script)),0)+this.outs.reduce(((t,e)=>t+8+$u(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Wu.encodingLength(e)+t.reduce(((t,e)=>t+$u(e)),0)}(e.witness)),0):0)}clone(){const t=new ta;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Vu(Ku.tuple(Ku.UInt32,Ku.Buffer,Ku.Number),arguments),t>=this.ins.length)return Ju;const n=ju.compile(ju.decompile(e).filter((t=>t!==Gu.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===ta.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===ta.SIGHASH_SINGLE){if(t>=this.outs.length)return Ju;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&ta.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=zu})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),qu.hash256(o)}hashForWitnessV0(t,e,r,n){Vu(Ku.tuple(Ku.UInt32,Ku.Buffer,Ku.Satoshi,Ku.UInt32),arguments);let i,o=Buffer.from([]),s=Yu,u=Yu,a=Yu;if(n&ta.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new Fu.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=qu.hash256(o)),n&ta.SIGHASH_ANYONECANPAY||(31&n)===ta.SIGHASH_SINGLE||(31&n)===ta.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new Fu.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=qu.hash256(o)),(31&n)!==ta.SIGHASH_SINGLE&&(31&n)!==ta.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+$u(e.script)),0);o=Buffer.allocUnsafe(t),i=new Fu.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=qu.hash256(o)}else if((31&n)===ta.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}ta.DEFAULT_SEQUENCE=4294967295,ta.SIGHASH_ALL=1,ta.SIGHASH_NONE=2,ta.SIGHASH_SINGLE=3,ta.SIGHASH_ANYONECANPAY=128,ta.ADVANCED_TRANSACTION_MARKER=0,ta.ADVANCED_TRANSACTION_FLAG=1,Hu.Transaction=ta;Object.defineProperty(Pu,"__esModule",{value:!0});const ea=ku,ra=is,na=Hu,ia=yo,oa=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=na.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(sa([{getHash:ia.Function}],t),0===t.length)throw aa;if(e&&!ca(t))throw ha;const r=t.map((t=>t.getHash(e))),n=oa(r,ra.hash256);return e?ra.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ca(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+ua.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return ra.hash256(this.toBuffer(!0))}getId(){return ea.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new ea.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(ua.encode(this.transactions.length,e,r.offset),r.offset+=ua.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=ea.reverseBuffer(this.getHash()),e=fa.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw aa;const t=fa.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw aa;if(!this.hasWitnessCommit())throw ha;const t=fa.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ca(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}Pu.Block=fa;var la={},pa={},da={},ya={},ga={},va={},ma={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(ma);var wa={};Object.defineProperty(wa,"__esModule",{value:!0});const ba=ma;wa.decode=function(t){if(t.key[0]!==ba.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},wa.encode=function(t){const e=Buffer.from([ba.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},wa.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",wa.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},wa.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});const _a=ma;Ea.encode=function(t){return{key:Buffer.from([_a.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var Sa={};Object.defineProperty(Sa,"__esModule",{value:!0});const Ia=ma;Sa.decode=function(t){if(t.key[0]!==Ia.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},Sa.encode=function(t){return{key:Buffer.from([Ia.InputTypes.FINAL_SCRIPTSIG]),value:t}},Sa.expected="Buffer",Sa.check=function(t){return Buffer.isBuffer(t)},Sa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var Ta={};Object.defineProperty(Ta,"__esModule",{value:!0});const Oa=ma;Ta.decode=function(t){if(t.key[0]!==Oa.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},Ta.encode=function(t){return{key:Buffer.from([Oa.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},Ta.expected="Buffer",Ta.check=function(t){return Buffer.isBuffer(t)},Ta.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var Pa={};Object.defineProperty(Pa,"__esModule",{value:!0});const ka=ma;Pa.decode=function(t){if(t.key[0]!==ka.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},Pa.encode=function(t){return{key:Buffer.from([ka.InputTypes.NON_WITNESS_UTXO]),value:t}},Pa.expected="Buffer",Pa.check=function(t){return Buffer.isBuffer(t)},Pa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Aa={};Object.defineProperty(Aa,"__esModule",{value:!0});const Ma=ma;Aa.decode=function(t){if(t.key[0]!==Ma.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Aa.encode=function(t){const e=Buffer.from([Ma.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},Aa.expected="{ pubkey: Buffer; signature: Buffer; }",Aa.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Aa.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var xa={};Object.defineProperty(xa,"__esModule",{value:!0});const Na=ma;xa.decode=function(t){if(t.key[0]!==Na.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},xa.encode=function(t){return{key:Buffer.from([Na.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},xa.expected="string",xa.check=function(t){return"string"==typeof t},xa.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0});const Ba=ma;Ra.decode=function(t){if(t.key[0]!==Ba.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ra.encode=function(t){const e=Buffer.from([Ba.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ra.expected="number",Ra.check=function(t){return"number"==typeof t},Ra.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ca={},Ua={},La={};Object.defineProperty(La,"__esModule",{value:!0});function Da(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Ha(t){return Da(t),t<253?1:t<=65535?3:t<=4294967295?5:9}La.encode=function t(e,r,n){if(Da(e),r||(r=Buffer.allocUnsafe(Ha(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},La.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Da(i),i}},La.encodingLength=Ha,Object.defineProperty(Ua,"__esModule",{value:!0});const Fa=La;function qa(t){const e=t.key.length,r=t.value.length,n=Fa.encodingLength(e),i=Fa.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return Fa.encode(e,o,0),t.key.copy(o,n),Fa.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function ja(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ua.range=t=>[...Array(t).keys()],Ua.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var $a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var za={};Object.defineProperty(za,"__esModule",{value:!0}),za.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0}),Xa.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(va,"__esModule",{value:!0});const Ya=ma,Ja=Sa,Qa=Ta,Za=Pa,th=Aa,eh=xa,rh=Ra,nh=Ca,ih=Wa,oh=$a,sh=za,uh=Xa,ah={unsignedTx:Ea,globalXpub:wa,checkPubkey:oh.makeChecker([])};va.globals=ah;const hh={nonWitnessUtxo:Za,partialSig:th,sighashType:rh,finalScriptSig:Ja,finalScriptWitness:Qa,porCommitment:eh,witnessUtxo:nh,bip32Derivation:ih.makeConverter(Ya.InputTypes.BIP32_DERIVATION),redeemScript:sh.makeConverter(Ya.InputTypes.REDEEM_SCRIPT),witnessScript:uh.makeConverter(Ya.InputTypes.WITNESS_SCRIPT),checkPubkey:oh.makeChecker([Ya.InputTypes.PARTIAL_SIG,Ya.InputTypes.BIP32_DERIVATION])};va.inputs=hh;const fh={bip32Derivation:ih.makeConverter(Ya.OutputTypes.BIP32_DERIVATION),redeemScript:sh.makeConverter(Ya.OutputTypes.REDEEM_SCRIPT),witnessScript:uh.makeConverter(Ya.OutputTypes.WITNESS_SCRIPT),checkPubkey:oh.makeChecker([Ya.OutputTypes.BIP32_DERIVATION])};va.outputs=fh,Object.defineProperty(ga,"__esModule",{value:!0});const ch=va,lh=Ua,ph=La,dh=ma;function yh(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function gh(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case dh.GlobalTypes.UNSIGNED_TX:if(yh("global",t.key,dh.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case dh.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(ch.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of lh.range(s)){const e={};for(const n of r[t])switch(ch.inputs.checkPubkey(n),n.key[0]){case dh.InputTypes.NON_WITNESS_UTXO:if(yh("input",n.key,dh.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=ch.inputs.nonWitnessUtxo.decode(n);break;case dh.InputTypes.WITNESS_UTXO:if(yh("input",n.key,dh.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=ch.inputs.witnessUtxo.decode(n);break;case dh.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(ch.inputs.partialSig.decode(n));break;case dh.InputTypes.SIGHASH_TYPE:if(yh("input",n.key,dh.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=ch.inputs.sighashType.decode(n);break;case dh.InputTypes.REDEEM_SCRIPT:if(yh("input",n.key,dh.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=ch.inputs.redeemScript.decode(n);break;case dh.InputTypes.WITNESS_SCRIPT:if(yh("input",n.key,dh.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=ch.inputs.witnessScript.decode(n);break;case dh.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(ch.inputs.bip32Derivation.decode(n));break;case dh.InputTypes.FINAL_SCRIPTSIG:yh("input",n.key,dh.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=ch.inputs.finalScriptSig.decode(n);break;case dh.InputTypes.FINAL_SCRIPTWITNESS:yh("input",n.key,dh.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=ch.inputs.finalScriptWitness.decode(n);break;case dh.InputTypes.POR_COMMITMENT:yh("input",n.key,dh.InputTypes.POR_COMMITMENT),e.porCommitment=ch.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of lh.range(u)){const e={};for(const r of n[t])switch(ch.outputs.checkPubkey(r),r.key[0]){case dh.OutputTypes.REDEEM_SCRIPT:if(yh("output",r.key,dh.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=ch.outputs.redeemScript.decode(r);break;case dh.OutputTypes.WITNESS_SCRIPT:if(yh("output",r.key,dh.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=ch.outputs.witnessScript.decode(r);break;case dh.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(ch.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}ga.psbtFromBuffer=function(t,e){let r=0;function n(){const e=ph.decode(t,r);r+=ph.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===dh.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of lh.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of lh.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return gh(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},ga.checkKeyBuffer=yh,ga.psbtFromKeyVals=gh;var vh={};Object.defineProperty(vh,"__esModule",{value:!0});const mh=va,wh=Ua;vh.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=_h({globalMap:t,inputs:e,outputs:r}),s=wh.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(wh.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const bh=(t,e)=>t.key.compare(e.key);function Eh(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(bh)}function _h({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:Eh(t,mh.globals),inputKeyVals:e.map((t=>Eh(t,mh.inputs))),outputKeyVals:r.map((t=>Eh(t,mh.outputs)))}}vh.psbtToKeyVals=_h,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(ga),e(vh)}(ya),Object.defineProperty(da,"__esModule",{value:!0});const Sh=ya;function Ih(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function Th(t){return t.globalMap.unsignedTx}function Oh(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}da.combine=function(t){const e=t[0],r=Sh.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=Th(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=Oh(r.globalKeyVals),s=r.inputKeyVals.map(Oh),u=r.outputKeyVals.map(Oh);for(const t of n){const e=Th(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=Sh.psbtToKeyVals(t);Oh(n.globalKeyVals).forEach(Ih(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(Oh).forEach(((t,e)=>t.forEach(Ih(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(Oh).forEach(((t,e)=>t.forEach(Ih(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return Sh.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var Ph={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=va;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(Ph),Object.defineProperty(pa,"__esModule",{value:!0});const kh=da,Ah=ya,Mh=ma,xh=Ph;pa.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ah.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ah.psbtToBuffer(this)}updateGlobal(t){return xh.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=xh.checkForInput(this.inputs,t);return xh.updateInput(e,r),this}updateOutput(t,e){const r=xh.checkForOutput(this.outputs,t);return xh.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return xh.checkHasKey(t,this.globalMap.unknownKeyVals,xh.getEnumLength(Mh.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=xh.checkForInput(this.inputs,t);return xh.checkHasKey(e,r.unknownKeyVals,xh.getEnumLength(Mh.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=xh.checkForOutput(this.outputs,t);return xh.checkHasKey(e,r.unknownKeyVals,xh.getEnumLength(Mh.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),xh.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),xh.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=xh.checkForInput(this.inputs,t);xh.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=kh.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(la,"__esModule",{value:!0});const Nh=pa,Rh=La,Bh=Ph,Ch=uo,Uh=ku,Lh=is,Dh=gu,Hh=ho,Fh=co,qh=Hu,jh={network:ao.bitcoin,maximumFeeRate:5e3};class Gh{constructor(t={},e=new Nh.Psbt(new Vh)){this.data=e,this.opts=Object.assign({},jh,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=Nh.Psbt.fromBuffer(t,Kh),n=new Gh(e,r);return function(t,e){t.ins.forEach((t=>{uf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:Uh.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Ch.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:Uh.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Gh.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){nf(t),this.opts.maximumFeeRate=t}setVersion(t){nf(t),of(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){nf(t),of(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){nf(e),of(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");of(this.data.inputs,"addInput"),t.witnessScript&&If(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);uf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&mf(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");of(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Ch.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(zh))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return wf(this.data.inputs,r,e,!0),r}getFeeRate(){return cf("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return cf("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Bh.checkForInput(this.data.inputs,0),Pf(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=lf){const r=Bh.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=bf(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Zh(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Fh.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Bh.checkForInput(this.data.inputs,t),r=Sf(Ef(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Fh.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||_f(r)||(n=r,Fh.isCanonicalScriptSignature(n)))return;var n;if(!Fh.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=gf(t),r=e[e.length-1];if(_f(r))return;if(!Fh.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+Of(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=Ef(r,e,n),{meaningfulScript:o}=Sf(i,r,"input",e.redeemScript,e.witnessScript);return Tf(t,o)}(e,Bh.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Bh.checkForInput(this.data.inputs,t),n=rf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=Sf(i,r,"output",e.redeemScript,e.witnessScript);return Tf(t,o)}(e,Bh.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Bh.checkForOutput(this.data.outputs,t),n=rf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Bh.checkForInput(this.data.inputs,0);return Pf(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Fh.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?df(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,sf(e.pubkey,h,"verify");const f=Dh.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[qh.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of Pf(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[qh.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of Pf(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[qh.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return yf(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[qh.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=yf(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[qh.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of Pf(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[qh.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[qh.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=pf(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Fh.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[qh.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=pf(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Fh.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Wh(this.__CACHE),this.data.toBuffer()}toHex(){return Wh(this.__CACHE),this.data.toHex()}toBase64(){return Wh(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&If(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&mf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}la.Psbt=Gh;const Kh=t=>new Vh(t);class Vh{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=qh.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?Uh.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Wh(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function $h(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Dh.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function zh(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Xh(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Yh=Xh(Hh.p2ms),Jh=Xh(Hh.p2pk),Qh=Xh(Hh.p2pkh),Zh=Xh(Hh.p2wpkh),tf=Xh(Hh.p2wsh),ef=Xh(Hh.p2sh);function rf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function nf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function of(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Fh.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Fh.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Fh.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Fh.signature.decode(t.signature),i=[];n&qh.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case qh.Transaction.SIGHASH_ALL:break;case qh.Transaction.SIGHASH_SINGLE:case qh.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function sf(t,e,r){if(!Tf(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function uf(t,e){const r=Uh.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function af(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const hf=af(Hh.p2sh,"Redeem script"),ff=af(Hh.p2wsh,"Witness script");function cf(t,e,r,n){if(!r.every(zh))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),wf(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function lf(t,e,r,n,i,o){const s=Of(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return $h(1,t.partialSig);case"multisig":const r=Hh.p2ms({output:e});return $h(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return Hh.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=Hh.p2ms({output:t,signatures:e});break;case"pubkey":n=Hh.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=Hh.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=Hh.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?Hh.p2wsh({redeem:a}):null,f=i?Hh.p2sh({redeem:h||a}):null;n?(u=vf(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function pf(t,e,r,n,i){const o=Bh.checkForInput(t,e),{hash:s,sighashType:u,script:a}=df(e,o,n,!1,i);return sf(r,a,"sign"),{hash:s,sighashType:u}}function df(t,e,r,n,i){const o=r.__TX,s=e.sighashType||qh.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&qh.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case qh.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case qh.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case qh.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=bf(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=Sf(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Zh(h)){const e=Hh.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function yf(t,e,r){const n=Bh.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function gf(t){let e=0;function r(){const r=Rh.decode(t,e);return e+=Rh.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=gf(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=bf(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function bf(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||mf(t,e,r),n[r]}function Ef(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return bf(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function _f(t){return 33===t.length&&Fh.isCanonicalPubKey(t)}function Sf(t,e,r,n,i){const o=ef(t),s=o&&n&&tf(n),u=tf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,hf(e,t,n,r),ff(e,n,i,r),If(a)):u?(a=i,ff(e,t,i,r),If(a)):o?(a=n,hf(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function If(t){if(Zh(t)||ef(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Tf(t,e){const r=Lh.hash160(t),n=Fh.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function Of(t){return Zh(t)?"witnesspubkeyhash":Qh(t)?"pubkeyhash":Yh(t)?"multisig":Jh(t)?"pubkey":"nonstandard"}function Pf(t){return[...Array(t).keys()]}var kf={},Af={},Mf={},xf={};Object.defineProperty(xf,"__esModule",{value:!0});const Nf=co,Rf=co;function Bf(t){return t===Rf.OPS.OP_0||Nf.isCanonicalScriptSignature(t)}function Cf(t,e){const r=Nf.decompile(t);return!(r.length<2)&&(r[0]===Rf.OPS.OP_0&&(e?r.slice(1).every(Bf):r.slice(1).every(Nf.isCanonicalScriptSignature)))}xf.check=Cf,Cf.toJSON=()=>"multisig input";var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0});const Lf=co,Df=co,Hf=yo,Ff=Df.OPS.OP_RESERVED;function qf(t,e){const r=Lf.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Df.OPS.OP_CHECKMULTISIG)return!1;if(!Hf.Number(r[0]))return!1;if(!Hf.Number(r[r.length-2]))return!1;const n=r[0]-Ff,i=r[r.length-2]-Ff;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(Lf.isCanonicalPubKey)}Uf.check=qf,qf.toJSON=()=>"multi-sig output",Object.defineProperty(Mf,"__esModule",{value:!0});const jf=xf;Mf.input=jf;const Gf=Uf;Mf.output=Gf;var Kf={};Object.defineProperty(Kf,"__esModule",{value:!0});const Vf=co,Wf=Vf.OPS;function $f(t){const e=Vf.compile(t);return e.length>1&&e[0]===Wf.OP_RETURN}Kf.check=$f,$f.toJSON=()=>"null data output";const zf={check:$f};Kf.output=zf;var Xf={},Yf={};Object.defineProperty(Yf,"__esModule",{value:!0});const Jf=co;function Qf(t){const e=Jf.decompile(t);return 1===e.length&&Jf.isCanonicalScriptSignature(e[0])}Yf.check=Qf,Qf.toJSON=()=>"pubKey input";var Zf={};Object.defineProperty(Zf,"__esModule",{value:!0});const tc=co,ec=co;function rc(t){const e=tc.decompile(t);return 2===e.length&&tc.isCanonicalPubKey(e[0])&&e[1]===ec.OPS.OP_CHECKSIG}Zf.check=rc,rc.toJSON=()=>"pubKey output",Object.defineProperty(Xf,"__esModule",{value:!0});const nc=Yf;Xf.input=nc;const ic=Zf;Xf.output=ic;var oc={},sc={};Object.defineProperty(sc,"__esModule",{value:!0});const uc=co;function ac(t){const e=uc.decompile(t);return 2===e.length&&uc.isCanonicalScriptSignature(e[0])&&uc.isCanonicalPubKey(e[1])}sc.check=ac,ac.toJSON=()=>"pubKeyHash input";var hc={};Object.defineProperty(hc,"__esModule",{value:!0});const fc=co,cc=co;function lc(t){const e=fc.compile(t);return 25===e.length&&e[0]===cc.OPS.OP_DUP&&e[1]===cc.OPS.OP_HASH160&&20===e[2]&&e[23]===cc.OPS.OP_EQUALVERIFY&&e[24]===cc.OPS.OP_CHECKSIG}hc.check=lc,lc.toJSON=()=>"pubKeyHash output",Object.defineProperty(oc,"__esModule",{value:!0});const pc=sc;oc.input=pc;const dc=hc;oc.output=dc;var yc={},gc={},vc={};Object.defineProperty(vc,"__esModule",{value:!0});const mc=co,wc=co;function bc(t){const e=mc.compile(t);return 22===e.length&&e[0]===wc.OPS.OP_0&&20===e[1]}vc.check=bc,bc.toJSON=()=>"Witness pubKeyHash output";var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});const _c=co,Sc=co;function Ic(t){const e=_c.compile(t);return 34===e.length&&e[0]===Sc.OPS.OP_0&&32===e[1]}Ec.check=Ic,Ic.toJSON=()=>"Witness scriptHash output",Object.defineProperty(gc,"__esModule",{value:!0});const Tc=co,Oc=Mf,Pc=Xf,kc=oc,Ac=vc,Mc=Ec;function xc(t,e){const r=Tc.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=Tc.decompile(Tc.compile(r.slice(0,-1))),o=Tc.decompile(n);return!!o&&(!!Tc.isPushOnly(i)&&(1===r.length?Mc.check(o)||Ac.check(o):!(!kc.input.check(i)||!kc.output.check(o))||(!(!Oc.input.check(i,e)||!Oc.output.check(o))||!(!Pc.input.check(i)||!Pc.output.check(o)))))}gc.check=xc,xc.toJSON=()=>"scriptHash input";var Nc={};Object.defineProperty(Nc,"__esModule",{value:!0});const Rc=co,Bc=co;function Cc(t){const e=Rc.compile(t);return 23===e.length&&e[0]===Bc.OPS.OP_HASH160&&20===e[1]&&e[22]===Bc.OPS.OP_EQUAL}Nc.check=Cc,Cc.toJSON=()=>"scriptHash output",Object.defineProperty(yc,"__esModule",{value:!0});const Uc=gc;yc.input=Uc;const Lc=Nc;yc.output=Lc;var Dc={},Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});const Fc=co,qc=co,jc=yo,Gc=Hi,Kc=Buffer.from("aa21a9ed","hex");function Vc(t){const e=Fc.compile(t);return e.length>37&&e[0]===qc.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Kc)}Hc.check=Vc,Vc.toJSON=()=>"Witness commitment output",Hc.encode=function(t){Gc(jc.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Kc.copy(e,0),t.copy(e,4),Fc.compile([qc.OPS.OP_RETURN,e])},Hc.decode=function(t){return Gc(Vc,t),Fc.decompile(t)[1].slice(4,36)},Object.defineProperty(Dc,"__esModule",{value:!0});const Wc=Hc;Dc.output=Wc;var $c={},zc={};Object.defineProperty(zc,"__esModule",{value:!0});const Xc=co;function Yc(t){const e=Xc.decompile(t);return 2===e.length&&Xc.isCanonicalScriptSignature(e[0])&&function(t){return Xc.isCanonicalPubKey(t)&&33===t.length}(e[1])}zc.check=Yc,Yc.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty($c,"__esModule",{value:!0});const Jc=zc;$c.input=Jc;const Qc=vc;$c.output=Qc;var Zc={},tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=co,rl=Hi,nl=Mf,il=Xf,ol=oc;function sl(t,e){if(rl(rl.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=el.decompile(r);if(!n||0===n.length)return!1;const i=el.compile(t.slice(0,-1));return!(!ol.input.check(i)||!ol.output.check(n))||(!(!nl.input.check(i,e)||!nl.output.check(n))||!(!il.input.check(i)||!il.output.check(n)))}tl.check=sl,sl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Zc,"__esModule",{value:!0});const ul=tl;Zc.input=ul;const al=Ec;Zc.output=al,Object.defineProperty(Af,"__esModule",{value:!0});const hl=co,fl=Mf,cl=Kf,ll=Xf,pl=oc,dl=yc,yl=Dc,gl=$c,vl=Zc,ml={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Af.types=ml,Af.output=function(t){if(gl.output.check(t))return ml.P2WPKH;if(vl.output.check(t))return ml.P2WSH;if(pl.output.check(t))return ml.P2PKH;if(dl.output.check(t))return ml.P2SH;const e=hl.decompile(t);if(!e)throw new TypeError("Invalid script");return fl.output.check(e)?ml.P2MS:ll.output.check(e)?ml.P2PK:yl.output.check(e)?ml.WITNESS_COMMITMENT:cl.output.check(e)?ml.NULLDATA:ml.NONSTANDARD},Af.input=function(t,e){const r=hl.decompile(t);if(!r)throw new TypeError("Invalid script");return pl.input.check(r)?ml.P2PKH:dl.input.check(r,e)?ml.P2SH:fl.input.check(r,e)?ml.P2MS:ll.input.check(r)?ml.P2PK:ml.NONSTANDARD},Af.witness=function(t,e){const r=hl.decompile(t);if(!r)throw new TypeError("Invalid script");return gl.input.check(r)?ml.P2WPKH:vl.input.check(r,e)?ml.P2WSH:ml.NONSTANDARD},Object.defineProperty(kf,"__esModule",{value:!0});const wl=uo,bl=ku,El=Af,_l=is,Sl=gu,Il=ao,Tl=ho,Ol=co,Pl=co,kl=Hu,Al=yo,Ml=Hi,xl=El.types,Nl=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Rl(t,e,r){try{Ml(t,e)}catch(t){throw new Error(r)}}class Bl{constructor(t=Il.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new kl.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Bl(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==xl.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=Sl.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=Ol.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ml(Ml.maybe(Ml.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ml(Al.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ml(Al.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=bl.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof kl.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=wl.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=Ol.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Nl.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Rl(Ml.Number,e.vin,"sign must include vin parameter as Number (input index)"),Rl(Al.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Rl(Ml.maybe(Ml.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires redeemScript`),Rl(Ml.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.Buffer,e.witnessScript,`${n} requires witnessScript`),Rl(Ml.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Rl(Ml.Buffer,e.witnessScript,`${n} requires witnessScript`),Rl(Ml.Buffer,e.redeemScript,`${n} requires witnessScript`),Rl(Al.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||kl.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Dl(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ml(Al.Satoshi,a),l.value=a}if(!Dl(l)){const t=function(t,e,r,n){if(r&&n){const i=Tl.p2wsh({redeem:{output:n}}),o=Tl.p2wsh({output:r}),s=Tl.p2sh({redeem:{output:r}}),u=Tl.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ul(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+Ol.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===xl.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:xl.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:xl.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=Tl.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=Tl.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ul(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+Ol.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===xl.P2WPKH&&(o=Tl.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:xl.P2SH,prevOutScript:n.output,hasWitness:i.type===xl.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=Tl.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=Tl.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ul(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+Ol.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===xl.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:xl.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===xl.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===xl.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ul(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+Ol.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===xl.P2WPKH&&(n=Tl.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===xl.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=Tl.p2pkh({pubkey:e}).output;return{prevOutType:xl.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:xl.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Dl(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(kl.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Cl(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ul(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||El.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=Ll(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===xl.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Hl(t)&kl.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===kl.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Hl(t)&kl.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Hl(r);return n===kl.Transaction.SIGHASH_NONE||n===kl.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Cl(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=El.input(t,!0),i=El.witness(e,!0);n===xl.NONSTANDARD&&(n=void 0),i===xl.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case xl.P2WPKH:{const{output:t,pubkey:r,signature:n}=Tl.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:xl.P2WPKH,pubkeys:[r],signatures:[n]}}case xl.P2PKH:{const{output:e,pubkey:r,signature:n}=Tl.p2pkh({input:t});return{prevOutScript:e,prevOutType:xl.P2PKH,pubkeys:[r],signatures:[n]}}case xl.P2PK:{const{signature:e}=Tl.p2pk({input:t});return{prevOutType:xl.P2PK,pubkeys:[void 0],signatures:[e]}}case xl.P2MS:{const{m:e,pubkeys:r,signatures:i}=Tl.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:xl.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===xl.P2SH){const{output:r,redeem:n}=Tl.p2sh({input:t,witness:e}),i=El.output(n.output),o=Cl(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:xl.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===xl.P2WSH){const{output:r,redeem:n}=Tl.p2wsh({input:t,witness:e}),i=El.output(n.output);let o;return o=i===xl.P2WPKH?Cl(n.input,n.witness,i):Cl(Ol.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:xl.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:xl.NONSTANDARD,prevOutScript:t}}function Ul(t,e){Ml(Al.Buffer,t);const r=El.output(t);switch(r){case xl.P2PKH:{if(!e)return{type:r};const n=Tl.p2pkh({output:t}).hash,i=_l.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case xl.P2WPKH:{if(!e)return{type:r};const n=Tl.p2wpkh({output:t}).hash,i=_l.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case xl.P2PK:return{type:r,pubkeys:[Tl.p2pk({output:t}).pubkey],signatures:[void 0]};case xl.P2MS:{const e=Tl.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function Ll(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case xl.P2PKH:if(0===n.length)break;if(0===i.length)break;return Tl.p2pkh({pubkey:n[0],signature:i[0]});case xl.P2WPKH:if(0===n.length)break;if(0===i.length)break;return Tl.p2wpkh({pubkey:n[0],signature:i[0]});case xl.P2PK:if(0===n.length)break;if(0===i.length)break;return Tl.p2pk({signature:i[0]});case xl.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||Pl.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return Tl.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case xl.P2SH:{const t=Ll(e.redeemScriptType,e,r);if(!t)return;return Tl.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case xl.P2WSH:{const t=Ll(e.witnessScriptType,e,r);if(!t)return;return Tl.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Dl(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Hl(t){return t.readUInt8(t.length-1)}kf.TransactionBuilder=Bl,Object.defineProperty(R,"__esModule",{value:!0});const Fl=B;R.bip32=Fl;const ql=uo;R.address=ql;const jl=is;var Gl=R.crypto=jl;const Kl=gu;R.ECPair=Kl;const Vl=ao;R.networks=Vl;const Wl=ho;R.payments=Wl;const $l=co;R.script=$l;var zl=Pu;R.Block=zl.Block;var Xl=la;R.Psbt=Xl.Psbt;var Yl=co;R.opcodes=Yl.OPS;var Jl=Hu;R.Transaction=Jl.Transaction;var Ql=kf;R.TransactionBuilder=Ql.TransactionBuilder;var Zl={exports:{}};var tp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var ep="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=tp,n=ep,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Zl,Zl.exports);const rp=["includePrerelease","loose","rtl"];var np=t=>t?"object"!=typeof t?{loose:!0}:rp.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const ip=/^[0-9]+$/,op=(t,e)=>{const r=ip.test(t),n=ip.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:top(e,t)};const up=ep,{MAX_LENGTH:ap,MAX_SAFE_INTEGER:hp}=tp,{re:fp,t:cp}=Zl.exports,lp=np,{compareIdentifiers:pp}=sp;class dp{constructor(t,e){if(e=lp(e),t instanceof dp){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>ap)throw new TypeError(`version is longer than ${ap} characters`);up("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?fp[cp.LOOSE]:fp[cp.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>hp||this.major<0)throw new TypeError("Invalid major version");if(this.minor>hp||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>hp||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var yp=dp;const{MAX_LENGTH:gp}=tp,{re:vp,t:mp}=Zl.exports,wp=yp,bp=np;var Ep=(t,e)=>{if(e=bp(e),t instanceof wp)return t;if("string"!=typeof t)return null;if(t.length>gp)return null;if(!(e.loose?vp[mp.LOOSE]:vp[mp.FULL]).test(t))return null;try{return new wp(t,e)}catch(t){return null}};const _p=Ep;var Sp=(t,e)=>{const r=_p(t,e);return r?r.version:null};const Ip=Ep;var Tp=(t,e)=>{const r=Ip(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const Op=yp;var Pp=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new Op(t,r).inc(e,n).version}catch(t){return null}};const kp=yp;var Ap=(t,e,r)=>new kp(t,r).compare(new kp(e,r));const Mp=Ap;var xp=(t,e,r)=>0===Mp(t,e,r);const Np=Ep,Rp=xp;var Bp=(t,e)=>{if(Rp(t,e))return null;{const r=Np(t),n=Np(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Cp=yp;var Up=(t,e)=>new Cp(t,e).major;const Lp=yp;var Dp=(t,e)=>new Lp(t,e).minor;const Hp=yp;var Fp=(t,e)=>new Hp(t,e).patch;const qp=Ep;var jp=(t,e)=>{const r=qp(t,e);return r&&r.prerelease.length?r.prerelease:null};const Gp=Ap;var Kp=(t,e,r)=>Gp(e,t,r);const Vp=Ap;var Wp=(t,e)=>Vp(t,e,!0);const $p=yp;var zp=(t,e,r)=>{const n=new $p(t,r),i=new $p(e,r);return n.compare(i)||n.compareBuild(i)};const Xp=zp;var Yp=(t,e)=>t.sort(((t,r)=>Xp(t,r,e)));const Jp=zp;var Qp=(t,e)=>t.sort(((t,r)=>Jp(r,t,e)));const Zp=Ap;var td=(t,e,r)=>Zp(t,e,r)>0;const ed=Ap;var rd=(t,e,r)=>ed(t,e,r)<0;const nd=Ap;var id=(t,e,r)=>0!==nd(t,e,r);const od=Ap;var sd=(t,e,r)=>od(t,e,r)>=0;const ud=Ap;var ad=(t,e,r)=>ud(t,e,r)<=0;const hd=xp,fd=id,cd=td,ld=sd,pd=rd,dd=ad;var yd=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return hd(t,r,n);case"!=":return fd(t,r,n);case">":return cd(t,r,n);case">=":return ld(t,r,n);case"<":return pd(t,r,n);case"<=":return dd(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const gd=yp,vd=Ep,{re:md,t:wd}=Zl.exports;var bd=(t,e)=>{if(t instanceof gd)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=md[wd.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),md[wd.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;md[wd.COERCERTL].lastIndex=-1}else r=t.match(md[wd.COERCE]);return null===r?null:vd(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},Ed=_d;function _d(t){var e=this;if(e instanceof _d||(e=new _d),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},_d.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},_d.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},_d.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},_d.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new _d;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},_d.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Hd=(t,e,r)=>{const n=t[Ud].get(e);if(n){const e=n.value;if(Fd(t,e)){if(jd(t,n),!t[xd])return}else r&&(t[Ld]&&(n.value.now=Date.now()),t[Cd].unshiftNode(n));return e.value}},Fd=(t,e)=>{if(!e||!e.maxAge&&!t[Nd])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Nd]&&r>t[Nd]},qd=t=>{if(t[Ad]>t[kd])for(let e=t[Cd].tail;t[Ad]>t[kd]&&null!==e;){const r=e.prev;jd(t,e),e=r}},jd=(t,e)=>{if(e){const r=e.value;t[Rd]&&t[Rd](r.key,r.value),t[Ad]-=r.length,t[Ud].delete(r.key),t[Cd].removeNode(e)}};class Gd{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Kd=(t,e,r,n)=>{let i=r.value;Fd(t,i)&&(jd(t,r),t[xd]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Vd=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[kd]=t.max||1/0;const e=t.length||Dd;if(this[Md]="function"!=typeof e?Dd:e,this[xd]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Nd]=t.maxAge||0,this[Rd]=t.dispose,this[Bd]=t.noDisposeOnSet||!1,this[Ld]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[kd]=t||1/0,qd(this)}get max(){return this[kd]}set allowStale(t){this[xd]=!!t}get allowStale(){return this[xd]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Nd]=t,qd(this)}get maxAge(){return this[Nd]}set lengthCalculator(t){"function"!=typeof t&&(t=Dd),t!==this[Md]&&(this[Md]=t,this[Ad]=0,this[Cd].forEach((t=>{t.length=this[Md](t.value,t.key),this[Ad]+=t.length}))),qd(this)}get lengthCalculator(){return this[Md]}get length(){return this[Ad]}get itemCount(){return this[Cd].length}rforEach(t,e){e=e||this;for(let r=this[Cd].tail;null!==r;){const n=r.prev;Kd(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Cd].head;null!==r;){const n=r.next;Kd(this,t,r,e),r=n}}keys(){return this[Cd].toArray().map((t=>t.key))}values(){return this[Cd].toArray().map((t=>t.value))}reset(){this[Rd]&&this[Cd]&&this[Cd].length&&this[Cd].forEach((t=>this[Rd](t.key,t.value))),this[Ud]=new Map,this[Cd]=new Pd,this[Ad]=0}dump(){return this[Cd].map((t=>!Fd(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Cd]}set(t,e,r){if((r=r||this[Nd])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Md](e,t);if(this[Ud].has(t)){if(i>this[kd])return jd(this,this[Ud].get(t)),!1;const o=this[Ud].get(t).value;return this[Rd]&&(this[Bd]||this[Rd](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Ad]+=i-o.length,o.length=i,this.get(t),qd(this),!0}const o=new Gd(t,e,i,n,r);return o.length>this[kd]?(this[Rd]&&this[Rd](t,e),!1):(this[Ad]+=o.length,this[Cd].unshift(o),this[Ud].set(t,this[Cd].head),qd(this),!0)}has(t){if(!this[Ud].has(t))return!1;const e=this[Ud].get(t).value;return!Fd(this,e)}get(t){return Hd(this,t,!0)}peek(t){return Hd(this,t,!1)}pop(){const t=this[Cd].tail;return t?(jd(this,t),t.value):null}del(t){jd(this,this[Ud].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ud].forEach(((t,e)=>Hd(this,e,!1)))}};class Wd{constructor(t,e){if(e=Xd(e),t instanceof Wd)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Wd(t.raw,e);if(t instanceof Yd)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!iy(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&oy(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=zd.get(e);if(r)return r;const n=this.options.loose,i=n?Zd[ty.HYPHENRANGELOOSE]:Zd[ty.HYPHENRANGE];t=t.replace(i,vy(this.options.includePrerelease)),Jd("hyphen replace",t),t=t.replace(Zd[ty.COMPARATORTRIM],ey),Jd("comparator trim",t,Zd[ty.COMPARATORTRIM]),t=(t=(t=t.replace(Zd[ty.TILDETRIM],ry)).replace(Zd[ty.CARETTRIM],ny)).split(/\s+/).join(" ");const o=n?Zd[ty.COMPARATORLOOSE]:Zd[ty.COMPARATOR],s=t.split(" ").map((t=>uy(t,this.options))).join(" ").split(/\s+/).map((t=>gy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Yd(t,this.options)));s.length;const u=new Map;for(const t of s){if(iy(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return zd.set(e,a),a}intersects(t,e){if(!(t instanceof Wd))throw new TypeError("a Range is required");return this.set.some((r=>sy(r,e)&&t.set.some((t=>sy(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Qd(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,oy=t=>""===t.value,sy=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},uy=(t,e)=>(Jd("comp",t,e),t=cy(t,e),Jd("caret",t),t=hy(t,e),Jd("tildes",t),t=py(t,e),Jd("xrange",t),t=yy(t,e),Jd("stars",t),t),ay=t=>!t||"x"===t.toLowerCase()||"*"===t,hy=(t,e)=>t.trim().split(/\s+/).map((t=>fy(t,e))).join(" "),fy=(t,e)=>{const r=e.loose?Zd[ty.TILDELOOSE]:Zd[ty.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Jd("tilde",t,e,r,n,i,o),ay(r)?s="":ay(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:ay(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Jd("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Jd("tilde return",s),s}))},cy=(t,e)=>t.trim().split(/\s+/).map((t=>ly(t,e))).join(" "),ly=(t,e)=>{Jd("caret",t,e);const r=e.loose?Zd[ty.CARETLOOSE]:Zd[ty.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Jd("caret",t,e,r,i,o,s),ay(r)?u="":ay(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:ay(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Jd("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Jd("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Jd("caret return",u),u}))},py=(t,e)=>(Jd("replaceXRanges",t,e),t.split(/\s+/).map((t=>dy(t,e))).join(" ")),dy=(t,e)=>{t=t.trim();const r=e.loose?Zd[ty.XRANGELOOSE]:Zd[ty.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Jd("xRange",t,r,n,i,o,s,u);const a=ay(i),h=a||ay(o),f=h||ay(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Jd("xRange return",r),r}))},yy=(t,e)=>(Jd("replaceStars",t,e),t.trim().replace(Zd[ty.STAR],"")),gy=(t,e)=>(Jd("replaceGTE0",t,e),t.trim().replace(Zd[e.includePrerelease?ty.GTE0PRE:ty.GTE0],"")),vy=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=ay(n)?"":ay(i)?`>=${n}.0.0${t?"-0":""}`:ay(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=ay(h)?"":ay(f)?`<${+h+1}.0.0-0`:ay(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),my=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},wy=Symbol("SemVer ANY");class by{static get ANY(){return wy}constructor(t,e){if(e=_y(e),t instanceof by){if(t.loose===!!e.loose)return t;t=t.value}Oy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===wy?this.value="":this.value=this.operator+this.semver.version,Oy("comp",this)}parse(t){const e=this.options.loose?Sy[Iy.COMPARATORLOOSE]:Sy[Iy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new Py(r[2],this.options.loose):this.semver=wy}toString(){return this.value}test(t){if(Oy("Comparator.test",t,this.options.loose),this.semver===wy||t===wy)return!0;if("string"==typeof t)try{t=new Py(t,this.options)}catch(t){return!1}return Ty(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof by))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new ky(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new ky(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=Ty(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=Ty(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var Ey=by;const _y=np,{re:Sy,t:Iy}=Zl.exports,Ty=yd,Oy=ep,Py=yp,ky=$d,Ay=$d;var My=(t,e,r)=>{try{e=new Ay(e,r)}catch(t){return!1}return e.test(t)};const xy=$d;var Ny=(t,e)=>new xy(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Ry=yp,By=$d;var Cy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new By(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Ry(n,r)))})),n};const Uy=yp,Ly=$d;var Dy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ly(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Uy(n,r)))})),n};const Hy=yp,Fy=$d,qy=td;var jy=(t,e)=>{t=new Fy(t,e);let r=new Hy("0.0.0");if(t.test(r))return r;if(r=new Hy("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new Hy(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!qy(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!qy(r,i)||(r=i)}return r&&t.test(r)?r:null};const Gy=$d;var Ky=(t,e)=>{try{return new Gy(t,e).range||"*"}catch(t){return null}};const Vy=yp,Wy=Ey,{ANY:$y}=Wy,zy=$d,Xy=My,Yy=td,Jy=rd,Qy=ad,Zy=sd;var tg=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Vy(t,n),e=new zy(e,n),r){case">":i=Yy,o=Qy,s=Jy,u=">",a=">=";break;case"<":i=Jy,o=Zy,s=Yy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Xy(t,e,n))return!1;for(let r=0;r{t.semver===$y&&(t=new Wy(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const eg=tg;var rg=(t,e,r)=>eg(t,e,">",r);const ng=tg;var ig=(t,e,r)=>ng(t,e,"<",r);const og=$d;var sg=(t,e,r)=>(t=new og(t,r),e=new og(e,r),t.intersects(e));const ug=My,ag=Ap;const hg=$d,fg=Ey,{ANY:cg}=fg,lg=My,pg=Ap,dg=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===cg){if(1===e.length&&e[0].semver===cg)return!0;t=r.includePrerelease?[new fg(">=0.0.0-0")]:[new fg(">=0.0.0")]}if(1===e.length&&e[0].semver===cg){if(r.includePrerelease)return!0;e=[new fg(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=yg(i,e,r):"<"===e.operator||"<="===e.operator?o=gg(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=pg(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!lg(t,String(i),r))return null;if(o&&!lg(t,String(o),r))return null;for(const n of e)if(!lg(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=yg(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!lg(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=gg(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!lg(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},yg=(t,e,r)=>{if(!t)return e;const n=pg(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},gg=(t,e,r)=>{if(!t)return e;const n=pg(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var vg=(t,e,r={})=>{if(t===e)return!0;t=new hg(t,r),e=new hg(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=dg(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const mg=Zl.exports;var wg={re:mg.re,src:mg.src,tokens:mg.t,SEMVER_SPEC_VERSION:tp.SEMVER_SPEC_VERSION,SemVer:yp,compareIdentifiers:sp.compareIdentifiers,rcompareIdentifiers:sp.rcompareIdentifiers,parse:Ep,valid:Sp,clean:Tp,inc:Pp,diff:Bp,major:Up,minor:Dp,patch:Fp,prerelease:jp,compare:Ap,rcompare:Kp,compareLoose:Wp,compareBuild:zp,sort:Yp,rsort:Qp,gt:td,lt:rd,eq:xp,neq:id,gte:sd,lte:ad,cmp:yd,coerce:bd,Comparator:Ey,Range:$d,satisfies:My,toComparators:Ny,maxSatisfying:Cy,minSatisfying:Dy,minVersion:jy,validRange:Ky,outside:tg,gtr:rg,ltr:ig,intersects:sg,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>ag(t,e,r)));for(const t of s){ug(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Ag.alloc(0);for(var e=Ag.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ng(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Ag.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:xg,value:function(t,e){return Mg(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Fg("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Fg("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${qg(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${qg(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Fg("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Fg("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Fg("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Fg("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Fg("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Fg("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Fg("ERR_STREAM_WRITE_AFTER_END","write after end"),Fg("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Fg("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Fg("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Dg.codes=Hg;var jg=Dg.codes.ERR_INVALID_OPT_VALUE;var Gg,Kg={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new jg(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Vg=l.default.deprecate,Wg=pv;function $g(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}pv.WritableState=lv;var zg={deprecate:Vg},Xg=Tg,Yg=h.default.Buffer,Jg=p.Uint8Array||function(){};var Qg,Zg=Lg,tv=Kg.getHighWaterMark,ev=Dg.codes,rv=ev.ERR_INVALID_ARG_TYPE,nv=ev.ERR_METHOD_NOT_IMPLEMENTED,iv=ev.ERR_MULTIPLE_CALLBACK,ov=ev.ERR_STREAM_CANNOT_PIPE,sv=ev.ERR_STREAM_DESTROYED,uv=ev.ERR_STREAM_NULL_VALUES,av=ev.ERR_STREAM_WRITE_AFTER_END,hv=ev.ERR_UNKNOWN_ENCODING,fv=Zg.errorOrDestroy;function cv(){}function lv(t,e,r){Gg=Gg||Ev,t=t||{},"boolean"!=typeof r&&(r=e instanceof Gg),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=tv(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new iv;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(wv,t,e),t._writableState.errorEmitted=!0,fv(t,n)):(i(n),t._writableState.errorEmitted=!0,fv(t,n),wv(t,e))}(t,r,n,e,i);else{var o=vv(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||gv(t,r),n?process.nextTick(yv,t,r,o,i):yv(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $g(this)}function pv(t){var e=this instanceof(Gg=Gg||Ev);if(!e&&!Qg.call(pv,this))return new pv(t);this._writableState=new lv(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Xg.call(this)}function dv(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new sv("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function yv(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),wv(t,e)}function gv(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,dv(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new $g(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(dv(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function vv(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function mv(t,e){t._final((function(r){e.pendingcb--,r&&fv(t,r),e.prefinished=!0,t.emit("prefinish"),wv(t,e)}))}function wv(t,e){var r=vv(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(mv,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}ut.exports(pv,Xg),lv.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(lv.prototype,"buffer",{get:zg.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Qg=Function.prototype[Symbol.hasInstance],Object.defineProperty(pv,Symbol.hasInstance,{value:function(t){return!!Qg.call(this,t)||this===pv&&(t&&t._writableState instanceof lv)}})):Qg=function(t){return t instanceof this},pv.prototype.pipe=function(){fv(this,new ov)},pv.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Yg.isBuffer(n)||n instanceof Jg);return s&&!Yg.isBuffer(t)&&(t=function(t){return Yg.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=cv),i.ending?function(t,e){var r=new av;fv(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new uv:"string"==typeof r||e.objectMode||(i=new rv("chunk",["string","Buffer"],r)),!i||(fv(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Yg.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new hv(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(pv.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(pv.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),pv.prototype._write=function(t,e,r){r(new nv("_write()"))},pv.prototype._writev=null,pv.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,wv(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(pv.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(pv.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),pv.prototype.destroy=Zg.destroy,pv.prototype._undestroy=Zg.undestroy,pv.prototype._destroy=function(t,e){e(t)};var bv=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},Ev=Pv,_v=dm,Sv=Wg;ut.exports(Pv,_v);for(var Iv=bv(Sv.prototype),Tv=0;Tv>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Cv(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Uv(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function Lv(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Dv(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Hv(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Fv(t){return t.toString(this.encoding)}function qv(t){return t&&t.length?this.write(t):""}Mv.StringDecoder=Rv,Rv.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Rv.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var jv=Dg.codes.ERR_STREAM_PREMATURE_CLOSE;function Gv(){}var Kv,Vv=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===vm.prototype||(e=function(t){return vm.from(t)}(e)),n)s.endEmitted?Nm(t,new xm):Lm(t,s,e,!0);else if(s.ended)Nm(t,new Am);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?Lm(t,s,e,!1):jm(t,s)):Lm(t,s,e,!1)}else n||(s.reading=!1,jm(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Dm?t=Dm:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Fm(t){var e=t._readableState;wm("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(wm("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(qm,t))}function qm(t){var e=t._readableState;wm("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,$m(t)}function jm(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(Gm,t,e))}function Gm(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function Vm(t){wm("readable nexttick read 0"),t.read(0)}function Wm(t,e){wm("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),$m(t),e.flowing&&!e.reading&&t.read(0)}function $m(t){var e=t._readableState;for(wm("flow",e.flowing);e.flowing&&null!==t.read(););}function zm(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function Xm(t){var e=t._readableState;wm("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(Ym,e,t))}function Ym(t,e){if(wm("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function Jm(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return wm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Xm(this):Fm(this),null;if(0===(t=Hm(t,e))&&e.ended)return 0===e.length&&Xm(this),null;var n,i=e.needReadable;return wm("need readable",i),(0===e.length||e.length-t0?zm(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Xm(this)),null!==n&&this.emit("data",n),n},Cm.prototype._read=function(t){Nm(this,new Mm("_read()"))},Cm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,wm("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){wm("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,wm("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){wm("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;wm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&ym(t,"data")&&(e.flowing=!0,$m(t))}}(r);t.on("drain",u);var a=!1;function h(e){wm("ondata");var i=t.write(e);wm("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Jm(n.pipes,t))&&!a&&(wm("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){wm("onerror",e),p(),t.removeListener("error",f),0===ym(t,"error")&&Nm(t,e)}function c(){t.removeListener("finish",l),p()}function l(){wm("onfinish"),t.removeListener("close",c),p()}function p(){wm("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(wm("pipe resume"),r.resume()),t},Cm.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,wm("on readable",n.length,n.reading),n.length?Fm(this):n.reading||process.nextTick(Vm,this))),r},Cm.prototype.addListener=Cm.prototype.on,Cm.prototype.removeListener=function(t,e){var r=gm.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(Km,this),r},Cm.prototype.removeAllListeners=function(t){var e=gm.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(Km,this),e},Cm.prototype.resume=function(){var t=this._readableState;return t.flowing||(wm("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(Wm,t,e))}(this,t)),t.paused=!1,this},Cm.prototype.pause=function(){return wm("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(wm("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Cm.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(wm("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(wm("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(mw),s||(o.forEach(mw),i(n))}))}));return e.reduce(ww)};!function(t,e){var r=f.default;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=dm).Stream=r||e,e.Readable=e,e.Writable=Wg,e.Duplex=Ev,e.Transform=Qm,e.PassThrough=fw,e.finished=Vv,e.pipeline=Ew)}(Ig,Ig.exports);var _w=m.exports.Buffer,Sw=Ig.exports.Transform;function Iw(t){Sw.call(this),this._block=_w.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,ut.exports)(Iw,Sw),Iw.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},Iw.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},Iw.prototype.update=function(t,e){if(function(t,e){if(!_w.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");_w.isBuffer(t)||(t=_w.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},Iw.prototype._update=function(){throw new Error("_update is not implemented")},Iw.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},Iw.prototype._digest=function(){throw new Error("_digest is not implemented")};var Tw=Iw,Ow=h.default.Buffer,Pw=ut.exports,kw=Tw,Aw=new Array(16),Mw=[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],xw=[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],Nw=[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],Rw=[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],Bw=[0,1518500249,1859775393,2400959708,2840853838],Cw=[1352829926,1548603684,1836072691,2053994217,0];function Uw(){kw.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function Lw(t,e){return t<>>32-e}function Dw(t,e,r,n,i,o,s,u){return Lw(t+(e^r^n)+o+s|0,u)+i|0}function Hw(t,e,r,n,i,o,s,u){return Lw(t+(e&r|~e&n)+o+s|0,u)+i|0}function Fw(t,e,r,n,i,o,s,u){return Lw(t+((e|~r)^n)+o+s|0,u)+i|0}function qw(t,e,r,n,i,o,s,u){return Lw(t+(e&n|r&~n)+o+s|0,u)+i|0}function jw(t,e,r,n,i,o,s,u){return Lw(t+(e^(r|~n))+o+s|0,u)+i|0}Pw(Uw,kw),Uw.prototype._update=function(){for(var t=Aw,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=Dw(r,n,i,o,s,t[Mw[l]],Bw[0],Nw[l]),d=jw(u,a,h,f,c,t[xw[l]],Cw[0],Rw[l])):l<32?(p=Hw(r,n,i,o,s,t[Mw[l]],Bw[1],Nw[l]),d=qw(u,a,h,f,c,t[xw[l]],Cw[1],Rw[l])):l<48?(p=Fw(r,n,i,o,s,t[Mw[l]],Bw[2],Nw[l]),d=Fw(u,a,h,f,c,t[xw[l]],Cw[2],Rw[l])):l<64?(p=qw(r,n,i,o,s,t[Mw[l]],Bw[3],Nw[l]),d=Hw(u,a,h,f,c,t[xw[l]],Cw[3],Rw[l])):(p=jw(r,n,i,o,s,t[Mw[l]],Bw[4],Nw[l]),d=Dw(u,a,h,f,c,t[xw[l]],Cw[4],Rw[l])),r=s,s=o,o=Lw(i,10),i=n,n=p,u=c,c=f,f=Lw(h,10),h=a,a=d}var y=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=y},Uw.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=Ow.alloc?Ow.alloc(20):new Ow(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var Gw=Uw,Kw={exports:{}},Vw=m.exports.Buffer;function Ww(t,e){this._block=Vw.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}Ww.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=Vw.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},Ww.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var $w=Ww,zw=ut.exports,Xw=$w,Yw=m.exports.Buffer,Jw=[1518500249,1859775393,-1894007588,-899497514],Qw=new Array(80);function Zw(){this.init(),this._w=Qw,Xw.call(this,64,56)}function tb(t){return t<<30|t>>>2}function eb(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}zw(Zw,Xw),Zw.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Zw.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+eb(f,i,o,s)+u+r[h]+Jw[f];u=s,s=o,o=tb(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},Zw.prototype._hash=function(){var t=Yw.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var rb=Zw,nb=ut.exports,ib=$w,ob=m.exports.Buffer,sb=[1518500249,1859775393,-1894007588,-899497514],ub=new Array(80);function ab(){this.init(),this._w=ub,ib.call(this,64,56)}function hb(t){return t<<5|t>>>27}function fb(t){return t<<30|t>>>2}function cb(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}nb(ab,ib),ab.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},ab.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=hb(n)+cb(f,i,o,s)+u+r[h]+sb[f]|0;u=s,s=o,o=fb(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},ab.prototype._hash=function(){var t=ob.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var lb=ab,pb=ut.exports,db=$w,yb=m.exports.Buffer,gb=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],vb=new Array(64);function mb(){this.init(),this._w=vb,db.call(this,64,56)}function wb(t,e,r){return r^t&(e^r)}function bb(t,e,r){return t&e|r&(t|e)}function Eb(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function _b(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function Sb(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function Ib(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}pb(mb,db),mb.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},mb.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=Ib(e[f-2])+e[f-7]+Sb(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+_b(s)+wb(s,u,a)+gb[c]+e[c]|0,p=Eb(r)+bb(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},mb.prototype._hash=function(){var t=yb.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var Tb=mb,Ob=ut.exports,Pb=Tb,kb=$w,Ab=m.exports.Buffer,Mb=new Array(64);function xb(){this.init(),this._w=Mb,kb.call(this,64,56)}Ob(xb,Pb),xb.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},xb.prototype._hash=function(){var t=Ab.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var Nb=xb,Rb=ut.exports,Bb=$w,Cb=m.exports.Buffer,Ub=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Lb=new Array(160);function Db(){this.init(),this._w=Lb,Bb.call(this,128,112)}function Hb(t,e,r){return r^t&(e^r)}function Fb(t,e,r){return t&e|r&(t|e)}function qb(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function jb(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function Gb(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function Kb(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function Vb(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function Wb(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function $b(t,e){return t>>>0>>0?1:0}Rb(Db,Bb),Db.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Db.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,y=0|this._fl,g=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=Gb(w,b),_=Kb(b,w),S=Vb(w=e[m-4],b=e[m-4+1]),I=Wb(b,w),T=e[m-14],O=e[m-14+1],P=e[m-32],k=e[m-32+1],A=_+O|0,M=E+T+$b(A,_)|0;M=(M=M+S+$b(A=A+I|0,I)|0)+P+$b(A=A+k|0,k)|0,e[m]=M,e[m+1]=A}for(var x=0;x<160;x+=2){M=e[x],A=e[x+1];var N=Fb(r,n,i),R=Fb(f,c,l),B=qb(r,f),C=qb(f,r),U=jb(s,d),L=jb(d,s),D=Ub[x],H=Ub[x+1],F=Hb(s,u,a),q=Hb(d,y,g),j=v+L|0,G=h+U+$b(j,v)|0;G=(G=(G=G+F+$b(j=j+q|0,q)|0)+D+$b(j=j+H|0,H)|0)+M+$b(j=j+A|0,A)|0;var K=C+R|0,V=B+N+$b(K,C)|0;h=a,v=g,a=u,g=y,u=s,y=d,s=o+G+$b(d=p+j|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+V+$b(f=j+K|0,j)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+y|0,this._gl=this._gl+g|0,this._hl=this._hl+v|0,this._ah=this._ah+r+$b(this._al,f)|0,this._bh=this._bh+n+$b(this._bl,c)|0,this._ch=this._ch+i+$b(this._cl,l)|0,this._dh=this._dh+o+$b(this._dl,p)|0,this._eh=this._eh+s+$b(this._el,d)|0,this._fh=this._fh+u+$b(this._fl,y)|0,this._gh=this._gh+a+$b(this._gl,g)|0,this._hh=this._hh+h+$b(this._hl,v)|0},Db.prototype._hash=function(){var t=Cb.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var zb=Db,Xb=ut.exports,Yb=zb,Jb=$w,Qb=m.exports.Buffer,Zb=new Array(160);function tE(){this.init(),this._w=Zb,Jb.call(this,128,112)}Xb(tE,Yb),tE.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},tE.prototype._hash=function(){var t=Qb.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var eE=tE,rE=Kw.exports=function(t){t=t.toLowerCase();var e=rE[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};rE.sha=rb,rE.sha1=lb,rE.sha224=Nb,rE.sha256=Tb,rE.sha384=eE,rE.sha512=zb;var nE=Kw.exports;function iE(t){return(new Gw).update(nE("sha256").update(t).digest()).digest()}var oE,sE=(oE=function(t,e){return oE=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},oE(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}oE(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),uE=function(t,e){this.psbt=t,this.masterFp=e},aE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(uE),hE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=iE(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(aE),fE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new bg,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Gl.sha256(Buffer.from("TapTweak","utf-8"));return Gl.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(F.exports.pointAddScalar(e,r)).slice(1)},e}(aE),cE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=this.createRedeemScript(t),n=iE(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=iE(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(aE),lE=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return sE(e,t),e.prototype.singleKeyCondition=function(t){var e=new bg,r=iE(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(aE),pE=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},dE=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return mE(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new vE(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new vE(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function GE(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,jE(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,jE(t.script.length),t.script])}))),r}function KE(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,jE(t.script.length),t.script,t.sequence])}));var a=GE(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),jE(t.inputs.length),s,a])}var VE=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},WE=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new wE(e,bE(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return VE(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I;return WE(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new kE,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new fE(e,r):t.additionals.includes("bech32")?new lE(e,r):t.segwit?new cE(e,r):new hE(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],y=0,T.label=2;case 2:return y0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new bg).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new bg;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new bg;FE(h,f),FE(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new bg).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}HE(t,r)}}(r),I=function(t){var e,r,n=new bg;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new bg,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function h_(t,e,r){return s_(this,void 0,void 0,(function(){var n,i,o,s;return u_(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function f_(t,e,r,n){return void 0===n&&(n=[]),s_(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N=this;return u_(this,(function(R){switch(R.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return s_(N,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return u_(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>_g?_g:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=a_(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,h_(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return h_(t,e)},[4,h_(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),jE(o.length)]),e)];case 1:R.sent(),R.label=2;case 2:R.trys.push([2,8,9,10]),d=a_(o),y=d.next(),R.label=3;case 3:return y.done?[3,7]:(g=y.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?g.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([g.prevout,m,v?Buffer.from([0]):jE(g.script.length)]),[4,h_(t,O)]);case 4:return R.sent(),[4,f?p(Buffer.concat([g.script,g.sequence])):v?p(g.sequence):l(g.script,g.sequence)];case 5:R.sent(),R.label=6;case 6:return y=d.next(),[3,3];case 7:return[3,10];case 8:return w=R.sent(),k={error:w},[3,10];case 9:try{y&&!y.done&&(A=d.return)&&A.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,h_(t,jE(s.length))];case 11:R.sent(),R.label=12;case 12:R.trys.push([12,17,18,19]),b=a_(s),E=b.next(),R.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),jE(_.script.length),_.script]),[4,h_(t,O)]);case 14:R.sent(),R.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=R.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([jE(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return P=R.sent(),o_(P,"missing result in processScriptBlocks"),[2,P]}}))}))}var c_=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},l_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function d_(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function y_(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),c_(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P;return l_(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),jE(r.inputs.length)]),[4,d_(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=p_(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,y=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,y.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,y,f?Buffer.from([0]):Buffer.alloc(0),jE(p.script.length)]),[4,d_(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),g=[],v=0,0===p.script.length)g.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>_g?_g:p.script.length-v,v+m!==p.script.length?g.push(p.script.slice(v,v+m)):g.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=p_(g),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,d_(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(P=w.return)&&P.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function g_(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=nE("sha256").update(nE("sha256").update(KE(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function v_(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=k(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var m_=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},w_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:_g,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var __=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},S_=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},A_={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function M_(t,e){return O_(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N,R,B,C,U,L,D,H,F,q,j,G,K,V,W,$,z,X,Y,J,Q,Z,tt,et,rt,nt,it,ot,st,ut,at;return P_(this,(function(ht){switch(ht.label){case 0:if(r=T_(T_({},A_),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,y=r.onDeviceSignatureRequested,void 0!==(g=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,I_(t)];case 2:return v=ht.sent(),g=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||wg.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return g=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),P=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),A=[],M=[],x=[],N=[],R=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},U=T&&!g?g_:f_,L=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=k_(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:F=ht.sent(),QE("hw","got trustedInput="+F),(q=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:Sg,0),A.push({trustedInput:!0,value:Buffer.from(F,"hex"),sequence:q}),ht.label=8;case 8:j=$[0].outputs,G=$[1],j&&G<=j.length-1&&M.push(j[G]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:Sg,0),{script:O,prevout:P,sequence:e}})),B)return[3,18];V=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),iE(N[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[A[it]]:A,T?X.inputs=[T_(T_({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,y_(t,!T&&R,X,Y,T,!!l&&!b,c,g)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,b_(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,E_(t,L,c)];case 30:ht.sent(),ht.label=31;case 31:return R&&(d(),w(1,0)),[4,v_(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,R&&(R=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},L_={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function D_(t,e){return B_(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S,I,T,O,P,k,A,M,x,N,R,B,C;return C_(this,(function(U){switch(U.label){case 0:r=R_(R_({},L_),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],y=[],g=!0,v=!1,m={inputs:[],version:l},w=a?g_:f_,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),E=U_(n),_=E.next(),U.label=2;case 2:return _.done?[3,6]:(A=_.value,v?[3,4]:[4,w(t,A[1],A[0])]);case 3:S=U.sent(),(P=Buffer.alloc(4)).writeUInt32LE(A.length>=4&&"number"==typeof A[3]?A[3]:Sg,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:P}),U.label=4;case 4:I=A[0].outputs,T=A[1],I&&T<=I.length-1&&d.push(I[T]),U.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=U.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:Sg,0),m.inputs.push({script:f,prevout:c,sequence:P});return a?[4,y_(t,!0,m,p,!0)]:[3,12];case 10:return U.sent(),[4,E_(t,b)];case 11:U.sent(),U.label=12;case 12:k=0,U.label=13;case 13:return k=3&&"string"==typeof A[2]?Buffer.from(A[2],"hex"):d[k].script,x=Object.assign({},m),N=a?[p[k]]:p,a?x.inputs=[R_(R_({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,y_(t,!a&&g,x,N,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,E_(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,v_(t,i[k],s,u)];case 17:R=U.sent(),y.push(a?R.toString("hex"):R.slice(0,R.length-1).toString("hex")),m.inputs[k].script=f,g&&(g=!1),U.label=18;case 18:return k++,[3,13];case 19:return[2,y]}}))}))}var H_=function(){return H_=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},c.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return c.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return u=c.sent(),a=u[0]-48,0===(h=u.slice(4,4+u[3]))[0]&&(h=h.slice(1)),h=h.toString("hex"),o=4+u[3]+2,0===(f=u.slice(o,o+u[o-1]))[0]&&(f=f.slice(1)),f=f.toString("hex"),[2,{v:a,r:h,s:f}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),M_(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),D_(this.transport,t)},t}();function G_(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var K_=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function V_(t){return nE("sha256").update(t).digest()}var W_,$_=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new yE(t.map((function(t){return gE(t)}))),this.values=e,this.valuesTree=new yE(e.map((function(t){return gE(t)})))}return t.prototype.commitment=function(){return Buffer.concat([jE(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),z_=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),X_=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},Y_=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},tS=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(W_||(W_={}));var rS,nS,iS=function(){},oS=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=W_.YIELD,n.results=e,n}return Q_(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(iS),sS=function(t){function e(e,r){var n=t.call(this)||this;return n.code=W_.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return Q_(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=jE(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,tS([],Z_(a.slice(-f)),!1)),Buffer.concat(tS([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],Z_(a.slice(0,h)),!1))},e}(iS),aS=function(t){function e(e){var r=t.call(this)||this;return r.code=W_.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return Q_(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(rS||(rS={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(nS||(nS={}));var dS=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return cS(this,void 0,void 0,(function(){var n,i,o;return lS(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,nS.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return cS(this,void 0,void 0,(function(){return lS(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(rS.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),P(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return cS(this,void 0,void 0,(function(){var o,s;return lS(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new fS((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(rS.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return cS(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,y,g,v,m,w,b,E,_,S;return lS(this,(function(I){switch(I.label){case 0:if(i=new J_(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new fS(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=pS(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=pS(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new yE(i.inputMapCommitments.map((function(t){return gE(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new yE(i.outputMapCommitments.map((function(t){return gE(t)}))).getRoot(),[4,this.makeRequest(rS.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),jE(i.getGlobalInputCount()),c,jE(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(y=pS(p),g=y.next();!g.done;g=y.next())v=g.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{g&&!g.done&&(S=y.return)&&S.call(y)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return cS(this,void 0,void 0,(function(){return lS(this,(function(t){return[2,this.makeRequest(rS.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var yS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},gS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof zE&&"bech32m"!=r.format)||r.verify&&0!=r.verify||mS(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),y=Buffer.from(t,"hex"),g=y.slice(a,a+4),v=g.equals(Buffer.from([3,0,0,128]))||g.equals(Buffer.from([4,0,0,128])),m=g.equals(Buffer.from([1,0,0,0]))||g.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===y[a]&&0!==y[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=y.slice(a,4+a),a+=4),v&&(c=y.slice(a,4+a),a+=4);var w=qE(y,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new j_(this.transport)},t.prototype.new=function(){return new zE(new dS(this.transport))},t}();function mS(t){var e=2147483648,r=M(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var wS=Object.freeze({__proto__:null,default:vS}),bS={},ES={},_S={},SS={};Object.defineProperty(SS,"__esModule",{value:!0});var IS="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},TS={},OS={};SS.addCustomErrorDeserializer=function(t,e){OS[t]=e};var PS=SS.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,TS[t]=e,e};function kS(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":IS(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=kS(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}SS.deserializeError=function t(e){if("object"===(void 0===e?"undefined":IS(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=OS[i];if(o)n=o(e);else{var s="Error"===i?Error:TS[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=PS(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},SS.serializeError=function(t){return t?"object"===(void 0===t?"undefined":IS(t))?kS(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(_S,"__esModule",{value:!0}),_S.StatusCodes=_S.DBNotReset=_S.DBWrongPassword=_S.NoDBPathGiven=_S.FirmwareOrAppUpdateRequired=_S.LedgerAPI5xx=_S.LedgerAPI4xx=_S.GenuineCheckFailed=_S.PairingFailed=_S.SyncError=_S.FeeTooHigh=_S.FeeRequired=_S.FeeNotLoaded=_S.CantScanQRCode=_S.ETHAddressNonEIP=_S.WrongAppForCurrency=_S.WrongDeviceForAccount=_S.WebsocketConnectionFailed=_S.WebsocketConnectionError=_S.DeviceShouldStayInApp=_S.TransportWebUSBGestureRequired=_S.TransportInterfaceNotAvailable=_S.TransportOpenUserCancelled=_S.UserRefusedOnDevice=_S.UserRefusedAllowManager=_S.UserRefusedFirmwareUpdate=_S.UserRefusedAddress=_S.UserRefusedDeviceNameChange=_S.UpdateYourApp=_S.UnavailableTezosOriginatedAccountSend=_S.UnavailableTezosOriginatedAccountReceive=_S.RecipientRequired=_S.MCUNotGenuineToDashboard=_S.UnexpectedBootloader=_S.TimeoutTagged=_S.RecommendUndelegation=_S.RecommendSubAccountsToEmpty=_S.PasswordIncorrectError=_S.PasswordsDontMatchError=_S.GasLessThanEstimate=_S.NotSupportedLegacyAddress=_S.NotEnoughGas=_S.NoAccessToCamera=_S.NotEnoughBalanceBecauseDestinationNotCreated=_S.NotEnoughSpendableBalance=_S.NotEnoughBalanceInParentAccount=_S.NotEnoughBalanceToDelegate=_S.NotEnoughBalance=_S.NoAddressesFound=_S.NetworkDown=_S.ManagerUninstallBTCDep=_S.ManagerNotEnoughSpaceError=_S.ManagerFirmwareNotEnoughSpaceError=_S.ManagerDeviceLockedError=_S.ManagerAppDepUninstallRequired=_S.ManagerAppDepInstallRequired=_S.ManagerAppRelyOnBTCError=_S.ManagerAppAlreadyInstalledError=_S.LedgerAPINotAvailable=_S.LedgerAPIErrorWithMessage=_S.LedgerAPIError=_S.UnknownMCU=_S.LatestMCUInstalledError=_S.InvalidAddressBecauseDestinationIsAlsoSource=_S.InvalidAddress=_S.InvalidXRPTag=_S.HardResetFail=_S.FeeEstimationFailed=_S.EthAppPleaseEnableContractData=_S.EnpointConfigError=_S.DisconnectedDeviceDuringOperation=_S.DisconnectedDevice=_S.DeviceSocketNoBulkStatus=_S.DeviceSocketFail=_S.DeviceNameInvalid=_S.DeviceHalted=_S.DeviceInOSUExpected=_S.DeviceOnDashboardUnexpected=_S.DeviceOnDashboardExpected=_S.DeviceNotGenuineError=_S.DeviceGenuineSocketEarlyClose=_S.DeviceAppVerifyNotSupported=_S.CurrencyNotSupported=_S.CashAddrNotSupported=_S.CantOpenDevice=_S.BtcUnmatchedApp=_S.BluetoothRequired=_S.AmountRequired=_S.AccountNotSupported=_S.AccountNameRequiredError=_S.addCustomErrorDeserializer=_S.createCustomErrorClass=_S.deserializeError=_S.serializeError=void 0,_S.TransportError=MS,_S.getAltStatusMessage=NS,_S.TransportStatusError=RS;var AS=SS;function MS(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}_S.serializeError=AS.serializeError,_S.deserializeError=AS.deserializeError,_S.createCustomErrorClass=AS.createCustomErrorClass,_S.addCustomErrorDeserializer=AS.addCustomErrorDeserializer,_S.AccountNameRequiredError=(0,AS.createCustomErrorClass)("AccountNameRequired"),_S.AccountNotSupported=(0,AS.createCustomErrorClass)("AccountNotSupported"),_S.AmountRequired=(0,AS.createCustomErrorClass)("AmountRequired"),_S.BluetoothRequired=(0,AS.createCustomErrorClass)("BluetoothRequired"),_S.BtcUnmatchedApp=(0,AS.createCustomErrorClass)("BtcUnmatchedApp"),_S.CantOpenDevice=(0,AS.createCustomErrorClass)("CantOpenDevice"),_S.CashAddrNotSupported=(0,AS.createCustomErrorClass)("CashAddrNotSupported"),_S.CurrencyNotSupported=(0,AS.createCustomErrorClass)("CurrencyNotSupported"),_S.DeviceAppVerifyNotSupported=(0,AS.createCustomErrorClass)("DeviceAppVerifyNotSupported"),_S.DeviceGenuineSocketEarlyClose=(0,AS.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),_S.DeviceNotGenuineError=(0,AS.createCustomErrorClass)("DeviceNotGenuine"),_S.DeviceOnDashboardExpected=(0,AS.createCustomErrorClass)("DeviceOnDashboardExpected"),_S.DeviceOnDashboardUnexpected=(0,AS.createCustomErrorClass)("DeviceOnDashboardUnexpected"),_S.DeviceInOSUExpected=(0,AS.createCustomErrorClass)("DeviceInOSUExpected"),_S.DeviceHalted=(0,AS.createCustomErrorClass)("DeviceHalted"),_S.DeviceNameInvalid=(0,AS.createCustomErrorClass)("DeviceNameInvalid"),_S.DeviceSocketFail=(0,AS.createCustomErrorClass)("DeviceSocketFail"),_S.DeviceSocketNoBulkStatus=(0,AS.createCustomErrorClass)("DeviceSocketNoBulkStatus"),_S.DisconnectedDevice=(0,AS.createCustomErrorClass)("DisconnectedDevice"),_S.DisconnectedDeviceDuringOperation=(0,AS.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),_S.EnpointConfigError=(0,AS.createCustomErrorClass)("EnpointConfig"),_S.EthAppPleaseEnableContractData=(0,AS.createCustomErrorClass)("EthAppPleaseEnableContractData"),_S.FeeEstimationFailed=(0,AS.createCustomErrorClass)("FeeEstimationFailed"),_S.HardResetFail=(0,AS.createCustomErrorClass)("HardResetFail"),_S.InvalidXRPTag=(0,AS.createCustomErrorClass)("InvalidXRPTag"),_S.InvalidAddress=(0,AS.createCustomErrorClass)("InvalidAddress"),_S.InvalidAddressBecauseDestinationIsAlsoSource=(0,AS.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),_S.LatestMCUInstalledError=(0,AS.createCustomErrorClass)("LatestMCUInstalledError"),_S.UnknownMCU=(0,AS.createCustomErrorClass)("UnknownMCU"),_S.LedgerAPIError=(0,AS.createCustomErrorClass)("LedgerAPIError"),_S.LedgerAPIErrorWithMessage=(0,AS.createCustomErrorClass)("LedgerAPIErrorWithMessage"),_S.LedgerAPINotAvailable=(0,AS.createCustomErrorClass)("LedgerAPINotAvailable"),_S.ManagerAppAlreadyInstalledError=(0,AS.createCustomErrorClass)("ManagerAppAlreadyInstalled"),_S.ManagerAppRelyOnBTCError=(0,AS.createCustomErrorClass)("ManagerAppRelyOnBTC"),_S.ManagerAppDepInstallRequired=(0,AS.createCustomErrorClass)("ManagerAppDepInstallRequired"),_S.ManagerAppDepUninstallRequired=(0,AS.createCustomErrorClass)("ManagerAppDepUninstallRequired"),_S.ManagerDeviceLockedError=(0,AS.createCustomErrorClass)("ManagerDeviceLocked"),_S.ManagerFirmwareNotEnoughSpaceError=(0,AS.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),_S.ManagerNotEnoughSpaceError=(0,AS.createCustomErrorClass)("ManagerNotEnoughSpace"),_S.ManagerUninstallBTCDep=(0,AS.createCustomErrorClass)("ManagerUninstallBTCDep"),_S.NetworkDown=(0,AS.createCustomErrorClass)("NetworkDown"),_S.NoAddressesFound=(0,AS.createCustomErrorClass)("NoAddressesFound"),_S.NotEnoughBalance=(0,AS.createCustomErrorClass)("NotEnoughBalance"),_S.NotEnoughBalanceToDelegate=(0,AS.createCustomErrorClass)("NotEnoughBalanceToDelegate"),_S.NotEnoughBalanceInParentAccount=(0,AS.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),_S.NotEnoughSpendableBalance=(0,AS.createCustomErrorClass)("NotEnoughSpendableBalance"),_S.NotEnoughBalanceBecauseDestinationNotCreated=(0,AS.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),_S.NoAccessToCamera=(0,AS.createCustomErrorClass)("NoAccessToCamera"),_S.NotEnoughGas=(0,AS.createCustomErrorClass)("NotEnoughGas"),_S.NotSupportedLegacyAddress=(0,AS.createCustomErrorClass)("NotSupportedLegacyAddress"),_S.GasLessThanEstimate=(0,AS.createCustomErrorClass)("GasLessThanEstimate"),_S.PasswordsDontMatchError=(0,AS.createCustomErrorClass)("PasswordsDontMatch"),_S.PasswordIncorrectError=(0,AS.createCustomErrorClass)("PasswordIncorrect"),_S.RecommendSubAccountsToEmpty=(0,AS.createCustomErrorClass)("RecommendSubAccountsToEmpty"),_S.RecommendUndelegation=(0,AS.createCustomErrorClass)("RecommendUndelegation"),_S.TimeoutTagged=(0,AS.createCustomErrorClass)("TimeoutTagged"),_S.UnexpectedBootloader=(0,AS.createCustomErrorClass)("UnexpectedBootloader"),_S.MCUNotGenuineToDashboard=(0,AS.createCustomErrorClass)("MCUNotGenuineToDashboard"),_S.RecipientRequired=(0,AS.createCustomErrorClass)("RecipientRequired"),_S.UnavailableTezosOriginatedAccountReceive=(0,AS.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),_S.UnavailableTezosOriginatedAccountSend=(0,AS.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),_S.UpdateYourApp=(0,AS.createCustomErrorClass)("UpdateYourApp"),_S.UserRefusedDeviceNameChange=(0,AS.createCustomErrorClass)("UserRefusedDeviceNameChange"),_S.UserRefusedAddress=(0,AS.createCustomErrorClass)("UserRefusedAddress"),_S.UserRefusedFirmwareUpdate=(0,AS.createCustomErrorClass)("UserRefusedFirmwareUpdate"),_S.UserRefusedAllowManager=(0,AS.createCustomErrorClass)("UserRefusedAllowManager"),_S.UserRefusedOnDevice=(0,AS.createCustomErrorClass)("UserRefusedOnDevice"),_S.TransportOpenUserCancelled=(0,AS.createCustomErrorClass)("TransportOpenUserCancelled"),_S.TransportInterfaceNotAvailable=(0,AS.createCustomErrorClass)("TransportInterfaceNotAvailable"),_S.TransportWebUSBGestureRequired=(0,AS.createCustomErrorClass)("TransportWebUSBGestureRequired"),_S.DeviceShouldStayInApp=(0,AS.createCustomErrorClass)("DeviceShouldStayInApp"),_S.WebsocketConnectionError=(0,AS.createCustomErrorClass)("WebsocketConnectionError"),_S.WebsocketConnectionFailed=(0,AS.createCustomErrorClass)("WebsocketConnectionFailed"),_S.WrongDeviceForAccount=(0,AS.createCustomErrorClass)("WrongDeviceForAccount"),_S.WrongAppForCurrency=(0,AS.createCustomErrorClass)("WrongAppForCurrency"),_S.ETHAddressNonEIP=(0,AS.createCustomErrorClass)("ETHAddressNonEIP"),_S.CantScanQRCode=(0,AS.createCustomErrorClass)("CantScanQRCode"),_S.FeeNotLoaded=(0,AS.createCustomErrorClass)("FeeNotLoaded"),_S.FeeRequired=(0,AS.createCustomErrorClass)("FeeRequired"),_S.FeeTooHigh=(0,AS.createCustomErrorClass)("FeeTooHigh"),_S.SyncError=(0,AS.createCustomErrorClass)("SyncError"),_S.PairingFailed=(0,AS.createCustomErrorClass)("PairingFailed"),_S.GenuineCheckFailed=(0,AS.createCustomErrorClass)("GenuineCheckFailed"),_S.LedgerAPI4xx=(0,AS.createCustomErrorClass)("LedgerAPI4xx"),_S.LedgerAPI5xx=(0,AS.createCustomErrorClass)("LedgerAPI5xx"),_S.FirmwareOrAppUpdateRequired=(0,AS.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),_S.NoDBPathGiven=(0,AS.createCustomErrorClass)("NoDBPathGiven"),_S.DBWrongPassword=(0,AS.createCustomErrorClass)("DBWrongPassword"),_S.DBNotReset=(0,AS.createCustomErrorClass)("DBNotReset"),MS.prototype=new Error,(0,AS.addCustomErrorDeserializer)("TransportError",(function(t){return new MS(t.message,t.id)}));var xS=_S.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function NS(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function RS(t){this.name="TransportStatusError";var e=Object.keys(xS).find((function(e){return xS[e]===t}))||"UNKNOWN_ERROR",r=NS(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}RS.prototype=new Error,(0,AS.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new RS(t.statusCode)})),Object.defineProperty(ES,"__esModule",{value:!0}),ES.getAltStatusMessage=ES.StatusCodes=ES.TransportStatusError=ES.TransportError=void 0;var BS,CS=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[DS.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new DS.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new DS.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=FS(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new DS.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return CS(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new DS.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new DS.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();qS.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",qS.ErrorMessage_NoDeviceFound="No Ledger device found",ES.default=qS;var jS={};Object.defineProperty(jS,"__esModule",{value:!0});var GS=_S;function KS(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var VS={data:Buffer.alloc(0),dataLength:0,sequence:0};jS.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([KS(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var WS={};Object.defineProperty(WS,"__esModule",{value:!0});var $S=Object.assign||function(t){for(var e=1;e>8;return YS.find((function(t){return t.productIdMM===r}))},WS.identifyProductName=function(t){var e=XS[t];return YS.find((function(t){return t.id===e}))};var JS=[],QS={};for(var ZS in zS){var tI=zS[ZS],eI=tI.bluetoothSpec;if(eI)for(var rI=0;rI0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",lI());case 6:case"end":return t.stop()}}),t,this)}))),function(){return cI.apply(this,arguments)});var dI=WS;function yI(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var gI=[{vendorId:dI.ledgerUSBVendorId}];aI.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(bS,"__esModule",{value:!0});var vI=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,wI.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,EI.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,EI.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new _I.DisconnectedDeviceDuringOperation(e.message);throw e}))}},kI=bS.default=OI,AI=Object.freeze(u({__proto__:null,default:kI},[bS]));t.Btc=wS,t.TransportWebUSB=AI,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,e){var r=ht,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(h,h.exports);var ft=h.exports.Buffer;var ct=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ft.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ft.from(e)),!ft.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,k=0|s[6],P=8191&k,M=k>>>13,x=0|s[7],R=8191&x,N=x>>>13,B=0|s[8],C=8191&B,L=B>>>13,U=0|s[9],D=8191&U,H=U>>>13,j=0|u[0],F=8191&j,q=j>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(c,F))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,F)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,F),i=(i=Math.imul(d,q))+Math.imul(g,F)|0,o=Math.imul(g,q);var vt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,F),i=(i=Math.imul(v,q))+Math.imul(m,F)|0,o=Math.imul(m,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,F),i=(i=Math.imul(b,q))+Math.imul(E,F)|0,o=Math.imul(E,q),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,W)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,F),i=(i=Math.imul(S,q))+Math.imul(I,F)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,W)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,F),i=(i=Math.imul(O,q))+Math.imul(A,F)|0,o=Math.imul(A,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(P,F),i=(i=Math.imul(P,q))+Math.imul(M,F)|0,o=Math.imul(M,q),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,W)|0)+Math.imul(A,K)|0,o=o+Math.imul(A,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(R,F),i=(i=Math.imul(R,q))+Math.imul(N,F)|0,o=Math.imul(N,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,W)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,F),i=(i=Math.imul(C,q))+Math.imul(L,F)|0,o=Math.imul(L,q),n=n+Math.imul(R,K)|0,i=(i=i+Math.imul(R,W)|0)+Math.imul(N,K)|0,o=o+Math.imul(N,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,F),i=(i=Math.imul(D,q))+Math.imul(H,F)|0,o=Math.imul(H,q),n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(L,K)|0,o=o+Math.imul(L,W)|0,n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,z)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,z)|0,n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,J)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(N,rt)|0,o=o+Math.imul(N,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(L,rt)|0,o=o+Math.imul(L,nt)|0,n=n+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,st)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ct)|0,o=o+Math.imul(A,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(L,ot)|0,o=o+Math.imul(L,st)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ht)|0)+Math.imul(N,at)|0,o=o+Math.imul(N,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(L,at)|0,o=o+Math.imul(L,ht)|0,n=n+Math.imul(R,ct)|0,i=(i=i+Math.imul(R,lt)|0)+Math.imul(N,ct)|0,o=o+Math.imul(N,lt)|0;var xt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(L,ct)|0,o=o+Math.imul(L,lt)|0;var Rt=(h+(n=n+Math.imul(R,dt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(N,dt)|0))<<13)|0;h=((o=o+Math.imul(N,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Nt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(L,dt)|0))<<13)|0;h=((o=o+Math.imul(L,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=kt,a[13]=Pt,a[14]=Mt,a[15]=xt,a[16]=Rt,a[17]=Nt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Rt);var Nt={},Bt="6.5.4",Ct={},Lt=Ut;function Ut(t,e){if(!t)throw new Error(e||"Assertion failed")}Ut.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Dt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Dt),function(t){var e=t,r=Rt.exports,n=Lt,i=Dt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ct);var Ht,jt={exports:{}};function Ft(t){this.rand=t}if(jt.exports=function(t){return Ht||(Ht=new Ft(null)),Ht.generate(t)},jt.exports.Rand=Ft,Ft.prototype.generate=function(t){return this._rand(t)},Ft.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Yt=Xt;function Jt(t,e){this.curve=t,this.type=e,this.precomputed=null}Xt.prototype.point=function(){throw new Error("Not implemented")},Xt.prototype.validate=function(){throw new Error("Not implemented")},Xt.prototype._fixedNafMul=function(t,e){zt(t.precomputed);var r=t._getDoubles(),n=Vt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];zt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Xt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=$t(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Jt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},se.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},se.prototype.pointFromX=function(t,e){(t=new re(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},se.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},se.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ae.prototype.isInfinity=function(){return this.inf},ae.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ae.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ae.prototype.getX=function(){return this.x.fromRed()},ae.prototype.getY=function(){return this.y.fromRed()},ae.prototype.mul=function(t){return t=new re(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ae.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ae.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ae.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ae.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ae.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ne(he,ie.BasePoint),se.prototype.jpoint=function(t,e,r){return new he(this,t,e,r)},he.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},he.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},he.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},he.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},he.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},he.prototype.inspect=function(){return this.isInfinity()?"":""},he.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var fe=Rt.exports,ce=Zt.exports,le=Yt,pe=Ct;function de(t){le.call(this,"mont",t),this.a=new fe(t.a,16).toRed(this.red),this.b=new fe(t.b,16).toRed(this.red),this.i4=new fe(4).toRed(this.red).redInvm(),this.two=new fe(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}ce(de,le);var ge=de;function ye(t,e,r){le.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new fe(e,16),this.z=new fe(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}de.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},ce(ye,le.BasePoint),de.prototype.decodePoint=function(t,e){return this.point(pe.toArray(t,e),1)},de.prototype.point=function(t,e){return new ye(this,t,e)},de.prototype.pointFromJSON=function(t){return ye.fromJSON(this,t)},ye.prototype.precompute=function(){},ye.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ye.fromJSON=function(t,e){return new ye(t,e[0],e[1]||t.one)},ye.prototype.inspect=function(){return this.isInfinity()?"":""},ye.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ye.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ye.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ye.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ye.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ye.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ye.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ve=Ct,me=Rt.exports,we=Zt.exports,be=Yt,Ee=ve.assert;function _e(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,be.call(this,"edwards",t),this.a=new me(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new me(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new me(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ee(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}we(_e,be);var Se=_e;function Ie(t,e,r,n,i){be.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new me(e,16),this.y=new me(r,16),this.z=n?new me(n,16):this.curve.one,this.t=i&&new me(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}_e.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},_e.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},_e.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},_e.prototype.pointFromX=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},_e.prototype.pointFromY=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},_e.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},we(Ie,be.BasePoint),_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},_e.prototype.point=function(t,e,r,n){return new Ie(this,t,e,r,n)},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1],e[2])},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ie.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Ie.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ie.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ie.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Ie.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Ie.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ie.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ie.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ie.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ie.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ie.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ie.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ie.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ie.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ie.prototype.toP=Ie.prototype.normalize,Ie.prototype.mixedAdd=Ie.prototype.add,function(t){var e=t;e.base=Yt,e.short=ue,e.mont=ge,e.edwards=Se}(Gt);var Te={},Oe={},Ae={},ke=Lt,Pe=Zt.exports;function Me(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Re(t){return 1===t.length?"0"+t:t}function Ne(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ae.inherits=Pe,Ae.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Me(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ae.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ae.rotr32=function(t,e){return t>>>e|t<<32-e},Ae.rotl32=function(t,e){return t<>>32-e},Ae.sum32=function(t,e){return t+e>>>0},Ae.sum32_3=function(t,e,r){return t+e+r>>>0},Ae.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ae.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ae.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ae.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ae.sum64_lo=function(t,e,r,n){return e+n>>>0},Ae.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ae.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ae.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ae.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ae.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ae.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ae.shr64_hi=function(t,e,r){return t>>>r},Ae.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Be={},Ce=Ae,Le=Lt;function Ue(){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}Be.BlockHash=Ue,Ue.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},He.g1_256=function(t){return je(t,17)^je(t,19)^t>>>10};var Ke=Ae,We=Be,Ve=He,$e=Ke.rotl32,ze=Ke.sum32,Xe=Ke.sum32_5,Ye=Ve.ft_1,Je=We.BlockHash,Ze=[1518500249,1859775393,2400959708,3395469782];function Qe(){if(!(this instanceof Qe))return new Qe;Je.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ke.inherits(Qe,Je);var tr=Qe;Qe.blockSize=512,Qe.outSize=160,Qe.hmacStrength=80,Qe.padLength=64,Qe.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),bn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var An=On;On.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},On.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=In.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Rn=Rt.exports,Nn=Ct,Bn=Nn.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Bn(t.r&&t.s,"Signature without r or s"),this.r=new Rn(t.r,16),this.s=new Rn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Ln=Cn;function Un(){this.place=0}function Dn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function Hn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Nn.toArray(t,e);var r=new Un;if(48!==t[r.place++])return!1;var n=Dn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Dn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Dn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Rn(o),this.s=new Rn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=Hn(e),r=Hn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];jn(n,e.length),(n=n.concat(e)).push(2),jn(n,r.length);var i=n.concat(r),o=[48];return jn(o,i.length),o=o.concat(i),Nn.encode(o,t)};var Fn=Rt.exports,qn=An,Gn=Ct,Kn=Te,Wn=jt.exports,Vn=Gn.assert,$n=xn,zn=Ln;function Xn(t){if(!(this instanceof Xn))return new Xn(t);"string"==typeof t&&(Vn(Object.prototype.hasOwnProperty.call(Kn,t),"Unknown curve "+t),t=Kn[t]),t instanceof Kn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Yn=Xn;Xn.prototype.keyPair=function(t){return new $n(this,t)},Xn.prototype.keyFromPrivate=function(t,e){return $n.fromPrivate(this,t,e)},Xn.prototype.keyFromPublic=function(t,e){return $n.fromPublic(this,t,e)},Xn.prototype.genKeyPair=function(t){t||(t={});for(var e=new qn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Wn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Fn(2));;){var i=new Fn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Xn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Xn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Fn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new qn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Fn(1)),h=0;;h++){var f=n.k?n.k(h):new Fn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new zn({r:p,s:d,recoveryParam:g})}}}}}},Xn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Fn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new zn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Xn.prototype.recoverPubKey=function(t,e,r,n){Vn((3&r)===r,"The recovery param is more than two bits"),e=new zn(e,n);var i=this.n,o=new Fn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Xn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new zn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Jn=Ct,Zn=Jn.assert,Qn=Jn.parseBytes,ti=Jn.cachedProperty;function ei(t,e){this.eddsa=t,this._secret=Qn(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=Qn(e.pub)}ei.fromPublic=function(t,e){return e instanceof ei?e:new ei(t,{pub:e})},ei.fromSecret=function(t,e){return e instanceof ei?e:new ei(t,{secret:e})},ei.prototype.secret=function(){return this._secret},ti(ei,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ti(ei,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ti(ei,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ti(ei,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ti(ei,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ti(ei,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ei.prototype.sign=function(t){return Zn(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ei.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ei.prototype.getSecret=function(t){return Zn(this._secret,"KeyPair is public only"),Jn.encode(this.secret(),t)},ei.prototype.getPublic=function(t){return Jn.encode(this.pubBytes(),t)};var ri=ei,ni=Rt.exports,ii=Ct,oi=ii.assert,si=ii.cachedProperty,ui=ii.parseBytes;function ai(t,e){this.eddsa=t,"object"!=typeof e&&(e=ui(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),oi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ni&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}si(ai,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),si(ai,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),si(ai,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),si(ai,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),ai.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},ai.prototype.toHex=function(){return ii.encode(this.toBytes(),"hex").toUpperCase()};var hi=ai,fi=Oe,ci=Te,li=Ct,pi=li.assert,di=li.parseBytes,gi=ri,yi=hi;function vi(t){if(pi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof vi))return new vi(t);t=ci[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=fi.sha512}var mi=vi;vi.prototype.sign=function(t,e){t=di(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},vi.prototype.verify=function(t,e,r){t=di(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},vi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Ki(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Oi)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function Hi(t){return 4!==t[0]}function ji(t){return!!Li(t)&&(t.compare(Oi)>0&&t.compare(Ai)<0)}function Fi(t,e){return void 0===t&&void 0!==e?Hi(e):void 0===t||t}function qi(t){return new Si(t)}function Gi(t){return t.toArrayLike(Buffer,"be",32)}function Ki(t){return Ii.curve.decodePoint(t)}function Wi(t,e){return Buffer.from(t._encode(e))}function Vi(t,e,r){if(!Li(t))throw new TypeError(Ci);if(!ji(e))throw new TypeError(Ri);if(void 0!==r&&!Li(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=qi(e),i=qi(t);let o,s;Ti(t,e,(function(t){const e=qi(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Pi),0!==o.isZero()&&(s=e.invm(Pi).mul(i.add(n.mul(o))).umod(Pi),0!==s.isZero()))}),ji,r),s.cmp(Mi)>0&&(s=Pi.sub(s));const u=Buffer.allocUnsafe(64);return Gi(o).copy(u,0),Gi(s).copy(u,32),u}var $i={isPoint:Di,isPointCompressed:function(t){return!!Di(t)&&Hi(t)},isPrivate:ji,pointAdd:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Di(e))throw new TypeError(Ni);const n=Ki(t),i=Ki(e),o=n.add(i);return o.isInfinity()?null:Wi(o,Fi(r,t))},pointAddScalar:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Ui(e))throw new TypeError(Bi);const n=Fi(r,t),i=Ki(t);if(0===e.compare(Oi))return Wi(i,n);const o=qi(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:Wi(u,n)},pointCompress:function(t,e){if(!Di(t))throw new TypeError(Ni);const r=Ki(t);if(r.isInfinity())throw new TypeError(Ni);return Wi(r,Fi(e,t))},pointFromScalar:function(t,e){if(!ji(t))throw new TypeError(Ri);const r=qi(t),n=xi.mul(r);return n.isInfinity()?null:Wi(n,Fi(e))},pointMultiply:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Ui(e))throw new TypeError(Bi);const n=Fi(r,t),i=Ki(t),o=qi(e),s=i.mul(o);return s.isInfinity()?null:Wi(s,n)},privateAdd:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Ui(e))throw new TypeError(Bi);const r=qi(t),n=qi(e),i=Gi(r.add(n).umod(Pi));return ji(i)?i:null},privateSub:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Ui(e))throw new TypeError(Bi);const r=qi(t),n=qi(e),i=Gi(r.sub(n).umod(Pi));return ji(i)?i:null},sign:function(t,e){return Vi(t,e)},signWithEntropy:function(t,e,r){return Vi(t,e,r)},verify:function(t,e,r,n){if(!Li(t))throw new TypeError(Ci);if(!Di(e))throw new TypeError(Ni);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Ai)<0&&r.compare(Ai)<0}(r))throw new TypeError("Expected Signature");const i=Ki(e),o=qi(r.slice(0,32)),s=qi(r.slice(32,64));if(n&&s.cmp(Mi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=qi(t),a=s.invm(Pi),h=u.mul(a).umod(Pi),f=o.mul(a).umod(Pi),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Pi).eq(o)}};try{xt.exports=require("./native")}catch(t){xt.exports=$i}var zi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Xi in zi.Null=zi.Nil,zi)zi[Xi].toJSON=function(t){return t}.bind(null,Xi);var Yi=zi,Ji=Yi;function Zi(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Qi(t){return Ji.Nil(t)?"":Zi(t.constructor)}function to(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function eo(t){return Ji.Function(t)?t.toJSON?t.toJSON():Zi(t):Ji.Array(t)?"Array":t&&Ji.Object(t)?"Object":void 0!==t?t:""}function ro(t,e,r){var n=function(t){return Ji.Function(t)?"":Ji.String(t)?JSON.stringify(t):t&&Ji.Object(t)?"":t}(e);return"Expected "+eo(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function no(t,e,r){r=r||Qi(e),this.message=ro(t,e,r),to(this,no),this.__type=t,this.__value=e,this.__valueTypeName=r}function io(t,e,r,n,i){t?(i=i||Qi(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ro('property "'+eo(r)+o+eo(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',to(this,no),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}no.prototype=Object.create(Error.prototype),no.prototype.constructor=no,io.prototype=Object.create(Error.prototype),io.prototype.constructor=no;var oo={TfTypeError:no,TfPropertyTypeError:io,tfCustomError:function(t,e){return new no(t,{},e)},tfSubError:function(t,e,r){return t instanceof io?(e=e+"."+t.__property,t=new io(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof no&&(t=new io(t.__type,e,r,t.__value,t.__valueTypeName)),to(t),t},tfJSON:eo,getValueTypeName:Qi},so=Yi,uo=oo;function ao(t){return Buffer.isBuffer(t)}function ho(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function fo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw uo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var co=fo.bind(null,so.Array),lo=fo.bind(null,ao),po=fo.bind(null,ho),go=fo.bind(null,so.String);var yo=Math.pow(2,53)-1;var vo={ArrayN:co,Buffer:ao,BufferN:lo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:ho,HexN:po,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-yo&&t<=yo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=yo&&Math.floor(t)===t}};for(var mo in vo)vo[mo].toJSON=function(t){return t}.bind(null,mo);var wo=vo,bo=Yi,Eo=oo.tfJSON,_o=oo.TfTypeError,So=oo.TfPropertyTypeError,Io=oo.tfSubError,To=oo.getValueTypeName,Oo={arrayOf:function(t,e){function r(r,n){return!!bo.Array(r)&&(!bo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw Io(t,r)}}))))))}return t=Ao(t),e=e||{},r.toJSON=function(){var r="["+Eo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return bo.Nil(r)||e(r,n,t)}return e=Ao(e),r.toJSON=function(){return"?"+Eo(e)},r},map:function(t,e){function r(r,n){if(!bo.Object(r))return!1;if(bo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw Io(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw Io(t,i)}}return!0}return t=Ao(t),e&&(e=Ao(e)),r.toJSON=e?function(){return"{"+Eo(e)+": "+Eo(t)+"}"}:function(){return"{"+Eo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ao(t[r]);function n(t,r){if(!bo.Object(t))return!1;if(bo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw Io(t,n)}if(r)for(n in t)if(!e[n])throw new So(void 0,n);return!0}return n.toJSON=function(){return Eo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join(" & ")},e},quacksLike:function(t){function e(e){return t===To(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return!bo.Nil(e)&&(!bo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw Io(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Eo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ao(t){if(bo.String(t))return"?"===t[0]?Oo.maybe(t.slice(1)):bo[t]||Oo.quacksLike(t);if(t&&bo.Object(t)){if(bo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Oo.arrayOf(t[0])}return Oo.object(t)}return bo.Function(t)?t:Oo.value(t)}function ko(t,e,r,n){if(bo.Function(t)){if(t(e,r))return!0;throw new _o(n||t,e)}return ko(Ao(t),e,r)}for(var Po in Oo.oneOf=Oo.anyOf,bo)ko[Po]=bo[Po];for(Po in Oo)ko[Po]=Oo[Po];var Mo=wo;for(Po in Mo)ko[Po]=Mo[Po];ko.compile=Ao,ko.TfTypeError=_o,ko.TfPropertyTypeError=So;var xo=ko,Ro=vt;function No(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Bo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return No(Ro.decode(t),e)},decodeRaw:No,encode:function(t,e,r){return"number"==typeof t?Ro.encode(Bo(t,e,r)):Ro.encode(Bo(t.version,t.privateKey,t.compressed))},encodeRaw:Bo};Object.defineProperty(Ot,"__esModule",{value:!0});const Lo=At,Uo=vt,Do=xt.exports,Ho=xo,jo=Co,Fo=Ho.BufferN(32),qo=Ho.compile({wif:Ho.UInt8,bip32:{public:Ho.UInt32,private:Ho.UInt32}}),Go={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Ko=2147483648,Wo=Math.pow(2,31)-1;function Vo(t){return Ho.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function $o(t){return Ho.UInt32(t)&&t<=Wo}class zo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,Ho(qo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Do.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Lo.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Jo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Uo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return jo.encode(this.network.wif,this.privateKey,!0)}derive(t){Ho(Ho.UInt32,t);const e=t>=Ko,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Lo.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Do.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Do.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Jo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Do.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Yo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return Ho($o,t),this.derive(t+Ko)}derivePath(t){Ho(Vo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Do.sign(t,this.privateKey);{let e=Do.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Do.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Do.verify(t,this.publicKey,e)}}function Xo(t,e,r){return Yo(t,e,r)}function Yo(t,e,r,n,i,o){if(Ho({privateKey:Fo,chainCode:Fo},{privateKey:t,chainCode:e}),r=r||Go,!Do.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new zo(t,void 0,e,r,n,i,o)}function Jo(t,e,r,n,i,o){if(Ho({publicKey:Ho.BufferN(33),chainCode:Fo},{publicKey:t,chainCode:e}),r=r||Go,!Do.isPoint(t))throw new TypeError("Point is not on the curve");return new zo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Uo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Go;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Yo(r.slice(46,78),u,e,i,s,o)}else{a=Jo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Xo,Ot.fromPublicKey=function(t,e,r){return Jo(t,e,r)},Ot.fromSeed=function(t,e){if(Ho(Ho.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Go;const r=Lo.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Xo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var Zo=Ot;Tt.fromSeed=Zo.fromSeed,Tt.fromBase58=Zo.fromBase58,Tt.fromPublicKey=Zo.fromPublicKey,Tt.fromPrivateKey=Zo.fromPrivateKey;var Qo={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ts.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ts.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var es={},rs={},ns={},is={};Object.defineProperty(is,"__esModule",{value:!0}),is.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0});const us=xo,as=Math.pow(2,31)-1;function hs(t){return us.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ss.UInt31=function(t){return us.UInt32(t)&&t<=as},ss.BIP32Path=hs,hs.toJSON=()=>"BIP32 derivation path",ss.Signer=function(t){return(us.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ss.Satoshi=function(t){return us.UInt53(t)&&t<=21e14},ss.ECPoint=us.quacksLike("Point"),ss.Network=us.compile({messagePrefix:us.oneOf(us.Buffer,us.String),bip32:{public:us.UInt32,private:us.UInt32},pubKeyHash:us.UInt8,scriptHash:us.UInt8,wif:us.UInt8}),ss.Buffer256bit=us.BufferN(32),ss.Hash160bit=us.BufferN(20),ss.Hash256bit=us.BufferN(32),ss.Number=us.Number,ss.Array=us.Array,ss.Boolean=us.Boolean,ss.String=us.String,ss.Buffer=us.Buffer,ss.Hex=us.Hex,ss.maybe=us.maybe,ss.tuple=us.tuple,ss.UInt8=us.UInt8,ss.UInt32=us.UInt32,ss.Function=us.Function,ss.BufferN=us.BufferN,ss.Null=us.Null,ss.oneOf=us.oneOf;var fs=h.exports.Buffer;var cs={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=fs.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(os,"__esModule",{value:!0});const ls=ss,ps=cs,ds=xo,gs=Buffer.alloc(1,0);function ys(t){let e=0;for(;0===t[e];)++e;return e===t.length?gs:128&(t=t.slice(e))[0]?Buffer.concat([gs,t],1+t.length):t}function vs(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}os.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=ps.decode(t.slice(0,-1)),i=vs(n.r),o=vs(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},os.encode=function(t,e){ds({signature:ls.BufferN(64),hashType:ls.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=ys(t.slice(0,32)),o=ys(t.slice(32,64));return Buffer.concat([ps.encode(i,o),n])};var ms={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ws=ms;function bs(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ws.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ws.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},_s=ms,Ss={};for(var Is in _s){Ss[_s[Is]]=Is}var Ts=Ss;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=is,r=os,n=ss,i=cs,o=xt.exports,s=Es,u=xo;t.OPS=ms;const a=Ts,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(ns);var Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Os.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(rs,"__esModule",{value:!0});const As=ts,ks=ns,Ps=Os,Ms=xo,xs=ks.OPS;rs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ms({network:Ms.maybe(Ms.Object),output:Ms.maybe(Ms.Buffer),data:Ms.maybe(Ms.arrayOf(Ms.Buffer))},t);const r={name:"embed",network:t.network||As.bitcoin};if(Ps.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Ps.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ms.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});const Ns=ts,Bs=ns,Cs=Os,Ls=Bs.OPS,Us=xo,Ds=xt.exports,Hs=Ls.OP_RESERVED;function js(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Rs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Bs.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ls.OP_0)}e=Object.assign({validate:!0},e||{}),Us({network:Us.maybe(Us.Object),m:Us.maybe(Us.Number),n:Us.maybe(Us.Number),output:Us.maybe(Us.Buffer),pubkeys:Us.maybe(Us.arrayOf(Ds.isPoint)),signatures:Us.maybe(Us.arrayOf(r)),input:Us.maybe(Us.Buffer)},t);const n={network:t.network||Ns.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Bs.decompile(t),n.m=i[0]-Hs,n.n=i[i.length-2]-Hs,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Bs.compile([].concat(Hs+t.m,t.pubkeys,Hs+n.n,Ls.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Bs.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Bs.compile([Ls.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Us.Number(i[0]))throw new TypeError("Output is invalid");if(!Us.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ls.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ds.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!js(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ls.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!js(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Fs={};Object.defineProperty(Fs,"__esModule",{value:!0});const qs=ts,Gs=ns,Ks=Os,Ws=xo,Vs=Gs.OPS,$s=xt.exports;Fs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ws({network:Ws.maybe(Ws.Object),output:Ws.maybe(Ws.Buffer),pubkey:Ws.maybe($s.isPoint),signature:Ws.maybe(Gs.isCanonicalScriptSignature),input:Ws.maybe(Ws.Buffer)},t);const r=Ks.value((()=>Gs.decompile(t.input))),n={name:"p2pk",network:t.network||qs.bitcoin};if(Ks.prop(n,"output",(()=>{if(t.pubkey)return Gs.compile([t.pubkey,Vs.OP_CHECKSIG])})),Ks.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Ks.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Ks.prop(n,"input",(()=>{if(t.signature)return Gs.compile([t.signature])})),Ks.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==Vs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!$s.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Gs.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var zs={},Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=a;function Js(t){try{return Ys("rmd160").update(t).digest()}catch(e){return Ys("ripemd160").update(t).digest()}}function Zs(t){return Ys("sha256").update(t).digest()}Xs.ripemd160=Js,Xs.sha1=function(t){return Ys("sha1").update(t).digest()},Xs.sha256=Zs,Xs.hash160=function(t){return Js(Zs(t))},Xs.hash256=function(t){return Zs(Zs(t))},Object.defineProperty(zs,"__esModule",{value:!0});const Qs=Xs,tu=ts,eu=ns,ru=Os,nu=xo,iu=eu.OPS,ou=xt.exports,su=vt;zs.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),nu({network:nu.maybe(nu.Object),address:nu.maybe(nu.String),hash:nu.maybe(nu.BufferN(20)),output:nu.maybe(nu.BufferN(25)),pubkey:nu.maybe(ou.isPoint),signature:nu.maybe(eu.isCanonicalScriptSignature),input:nu.maybe(nu.Buffer)},t);const r=ru.value((()=>{const e=su.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=ru.value((()=>eu.decompile(t.input))),i=t.network||tu.bitcoin,o={name:"p2pkh",network:i};if(ru.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),su.encode(t)})),ru.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?Qs.hash160(t.pubkey||o.pubkey):void 0)),ru.prop(o,"output",(()=>{if(o.hash)return eu.compile([iu.OP_DUP,iu.OP_HASH160,o.hash,iu.OP_EQUALVERIFY,iu.OP_CHECKSIG])})),ru.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),ru.prop(o,"signature",(()=>{if(t.input)return n()[0]})),ru.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return eu.compile([t.signature,t.pubkey])})),ru.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==iu.OP_DUP||t.output[1]!==iu.OP_HASH160||20!==t.output[2]||t.output[23]!==iu.OP_EQUALVERIFY||t.output[24]!==iu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=Qs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!eu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ou.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=Qs.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var uu={};Object.defineProperty(uu,"__esModule",{value:!0});const au=Xs,hu=ts,fu=ns,cu=Os,lu=xo,pu=fu.OPS,du=vt;uu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),lu({network:lu.maybe(lu.Object),address:lu.maybe(lu.String),hash:lu.maybe(lu.BufferN(20)),output:lu.maybe(lu.BufferN(23)),redeem:lu.maybe({network:lu.maybe(lu.Object),output:lu.maybe(lu.Buffer),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))}),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||hu.bitcoin);const n={network:r},i=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=cu.value((()=>fu.decompile(t.input))),s=cu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:fu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(cu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),du.encode(t)})),cu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?au.hash160(n.redeem.output):void 0)),cu.prop(n,"output",(()=>{if(n.hash)return fu.compile([pu.OP_HASH160,n.hash,pu.OP_EQUAL])})),cu.prop(n,"redeem",(()=>{if(t.input)return s()})),cu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return fu.compile([].concat(fu.decompile(t.redeem.input),t.redeem.output))})),cu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),cu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==pu.OP_HASH160||20!==t.output[1]||t.output[22]!==pu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=fu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=au.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=fu.decompile(t.input);if(!fu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var gu={},yu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vu={},mu=0;mu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Eu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=bu(e)^n>>5}for(e=bu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Eu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Su(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Eu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=bu(n)^s,i+=yu.charAt(s)}for(o=0;o<6;++o)n=bu(n);for(n^=1,o=0;o<6;++o){i+=yu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(gu,"__esModule",{value:!0});const Tu=Xs,Ou=ts,Au=ns,ku=Os,Pu=xo,Mu=Au.OPS,xu=xt.exports,Ru=Iu,Nu=Buffer.alloc(0);gu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Pu({address:Pu.maybe(Pu.String),hash:Pu.maybe(Pu.BufferN(20)),input:Pu.maybe(Pu.BufferN(0)),network:Pu.maybe(Pu.Object),output:Pu.maybe(Pu.BufferN(22)),pubkey:Pu.maybe(xu.isPoint),signature:Pu.maybe(Au.isCanonicalScriptSignature),witness:Pu.maybe(Pu.arrayOf(Pu.Buffer))},t);const r=ku.value((()=>{const e=Ru.decode(t.address),r=e.words.shift(),n=Ru.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Ou.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Ru.toWords(i.hash);return t.unshift(0),Ru.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Tu.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Au.compile([Mu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Nu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Mu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Tu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Au.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Tu.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0});const Cu=Xs,Lu=ts,Uu=ns,Du=Os,Hu=xo,ju=Uu.OPS,Fu=xt.exports,qu=Iu,Gu=Buffer.alloc(0);function Ku(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Fu.isPoint(t))}Bu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Hu({network:Hu.maybe(Hu.Object),address:Hu.maybe(Hu.String),hash:Hu.maybe(Hu.BufferN(32)),output:Hu.maybe(Hu.BufferN(34)),redeem:Hu.maybe({input:Hu.maybe(Hu.Buffer),network:Hu.maybe(Hu.Object),output:Hu.maybe(Hu.Buffer),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))}),input:Hu.maybe(Hu.BufferN(0)),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))},t);const r=Du.value((()=>{const e=qu.decode(t.address),r=e.words.shift(),n=qu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Du.value((()=>Uu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Lu.bitcoin);const o={network:i};if(Du.prop(o,"address",(()=>{if(!o.hash)return;const t=qu.toWords(o.hash);return t.unshift(0),qu.encode(i.bech32,t)})),Du.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Du.prop(o,"output",(()=>{if(o.hash)return Uu.compile([ju.OP_0,o.hash])})),Du.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Gu,witness:t.witness.slice(0,-1)}})),Du.prop(o,"input",(()=>{if(o.witness)return Gu})),Du.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Uu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Gu,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Du.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==ju.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Uu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Uu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Ku)||t.redeem.output&&(Uu.decompile(t.redeem.output)||[]).some(Ku))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Ku)||(Uu.decompile(e)||[]).some(Ku))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(es,"__esModule",{value:!0});const Wu=rs;es.embed=Wu.p2data;const Vu=Rs;es.p2ms=Vu.p2ms;const $u=Fs;es.p2pk=$u.p2pk;const zu=zs;es.p2pkh=zu.p2pkh;const Xu=uu;es.p2sh=Xu.p2sh;const Yu=gu;es.p2wpkh=Yu.p2wpkh;const Ju=Bu;es.p2wsh=Ju.p2wsh,Object.defineProperty(Qo,"__esModule",{value:!0});const Zu=ts,Qu=es,ta=ns,ea=ss,ra=Iu,na=vt,ia=xo;function oa(t){const e=na.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function sa(t){const e=ra.decode(t),r=ra.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}Qo.fromBase58Check=oa,Qo.fromBech32=sa,Qo.toBase58Check=function(t,e){ia(ea.tuple(ea.Hash160bit,ea.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),na.encode(r)},Qo.toBech32=function(t,e,r){const n=ra.toWords(t);return n.unshift(e),ra.encode(r,n)},Qo.fromOutputScript=function(t,e){e=e||Zu.bitcoin;try{return Qu.p2pkh({output:t,network:e}).address}catch(t){}try{return Qu.p2sh({output:t,network:e}).address}catch(t){}try{return Qu.p2wpkh({output:t,network:e}).address}catch(t){}try{return Qu.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ta.toASM(t)+" has no matching Address")},Qo.toOutputScript=function(t,e){let r,n;e=e||Zu.bitcoin;try{r=oa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return Qu.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return Qu.p2sh({hash:r.hash}).output}else{try{n=sa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return Qu.p2wpkh({hash:n.data}).output;if(32===n.data.length)return Qu.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ua={},aa=u.randomBytes;Object.defineProperty(ua,"__esModule",{value:!0});const ha=ts,fa=ss,ca=xt.exports,la=aa,pa=xo,da=Co,ga=pa.maybe(pa.compile({compressed:fa.maybe(fa.Boolean),network:fa.maybe(fa.Network)}));class ya{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ha.bitcoin,void 0!==e&&(this.__Q=ca.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=ca.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return da.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return ca.sign(t,this.__D);{let e=ca.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=ca.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return ca.verify(t,this.publicKey,e)}}function va(t,e){if(pa(fa.Buffer256bit,t),!ca.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return pa(ga,e),new ya(t,void 0,e)}ua.fromPrivateKey=va,ua.fromPublicKey=function(t,e){return pa(ca.isPoint,t),pa(ga,e),new ya(void 0,t,e)},ua.fromWIF=function(t,e){const r=da.decode(t),n=r.version;if(fa.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ha.bitcoin,n!==e.wif)throw new Error("Invalid network version");return va(r.privateKey,{compressed:r.compressed,network:e})},ua.makeRandom=function(t){pa(ga,t),void 0===t&&(t={});const e=t.rng||la;let r;do{r=e(32),pa(fa.Buffer256bit,r)}while(!ca.isPrivate(r));return va(r,t)};var ma={},wa={},ba=h.exports.Buffer;function Ea(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function _a(t){return Ea(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Sa={encode:function t(e,r,n){if(Ea(e),r||(r=ba.allocUnsafe(_a(e))),!ba.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!ba.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ea(o),o},encodingLength:_a};Object.defineProperty(wa,"__esModule",{value:!0});const Ia=ss,Ta=xo,Oa=Sa;function Aa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Aa(n+r,9007199254740991),n+r}function Pa(t,e,r){return Aa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}wa.readUInt64LE=ka,wa.writeUInt64LE=Pa,wa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};wa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ta(Ia.tuple(Ia.Buffer,Ia.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Oa.decode(this.buffer,this.offset);return this.offset+=Oa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Ua.encodingLength(this.ins.length)+Ua.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Da(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Da(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Ua.encodingLength(e)+t.reduce(((t,e)=>t+Da(e)),0)}(e.witness)),0):0)}clone(){const t=new Wa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(La(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return qa;const n=Na.compile(Na.decompile(e).filter((t=>t!==Ba.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Wa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Wa.SIGHASH_SINGLE){if(t>=this.outs.length)return qa;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Wa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=Ha})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ra.hash256(o)}hashForWitnessV0(t,e,r,n){La(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=Fa,u=Fa,a=Fa;if(n&Wa.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ra.hash256(o)),n&Wa.SIGHASH_ANYONECANPAY||(31&n)===Wa.SIGHASH_SINGLE||(31&n)===Wa.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ra.hash256(o)),(31&n)!==Wa.SIGHASH_SINGLE&&(31&n)!==Wa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Da(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ra.hash256(o)}else if((31&n)===Wa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Wa.DEFAULT_SEQUENCE=4294967295,Wa.SIGHASH_ALL=1,Wa.SIGHASH_NONE=2,Wa.SIGHASH_SINGLE=3,Wa.SIGHASH_ANYONECANPAY=128,Wa.ADVANCED_TRANSACTION_MARKER=0,Wa.ADVANCED_TRANSACTION_FLAG=1,Ma.Transaction=Wa;Object.defineProperty(ma,"__esModule",{value:!0});const Va=wa,$a=Xs,za=Ma,Xa=ss,Ya=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=za.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Ja([{getHash:Xa.Function}],t),0===t.length)throw Qa;if(e&&!rh(t))throw th;const r=t.map((t=>t.getHash(e))),n=Ya(r,$a.hash256);return e?$a.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!rh(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+Za.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return $a.hash256(this.toBuffer(!0))}getId(){return Va.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new Va.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(Za.encode(this.transactions.length,e,r.offset),r.offset+=Za.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=Va.reverseBuffer(this.getHash()),e=eh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw Qa;const t=eh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw Qa;if(!this.hasWitnessCommit())throw th;const t=eh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function rh(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ma.Block=eh;var nh={},ih={},oh={},sh={},uh={},ah={},hh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(hh);var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const ch=hh;fh.decode=function(t){if(t.key[0]!==ch.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},fh.encode=function(t){const e=Buffer.from([ch.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},fh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",fh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},fh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=hh;lh.encode=function(t){return{key:Buffer.from([ph.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=hh;dh.decode=function(t){if(t.key[0]!==gh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},dh.encode=function(t){return{key:Buffer.from([gh.InputTypes.FINAL_SCRIPTSIG]),value:t}},dh.expected="Buffer",dh.check=function(t){return Buffer.isBuffer(t)},dh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var yh={};Object.defineProperty(yh,"__esModule",{value:!0});const vh=hh;yh.decode=function(t){if(t.key[0]!==vh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},yh.encode=function(t){return{key:Buffer.from([vh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},yh.expected="Buffer",yh.check=function(t){return Buffer.isBuffer(t)},yh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=hh;mh.decode=function(t){if(t.key[0]!==wh.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([wh.InputTypes.NON_WITNESS_UTXO]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=hh;bh.decode=function(t){if(t.key[0]!==Eh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},bh.encode=function(t){const e=Buffer.from([Eh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},bh.expected="{ pubkey: Buffer; signature: Buffer; }",bh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},bh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=hh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},_h.encode=function(t){return{key:Buffer.from([Sh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},_h.expected="string",_h.check=function(t){return"string"==typeof t},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=hh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ih.encode=function(t){const e=Buffer.from([Th.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ih.expected="number",Ih.check=function(t){return"number"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Oh={},Ah={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Ph(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Mh(t){return Ph(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Ph(e),r||(r=Buffer.allocUnsafe(Mh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Ph(i),i}},kh.encodingLength=Mh,Object.defineProperty(Ah,"__esModule",{value:!0});const xh=kh;function Rh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Nh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ah.range=t=>[...Array(t).keys()],Ah.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Dh={};Object.defineProperty(Dh,"__esModule",{value:!0}),Dh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var Hh={};Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(ah,"__esModule",{value:!0});const Fh=hh,qh=dh,Gh=yh,Kh=mh,Wh=bh,Vh=_h,$h=Ih,zh=Oh,Xh=Uh,Yh=Dh,Jh=Hh,Zh=jh,Qh={unsignedTx:lh,globalXpub:fh,checkPubkey:Yh.makeChecker([])};ah.globals=Qh;const tf={nonWitnessUtxo:Kh,partialSig:Wh,sighashType:$h,finalScriptSig:qh,finalScriptWitness:Gh,porCommitment:Vh,witnessUtxo:zh,bip32Derivation:Xh.makeConverter(Fh.InputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(Fh.InputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(Fh.InputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([Fh.InputTypes.PARTIAL_SIG,Fh.InputTypes.BIP32_DERIVATION])};ah.inputs=tf;const ef={bip32Derivation:Xh.makeConverter(Fh.OutputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(Fh.OutputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(Fh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([Fh.OutputTypes.BIP32_DERIVATION])};ah.outputs=ef,Object.defineProperty(uh,"__esModule",{value:!0});const rf=ah,nf=Ah,of=kh,sf=hh;function uf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function af(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case sf.GlobalTypes.UNSIGNED_TX:if(uf("global",t.key,sf.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case sf.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(rf.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of nf.range(s)){const e={};for(const n of r[t])switch(rf.inputs.checkPubkey(n),n.key[0]){case sf.InputTypes.NON_WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=rf.inputs.nonWitnessUtxo.decode(n);break;case sf.InputTypes.WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=rf.inputs.witnessUtxo.decode(n);break;case sf.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(rf.inputs.partialSig.decode(n));break;case sf.InputTypes.SIGHASH_TYPE:if(uf("input",n.key,sf.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=rf.inputs.sighashType.decode(n);break;case sf.InputTypes.REDEEM_SCRIPT:if(uf("input",n.key,sf.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=rf.inputs.redeemScript.decode(n);break;case sf.InputTypes.WITNESS_SCRIPT:if(uf("input",n.key,sf.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=rf.inputs.witnessScript.decode(n);break;case sf.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.inputs.bip32Derivation.decode(n));break;case sf.InputTypes.FINAL_SCRIPTSIG:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=rf.inputs.finalScriptSig.decode(n);break;case sf.InputTypes.FINAL_SCRIPTWITNESS:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=rf.inputs.finalScriptWitness.decode(n);break;case sf.InputTypes.POR_COMMITMENT:uf("input",n.key,sf.InputTypes.POR_COMMITMENT),e.porCommitment=rf.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of nf.range(u)){const e={};for(const r of n[t])switch(rf.outputs.checkPubkey(r),r.key[0]){case sf.OutputTypes.REDEEM_SCRIPT:if(uf("output",r.key,sf.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=rf.outputs.redeemScript.decode(r);break;case sf.OutputTypes.WITNESS_SCRIPT:if(uf("output",r.key,sf.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=rf.outputs.witnessScript.decode(r);break;case sf.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}uh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=of.decode(t,r);r+=of.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===sf.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of nf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of nf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return af(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},uh.checkKeyBuffer=uf,uh.psbtFromKeyVals=af;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});const ff=ah,cf=Ah;hf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=df({globalMap:t,inputs:e,outputs:r}),s=cf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(cf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const lf=(t,e)=>t.key.compare(e.key);function pf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(lf)}function df({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:pf(t,ff.globals),inputKeyVals:e.map((t=>pf(t,ff.inputs))),outputKeyVals:r.map((t=>pf(t,ff.outputs)))}}hf.psbtToKeyVals=df,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(uh),e(hf)}(sh),Object.defineProperty(oh,"__esModule",{value:!0});const gf=sh;function yf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function vf(t){return t.globalMap.unsignedTx}function mf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}oh.combine=function(t){const e=t[0],r=gf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=vf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=mf(r.globalKeyVals),s=r.inputKeyVals.map(mf),u=r.outputKeyVals.map(mf);for(const t of n){const e=vf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=gf.psbtToKeyVals(t);mf(n.globalKeyVals).forEach(yf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return gf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var wf={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ah;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(wf),Object.defineProperty(ih,"__esModule",{value:!0});const bf=oh,Ef=sh,_f=hh,Sf=wf;ih.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ef.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ef.psbtToBuffer(this)}updateGlobal(t){return Sf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.updateInput(e,r),this}updateOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Sf.checkHasKey(t,this.globalMap.unknownKeyVals,Sf.getEnumLength(_f.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Sf.checkForInput(this.inputs,t);Sf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=bf.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(nh,"__esModule",{value:!0});const If=ih,Tf=kh,Of=wf,Af=Qo,kf=wa,Pf=Xs,Mf=ua,xf=es,Rf=ns,Nf=Ma,Bf={network:ts.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new If.Psbt(new Uf)){this.data=e,this.opts=Object.assign({},Bf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=If.Psbt.fromBuffer(t,Lf),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{Zf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Af.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Xf(t),this.opts.maximumFeeRate=t}setVersion(t){Xf(t),Yf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Xf(t),Yf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Xf(e),Yf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Yf(this.data.inputs,"addInput"),t.witnessScript&&gc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);Zf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&hc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Yf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Af.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(jf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return fc(this.data.inputs,r,e,!0),r}getFeeRate(){return rc("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return rc("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Of.checkForInput(this.data.inputs,0),mc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=nc){const r=Of.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=cc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Wf(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Rf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Of.checkForInput(this.data.inputs,t),r=dc(lc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Rf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||pc(r)||(n=r,Rf.isCanonicalScriptSignature(n)))return;var n;if(!Rf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=uc(t),r=e[e.length-1];if(pc(r))return;if(!Rf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+vc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=lc(r,e,n),{meaningfulScript:o}=dc(i,r,"input",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Of.checkForInput(this.data.inputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=dc(i,r,"output",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Of.checkForOutput(this.data.outputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Of.checkForInput(this.data.inputs,0);return mc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Rf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?oc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Jf(e.pubkey,h,"verify");const f=Mf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of mc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return sc(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=sc(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Rf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Rf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Df(this.__CACHE),this.data.toBuffer()}toHex(){return Df(this.__CACHE),this.data.toHex()}toBase64(){return Df(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&gc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&hc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}nh.Psbt=Cf;const Lf=t=>new Uf(t);class Uf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Nf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Df(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Hf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Mf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function jf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Ff(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const qf=Ff(xf.p2ms),Gf=Ff(xf.p2pk),Kf=Ff(xf.p2pkh),Wf=Ff(xf.p2wpkh),Vf=Ff(xf.p2wsh),$f=Ff(xf.p2sh);function zf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Xf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Yf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Rf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Rf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Rf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Rf.signature.decode(t.signature),i=[];n&Nf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Nf.Transaction.SIGHASH_ALL:break;case Nf.Transaction.SIGHASH_SINGLE:case Nf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Jf(t,e,r){if(!yc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function Zf(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function Qf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const tc=Qf(xf.p2sh,"Redeem script"),ec=Qf(xf.p2wsh,"Witness script");function rc(t,e,r,n){if(!r.every(jf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),fc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function nc(t,e,r,n,i,o){const s=vc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Hf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return Hf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=ac(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function ic(t,e,r,n,i){const o=Of.checkForInput(t,e),{hash:s,sighashType:u,script:a}=oc(e,o,n,!1,i);return Jf(r,a,"sign"),{hash:s,sighashType:u}}function oc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Nf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Nf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Nf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Nf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Nf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=cc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=dc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Wf(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function sc(t,e,r){const n=Of.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function uc(t){let e=0;function r(){const r=Tf.decode(t,e);return e+=Tf.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=uc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=cc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function cc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||hc(t,e,r),n[r]}function lc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return cc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function pc(t){return 33===t.length&&Rf.isCanonicalPubKey(t)}function dc(t,e,r,n,i){const o=$f(t),s=o&&n&&Vf(n),u=Vf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,tc(e,t,n,r),ec(e,n,i,r),gc(a)):u?(a=i,ec(e,t,i,r),gc(a)):o?(a=n,tc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function gc(t){if(Wf(t)||$f(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function yc(t,e){const r=Pf.hash160(t),n=Rf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function vc(t){return Wf(t)?"witnesspubkeyhash":Kf(t)?"pubkeyhash":qf(t)?"multisig":Gf(t)?"pubkey":"nonstandard"}function mc(t){return[...Array(t).keys()]}var wc={},bc={},Ec={},_c={};Object.defineProperty(_c,"__esModule",{value:!0});const Sc=ns,Ic=ns;function Tc(t){return t===Ic.OPS.OP_0||Sc.isCanonicalScriptSignature(t)}function Oc(t,e){const r=Sc.decompile(t);return!(r.length<2)&&(r[0]===Ic.OPS.OP_0&&(e?r.slice(1).every(Tc):r.slice(1).every(Sc.isCanonicalScriptSignature)))}_c.check=Oc,Oc.toJSON=()=>"multisig input";var Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const kc=ns,Pc=ns,Mc=ss,xc=Pc.OPS.OP_RESERVED;function Rc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Pc.OPS.OP_CHECKMULTISIG)return!1;if(!Mc.Number(r[0]))return!1;if(!Mc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Ac.check=Rc,Rc.toJSON=()=>"multi-sig output",Object.defineProperty(Ec,"__esModule",{value:!0});const Nc=_c;Ec.input=Nc;const Bc=Ac;Ec.output=Bc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Lc=ns,Uc=Lc.OPS;function Dc(t){const e=Lc.compile(t);return e.length>1&&e[0]===Uc.OP_RETURN}Cc.check=Dc,Dc.toJSON=()=>"null data output";const Hc={check:Dc};Cc.output=Hc;var jc={},Fc={};Object.defineProperty(Fc,"__esModule",{value:!0});const qc=ns;function Gc(t){const e=qc.decompile(t);return 1===e.length&&qc.isCanonicalScriptSignature(e[0])}Fc.check=Gc,Gc.toJSON=()=>"pubKey input";var Kc={};Object.defineProperty(Kc,"__esModule",{value:!0});const Wc=ns,Vc=ns;function $c(t){const e=Wc.decompile(t);return 2===e.length&&Wc.isCanonicalPubKey(e[0])&&e[1]===Vc.OPS.OP_CHECKSIG}Kc.check=$c,$c.toJSON=()=>"pubKey output",Object.defineProperty(jc,"__esModule",{value:!0});const zc=Fc;jc.input=zc;const Xc=Kc;jc.output=Xc;var Yc={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});const Zc=ns;function Qc(t){const e=Zc.decompile(t);return 2===e.length&&Zc.isCanonicalScriptSignature(e[0])&&Zc.isCanonicalPubKey(e[1])}Jc.check=Qc,Qc.toJSON=()=>"pubKeyHash input";var tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=ns,rl=ns;function nl(t){const e=el.compile(t);return 25===e.length&&e[0]===rl.OPS.OP_DUP&&e[1]===rl.OPS.OP_HASH160&&20===e[2]&&e[23]===rl.OPS.OP_EQUALVERIFY&&e[24]===rl.OPS.OP_CHECKSIG}tl.check=nl,nl.toJSON=()=>"pubKeyHash output",Object.defineProperty(Yc,"__esModule",{value:!0});const il=Jc;Yc.input=il;const ol=tl;Yc.output=ol;var sl={},ul={},al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=ns,fl=ns;function cl(t){const e=hl.compile(t);return 22===e.length&&e[0]===fl.OPS.OP_0&&20===e[1]}al.check=cl,cl.toJSON=()=>"Witness pubKeyHash output";var ll={};Object.defineProperty(ll,"__esModule",{value:!0});const pl=ns,dl=ns;function gl(t){const e=pl.compile(t);return 34===e.length&&e[0]===dl.OPS.OP_0&&32===e[1]}ll.check=gl,gl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(ul,"__esModule",{value:!0});const yl=ns,vl=Ec,ml=jc,wl=Yc,bl=al,El=ll;function _l(t,e){const r=yl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=yl.decompile(yl.compile(r.slice(0,-1))),o=yl.decompile(n);return!!o&&(!!yl.isPushOnly(i)&&(1===r.length?El.check(o)||bl.check(o):!(!wl.input.check(i)||!wl.output.check(o))||(!(!vl.input.check(i,e)||!vl.output.check(o))||!(!ml.input.check(i)||!ml.output.check(o)))))}ul.check=_l,_l.toJSON=()=>"scriptHash input";var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Il=ns,Tl=ns;function Ol(t){const e=Il.compile(t);return 23===e.length&&e[0]===Tl.OPS.OP_HASH160&&20===e[1]&&e[22]===Tl.OPS.OP_EQUAL}Sl.check=Ol,Ol.toJSON=()=>"scriptHash output",Object.defineProperty(sl,"__esModule",{value:!0});const Al=ul;sl.input=Al;const kl=Sl;sl.output=kl;var Pl={},Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const xl=ns,Rl=ns,Nl=ss,Bl=xo,Cl=Buffer.from("aa21a9ed","hex");function Ll(t){const e=xl.compile(t);return e.length>37&&e[0]===Rl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Ml.check=Ll,Ll.toJSON=()=>"Witness commitment output",Ml.encode=function(t){Bl(Nl.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Rl.OPS.OP_RETURN,e])},Ml.decode=function(t){return Bl(Ll,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Pl,"__esModule",{value:!0});const Ul=Ml;Pl.output=Ul;var Dl={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const jl=ns;function Fl(t){const e=jl.decompile(t);return 2===e.length&&jl.isCanonicalScriptSignature(e[0])&&function(t){return jl.isCanonicalPubKey(t)&&33===t.length}(e[1])}Hl.check=Fl,Fl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Dl,"__esModule",{value:!0});const ql=Hl;Dl.input=ql;const Gl=al;Dl.output=Gl;var Kl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Vl=ns,$l=xo,zl=Ec,Xl=jc,Yl=Yc;function Jl(t,e){if($l($l.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=Vl.decompile(r);if(!n||0===n.length)return!1;const i=Vl.compile(t.slice(0,-1));return!(!Yl.input.check(i)||!Yl.output.check(n))||(!(!zl.input.check(i,e)||!zl.output.check(n))||!(!Xl.input.check(i)||!Xl.output.check(n)))}Wl.check=Jl,Jl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Kl,"__esModule",{value:!0});const Zl=Wl;Kl.input=Zl;const Ql=ll;Kl.output=Ql,Object.defineProperty(bc,"__esModule",{value:!0});const tp=ns,ep=Ec,rp=Cc,np=jc,ip=Yc,op=sl,sp=Pl,up=Dl,ap=Kl,hp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};bc.types=hp,bc.output=function(t){if(up.output.check(t))return hp.P2WPKH;if(ap.output.check(t))return hp.P2WSH;if(ip.output.check(t))return hp.P2PKH;if(op.output.check(t))return hp.P2SH;const e=tp.decompile(t);if(!e)throw new TypeError("Invalid script");return ep.output.check(e)?hp.P2MS:np.output.check(e)?hp.P2PK:sp.output.check(e)?hp.WITNESS_COMMITMENT:rp.output.check(e)?hp.NULLDATA:hp.NONSTANDARD},bc.input=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return ip.input.check(r)?hp.P2PKH:op.input.check(r,e)?hp.P2SH:ep.input.check(r,e)?hp.P2MS:np.input.check(r)?hp.P2PK:hp.NONSTANDARD},bc.witness=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return up.input.check(r)?hp.P2WPKH:ap.input.check(r,e)?hp.P2WSH:hp.NONSTANDARD},Object.defineProperty(wc,"__esModule",{value:!0});const fp=Qo,cp=wa,lp=bc,pp=Xs,dp=ua,gp=ts,yp=es,vp=ns,mp=ns,wp=Ma,bp=ss,Ep=xo,_p=lp.types,Sp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Ip(t,e,r){try{Ep(t,e)}catch(t){throw new Error(r)}}class Tp{constructor(t=gp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new wp.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Tp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==_p.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=dp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=vp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ep(Ep.maybe(Ep.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ep(bp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ep(bp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=cp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof wp.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=fp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=vp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Sp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Ip(Ep.Number,e.vin,"sign must include vin parameter as Number (input index)"),Ip(bp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Ip(Ep.maybe(Ep.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires witnessScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||wp.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Pp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ep(bp.Satoshi,a),l.value=a}if(!Pp(l)){const t=function(t,e,r,n){if(r&&n){const i=yp.p2wsh({redeem:{output:n}}),o=yp.p2wsh({output:r}),s=yp.p2sh({redeem:{output:r}}),u=yp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ap(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===_p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:_p.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:_p.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=yp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=yp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ap(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+vp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===_p.P2WPKH&&(o=yp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:_p.P2SH,prevOutScript:n.output,hasWitness:i.type===_p.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=yp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=yp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ap(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===_p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:_p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===_p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===_p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ap(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+vp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===_p.P2WPKH&&(n=yp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===_p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=yp.p2pkh({pubkey:e}).output;return{prevOutType:_p.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:_p.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Pp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(wp.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Op(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ap(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||lp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===_p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Mp(t)&wp.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===wp.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Mp(t)&wp.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Mp(r);return n===wp.Transaction.SIGHASH_NONE||n===wp.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Op(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=lp.input(t,!0),i=lp.witness(e,!0);n===_p.NONSTANDARD&&(n=void 0),i===_p.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case _p.P2WPKH:{const{output:t,pubkey:r,signature:n}=yp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:_p.P2WPKH,pubkeys:[r],signatures:[n]}}case _p.P2PKH:{const{output:e,pubkey:r,signature:n}=yp.p2pkh({input:t});return{prevOutScript:e,prevOutType:_p.P2PKH,pubkeys:[r],signatures:[n]}}case _p.P2PK:{const{signature:e}=yp.p2pk({input:t});return{prevOutType:_p.P2PK,pubkeys:[void 0],signatures:[e]}}case _p.P2MS:{const{m:e,pubkeys:r,signatures:i}=yp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:_p.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===_p.P2SH){const{output:r,redeem:n}=yp.p2sh({input:t,witness:e}),i=lp.output(n.output),o=Op(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:_p.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===_p.P2WSH){const{output:r,redeem:n}=yp.p2wsh({input:t,witness:e}),i=lp.output(n.output);let o;return o=i===_p.P2WPKH?Op(n.input,n.witness,i):Op(vp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:_p.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:_p.NONSTANDARD,prevOutScript:t}}function Ap(t,e){Ep(bp.Buffer,t);const r=lp.output(t);switch(r){case _p.P2PKH:{if(!e)return{type:r};const n=yp.p2pkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2WPKH:{if(!e)return{type:r};const n=yp.p2wpkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2PK:return{type:r,pubkeys:[yp.p2pk({output:t}).pubkey],signatures:[void 0]};case _p.P2MS:{const e=yp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case _p.P2PKH:if(0===n.length)break;if(0===i.length)break;return yp.p2pkh({pubkey:n[0],signature:i[0]});case _p.P2WPKH:if(0===n.length)break;if(0===i.length)break;return yp.p2wpkh({pubkey:n[0],signature:i[0]});case _p.P2PK:if(0===n.length)break;if(0===i.length)break;return yp.p2pk({signature:i[0]});case _p.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||mp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return yp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case _p.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return yp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case _p.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return yp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Pp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Mp(t){return t.readUInt8(t.length-1)}wc.TransactionBuilder=Tp,Object.defineProperty(It,"__esModule",{value:!0});const xp=Tt;It.bip32=xp;const Rp=Qo;It.address=Rp;const Np=Xs;var Bp=It.crypto=Np;const Cp=ua;It.ECPair=Cp;const Lp=ts;It.networks=Lp;const Up=es;It.payments=Up;const Dp=ns;It.script=Dp;var Hp=ma;It.Block=Hp.Block;var jp=nh;It.Psbt=jp.Psbt;var Fp=ns;It.opcodes=Fp.OPS;var qp=Ma;It.Transaction=qp.Transaction;var Gp=wc;It.TransactionBuilder=Gp.TransactionBuilder;var Kp={exports:{}};var Wp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var Vp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Wp,n=Vp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Kp,Kp.exports);const $p=["includePrerelease","loose","rtl"];var zp=t=>t?"object"!=typeof t?{loose:!0}:$p.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Xp=/^[0-9]+$/,Yp=(t,e)=>{const r=Xp.test(t),n=Xp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tYp(e,t)};const Zp=Vp,{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:td}=Wp,{re:ed,t:rd}=Kp.exports,nd=zp,{compareIdentifiers:id}=Jp;class od{constructor(t,e){if(e=nd(e),t instanceof od){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);Zp("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?ed[rd.LOOSE]:ed[rd.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>td||this.major<0)throw new TypeError("Invalid major version");if(this.minor>td||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>td||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var sd=od;const{MAX_LENGTH:ud}=Wp,{re:ad,t:hd}=Kp.exports,fd=sd,cd=zp;var ld=(t,e)=>{if(e=cd(e),t instanceof fd)return t;if("string"!=typeof t)return null;if(t.length>ud)return null;if(!(e.loose?ad[hd.LOOSE]:ad[hd.FULL]).test(t))return null;try{return new fd(t,e)}catch(t){return null}};const pd=ld;var dd=(t,e)=>{const r=pd(t,e);return r?r.version:null};const gd=ld;var yd=(t,e)=>{const r=gd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const vd=sd;var md=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new vd(t,r).inc(e,n).version}catch(t){return null}};const wd=sd;var bd=(t,e,r)=>new wd(t,r).compare(new wd(e,r));const Ed=bd;var _d=(t,e,r)=>0===Ed(t,e,r);const Sd=ld,Id=_d;var Td=(t,e)=>{if(Id(t,e))return null;{const r=Sd(t),n=Sd(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Od=sd;var Ad=(t,e)=>new Od(t,e).major;const kd=sd;var Pd=(t,e)=>new kd(t,e).minor;const Md=sd;var xd=(t,e)=>new Md(t,e).patch;const Rd=ld;var Nd=(t,e)=>{const r=Rd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Bd=bd;var Cd=(t,e,r)=>Bd(e,t,r);const Ld=bd;var Ud=(t,e)=>Ld(t,e,!0);const Dd=sd;var Hd=(t,e,r)=>{const n=new Dd(t,r),i=new Dd(e,r);return n.compare(i)||n.compareBuild(i)};const jd=Hd;var Fd=(t,e)=>t.sort(((t,r)=>jd(t,r,e)));const qd=Hd;var Gd=(t,e)=>t.sort(((t,r)=>qd(r,t,e)));const Kd=bd;var Wd=(t,e,r)=>Kd(t,e,r)>0;const Vd=bd;var $d=(t,e,r)=>Vd(t,e,r)<0;const zd=bd;var Xd=(t,e,r)=>0!==zd(t,e,r);const Yd=bd;var Jd=(t,e,r)=>Yd(t,e,r)>=0;const Zd=bd;var Qd=(t,e,r)=>Zd(t,e,r)<=0;const tg=_d,eg=Xd,rg=Wd,ng=Jd,ig=$d,og=Qd;var sg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return tg(t,r,n);case"!=":return eg(t,r,n);case">":return rg(t,r,n);case">=":return ng(t,r,n);case"<":return ig(t,r,n);case"<=":return og(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const ug=sd,ag=ld,{re:hg,t:fg}=Kp.exports;var cg=(t,e)=>{if(t instanceof ug)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=hg[fg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),hg[fg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;hg[fg.COERCERTL].lastIndex=-1}else r=t.match(hg[fg.COERCE]);return null===r?null:ag(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},lg=pg;function pg(t){var e=this;if(e instanceof pg||(e=new pg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},pg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},pg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},pg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},pg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new pg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},pg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Mg=(t,e,r)=>{const n=t[Ag].get(e);if(n){const e=n.value;if(xg(t,e)){if(Ng(t,n),!t[_g])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Og].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Sg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Sg]&&r>t[Sg]},Rg=t=>{if(t[bg]>t[wg])for(let e=t[Og].tail;t[bg]>t[wg]&&null!==e;){const r=e.prev;Ng(t,e),e=r}},Ng=(t,e)=>{if(e){const r=e.value;t[Ig]&&t[Ig](r.key,r.value),t[bg]-=r.length,t[Ag].delete(r.key),t[Og].removeNode(e)}};class Bg{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Ng(t,r),t[_g]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Lg=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[wg]=t.max||1/0;const e=t.length||Pg;if(this[Eg]="function"!=typeof e?Pg:e,this[_g]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Sg]=t.maxAge||0,this[Ig]=t.dispose,this[Tg]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[wg]=t||1/0,Rg(this)}get max(){return this[wg]}set allowStale(t){this[_g]=!!t}get allowStale(){return this[_g]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Sg]=t,Rg(this)}get maxAge(){return this[Sg]}set lengthCalculator(t){"function"!=typeof t&&(t=Pg),t!==this[Eg]&&(this[Eg]=t,this[bg]=0,this[Og].forEach((t=>{t.length=this[Eg](t.value,t.key),this[bg]+=t.length}))),Rg(this)}get lengthCalculator(){return this[Eg]}get length(){return this[bg]}get itemCount(){return this[Og].length}rforEach(t,e){e=e||this;for(let r=this[Og].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Og].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Og].toArray().map((t=>t.key))}values(){return this[Og].toArray().map((t=>t.value))}reset(){this[Ig]&&this[Og]&&this[Og].length&&this[Og].forEach((t=>this[Ig](t.key,t.value))),this[Ag]=new Map,this[Og]=new mg,this[bg]=0}dump(){return this[Og].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Og]}set(t,e,r){if((r=r||this[Sg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Eg](e,t);if(this[Ag].has(t)){if(i>this[wg])return Ng(this,this[Ag].get(t)),!1;const o=this[Ag].get(t).value;return this[Ig]&&(this[Tg]||this[Ig](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[bg]+=i-o.length,o.length=i,this.get(t),Rg(this),!0}const o=new Bg(t,e,i,n,r);return o.length>this[wg]?(this[Ig]&&this[Ig](t,e),!1):(this[bg]+=o.length,this[Og].unshift(o),this[Ag].set(t,this[Og].head),Rg(this),!0)}has(t){if(!this[Ag].has(t))return!1;const e=this[Ag].get(t).value;return!xg(this,e)}get(t){return Mg(this,t,!0)}peek(t){return Mg(this,t,!1)}pop(){const t=this[Og].tail;return t?(Ng(this,t),t.value):null}del(t){Ng(this,this[Ag].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ag].forEach(((t,e)=>Mg(this,e,!1)))}};class Ug{constructor(t,e){if(e=jg(e),t instanceof Ug)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Ug(t.raw,e);if(t instanceof Fg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Xg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Yg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=Hg.get(e);if(r)return r;const n=this.options.loose,i=n?Kg[Wg.HYPHENRANGELOOSE]:Kg[Wg.HYPHENRANGE];t=t.replace(i,ay(this.options.includePrerelease)),qg("hyphen replace",t),t=t.replace(Kg[Wg.COMPARATORTRIM],Vg),qg("comparator trim",t,Kg[Wg.COMPARATORTRIM]),t=(t=(t=t.replace(Kg[Wg.TILDETRIM],$g)).replace(Kg[Wg.CARETTRIM],zg)).split(/\s+/).join(" ");const o=n?Kg[Wg.COMPARATORLOOSE]:Kg[Wg.COMPARATOR],s=t.split(" ").map((t=>Zg(t,this.options))).join(" ").split(/\s+/).map((t=>uy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Fg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Xg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return Hg.set(e,a),a}intersects(t,e){if(!(t instanceof Ug))throw new TypeError("a Range is required");return this.set.some((r=>Jg(r,e)&&t.set.some((t=>Jg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Gg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Yg=t=>""===t.value,Jg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},Zg=(t,e)=>(qg("comp",t,e),t=ry(t,e),qg("caret",t),t=ty(t,e),qg("tildes",t),t=iy(t,e),qg("xrange",t),t=sy(t,e),qg("stars",t),t),Qg=t=>!t||"x"===t.toLowerCase()||"*"===t,ty=(t,e)=>t.trim().split(/\s+/).map((t=>ey(t,e))).join(" "),ey=(t,e)=>{const r=e.loose?Kg[Wg.TILDELOOSE]:Kg[Wg.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return qg("tilde",t,e,r,n,i,o),Qg(r)?s="":Qg(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Qg(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(qg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,qg("tilde return",s),s}))},ry=(t,e)=>t.trim().split(/\s+/).map((t=>ny(t,e))).join(" "),ny=(t,e)=>{qg("caret",t,e);const r=e.loose?Kg[Wg.CARETLOOSE]:Kg[Wg.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return qg("caret",t,e,r,i,o,s),Qg(r)?u="":Qg(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Qg(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(qg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(qg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),qg("caret return",u),u}))},iy=(t,e)=>(qg("replaceXRanges",t,e),t.split(/\s+/).map((t=>oy(t,e))).join(" ")),oy=(t,e)=>{t=t.trim();const r=e.loose?Kg[Wg.XRANGELOOSE]:Kg[Wg.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{qg("xRange",t,r,n,i,o,s,u);const a=Qg(i),h=a||Qg(o),f=h||Qg(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),qg("xRange return",r),r}))},sy=(t,e)=>(qg("replaceStars",t,e),t.trim().replace(Kg[Wg.STAR],"")),uy=(t,e)=>(qg("replaceGTE0",t,e),t.trim().replace(Kg[e.includePrerelease?Wg.GTE0PRE:Wg.GTE0],"")),ay=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=Qg(n)?"":Qg(i)?`>=${n}.0.0${t?"-0":""}`:Qg(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Qg(h)?"":Qg(f)?`<${+h+1}.0.0-0`:Qg(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),hy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},fy=Symbol("SemVer ANY");class cy{static get ANY(){return fy}constructor(t,e){if(e=py(e),t instanceof cy){if(t.loose===!!e.loose)return t;t=t.value}vy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===fy?this.value="":this.value=this.operator+this.semver.version,vy("comp",this)}parse(t){const e=this.options.loose?dy[gy.COMPARATORLOOSE]:dy[gy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new my(r[2],this.options.loose):this.semver=fy}toString(){return this.value}test(t){if(vy("Comparator.test",t,this.options.loose),this.semver===fy||t===fy)return!0;if("string"==typeof t)try{t=new my(t,this.options)}catch(t){return!1}return yy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof cy))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new wy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new wy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=yy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=yy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var ly=cy;const py=zp,{re:dy,t:gy}=Kp.exports,yy=sg,vy=Vp,my=sd,wy=Dg,by=Dg;var Ey=(t,e,r)=>{try{e=new by(e,r)}catch(t){return!1}return e.test(t)};const _y=Dg;var Sy=(t,e)=>new _y(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Iy=sd,Ty=Dg;var Oy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ty(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Iy(n,r)))})),n};const Ay=sd,ky=Dg;var Py=(t,e,r)=>{let n=null,i=null,o=null;try{o=new ky(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Ay(n,r)))})),n};const My=sd,xy=Dg,Ry=Wd;var Ny=(t,e)=>{t=new xy(t,e);let r=new My("0.0.0");if(t.test(r))return r;if(r=new My("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new My(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Ry(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Ry(r,i)||(r=i)}return r&&t.test(r)?r:null};const By=Dg;var Cy=(t,e)=>{try{return new By(t,e).range||"*"}catch(t){return null}};const Ly=sd,Uy=ly,{ANY:Dy}=Uy,Hy=Dg,jy=Ey,Fy=Wd,qy=$d,Gy=Qd,Ky=Jd;var Wy=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Ly(t,n),e=new Hy(e,n),r){case">":i=Fy,o=Gy,s=qy,u=">",a=">=";break;case"<":i=qy,o=Ky,s=Fy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jy(t,e,n))return!1;for(let r=0;r{t.semver===Dy&&(t=new Uy(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const Vy=Wy;var $y=(t,e,r)=>Vy(t,e,">",r);const zy=Wy;var Xy=(t,e,r)=>zy(t,e,"<",r);const Yy=Dg;var Jy=(t,e,r)=>(t=new Yy(t,r),e=new Yy(e,r),t.intersects(e));const Zy=Ey,Qy=bd;const tv=Dg,ev=ly,{ANY:rv}=ev,nv=Ey,iv=bd,ov=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===rv){if(1===e.length&&e[0].semver===rv)return!0;t=r.includePrerelease?[new ev(">=0.0.0-0")]:[new ev(">=0.0.0")]}if(1===e.length&&e[0].semver===rv){if(r.includePrerelease)return!0;e=[new ev(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=sv(i,e,r):"<"===e.operator||"<="===e.operator?o=uv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=iv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!nv(t,String(i),r))return null;if(o&&!nv(t,String(o),r))return null;for(const n of e)if(!nv(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=sv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!nv(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=uv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!nv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},sv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},uv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var av=(t,e,r={})=>{if(t===e)return!0;t=new tv(t,r),e=new tv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=ov(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const hv=Kp.exports;var fv={re:hv.re,src:hv.src,tokens:hv.t,SEMVER_SPEC_VERSION:Wp.SEMVER_SPEC_VERSION,SemVer:sd,compareIdentifiers:Jp.compareIdentifiers,rcompareIdentifiers:Jp.rcompareIdentifiers,parse:ld,valid:dd,clean:yd,inc:md,diff:Td,major:Ad,minor:Pd,patch:xd,prerelease:Nd,compare:bd,rcompare:Cd,compareLoose:Ud,compareBuild:Hd,sort:Fd,rsort:Gd,gt:Wd,lt:$d,eq:_d,neq:Xd,gte:Jd,lte:Qd,cmp:sg,coerce:cg,Comparator:ly,Range:Dg,satisfies:Ey,toComparators:Sy,maxSatisfying:Oy,minSatisfying:Py,minVersion:Ny,validRange:Cy,outside:Wy,gtr:$y,ltr:Xy,intersects:Jy,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Qy(t,e,r)));for(const t of s){Zy(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Tv(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ov(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Av(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}yv.prototype=Object.create(null),vv.EventEmitter=vv,vv.usingDomains=!1,vv.prototype.domain=void 0,vv.prototype._events=void 0,vv.prototype._maxListeners=void 0,vv.defaultMaxListeners=10,vv.init=function(){this.domain=null,vv.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new yv,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},vv.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},vv.prototype.getMaxListeners=function(){return mv(this)},vv.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:wv(r,f,this);break;case 2:bv(r,f,this,arguments[1]);break;case 3:Ev(r,f,this,arguments[1],arguments[2]);break;case 4:_v(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new yv,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var kv=Object.freeze({__proto__:null,default:vv,EventEmitter:vv});function Pv(){throw new Error("setTimeout has not been defined")}function Mv(){throw new Error("clearTimeout has not been defined")}var xv=Pv,Rv=Mv;function Nv(t){if(xv===setTimeout)return setTimeout(t,0);if((xv===Pv||!xv)&&setTimeout)return xv=setTimeout,setTimeout(t,0);try{return xv(t,0)}catch(e){try{return xv.call(null,t,0)}catch(e){return xv.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xv=setTimeout),"function"==typeof global.clearTimeout&&(Rv=clearTimeout);var Bv,Cv=[],Lv=!1,Uv=-1;function Dv(){Lv&&Bv&&(Lv=!1,Bv.length?Cv=Bv.concat(Cv):Uv=-1,Cv.length&&Hv())}function Hv(){if(!Lv){var t=Nv(Dv);Lv=!0;for(var e=Cv.length;e;){for(Bv=Cv,Cv=[];++Uv1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),nm(e)?r.showHidden=e:e&&_m(r,e),hm(r.showHidden)&&(r.showHidden=!1),hm(r.depth)&&(r.depth=2),hm(r.colors)&&(r.colors=!1),hm(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Jv),Qv(r,t,r.depth)}function Jv(t,e){var r=Yv.styles[e];return r?"["+Yv.colors[r][0]+"m"+t+"["+Yv.colors[r][1]+"m":t}function Zv(t,e){return t}function Qv(t,e,r){if(t.customInspect&&e&&dm(e.inspect)&&e.inspect!==Yv&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return um(n)||(n=Qv(t,n,r)),n}var i=function(t,e){if(hm(e))return t.stylize("undefined","undefined");if(um(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(sm(e))return t.stylize(""+e,"number");if(nm(e))return t.stylize(""+e,"boolean");if(im(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),pm(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tm(e);if(0===o.length){if(dm(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(fm(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(lm(e))return t.stylize(Date.prototype.toString.call(e),"date");if(pm(e))return tm(e)}var a,h="",f=!1,c=["{","}"];(rm(e)&&(f=!0,c=["[","]"]),dm(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return fm(e)&&(h=" "+RegExp.prototype.toString.call(e)),lm(e)&&(h=" "+Date.prototype.toUTCString.call(e)),pm(e)&&(h=" "+tm(e)),0!==o.length||f&&0!=e.length?r<0?fm(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function tm(t){return"["+Error.prototype.toString.call(t)+"]"}function em(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Sm(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=im(r)?Qv(t,a.value,null):Qv(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),hm(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function rm(t){return Array.isArray(t)}function nm(t){return"boolean"==typeof t}function im(t){return null===t}function om(t){return null==t}function sm(t){return"number"==typeof t}function um(t){return"string"==typeof t}function am(t){return"symbol"==typeof t}function hm(t){return void 0===t}function fm(t){return cm(t)&&"[object RegExp]"===vm(t)}function cm(t){return"object"==typeof t&&null!==t}function lm(t){return cm(t)&&"[object Date]"===vm(t)}function pm(t){return cm(t)&&("[object Error]"===vm(t)||t instanceof Error)}function dm(t){return"function"==typeof t}function gm(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function ym(t){return Buffer.isBuffer(t)}function vm(t){return Object.prototype.toString.call(t)}function mm(t){return t<10?"0"+t.toString(10):t.toString(10)}Yv.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]},Yv.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var wm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bm(){var t=new Date,e=[mm(t.getHours()),mm(t.getMinutes()),mm(t.getSeconds())].join(":");return[t.getDate(),wm[t.getMonth()],e].join(" ")}function Em(){console.log("%s - %s",bm(),Wv.apply(null,arguments))}function _m(t,e){if(!e||!cm(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Sm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Im={inherits:Gv,_extend:_m,log:Em,isBuffer:ym,isPrimitive:gm,isFunction:dm,isError:pm,isDate:lm,isObject:cm,isRegExp:fm,isUndefined:hm,isSymbol:am,isString:um,isNumber:sm,isNullOrUndefined:om,isNull:im,isBoolean:nm,isArray:rm,inspect:Yv,deprecate:Vv,format:Wv,debuglog:Xv},Tm=Object.freeze({__proto__:null,format:Wv,deprecate:Vv,debuglog:Xv,inspect:Yv,isArray:rm,isBoolean:nm,isNull:im,isNullOrUndefined:om,isNumber:sm,isString:um,isSymbol:am,isUndefined:hm,isRegExp:fm,isObject:cm,isDate:lm,isError:pm,isFunction:dm,isPrimitive:gm,isBuffer:ym,log:Em,inherits:Gv,_extend:_m,default:Im});function Om(){this.head=null,this.tail=null,this.length=0}Om.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Om.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Om.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Om.prototype.clear=function(){this.head=this.tail=null,this.length=0},Om.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Om.prototype.concat=function(t){if(0===this.length)return I.alloc(0);if(1===this.length)return this.head.data;for(var e=I.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Am=I.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function km(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Am(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Mm;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xm;break;default:return void(this.write=Pm)}this.charBuffer=new I(6),this.charReceived=0,this.charLength=0}function Pm(t){return t.toString(this.encoding)}function Mm(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xm(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}km.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},km.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},km.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Bm.ReadableState=Nm;var Rm=Xv("stream");function Nm(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof aw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Om,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new km(t.encoding),this.encoding=t.encoding)}function Bm(t){if(!(this instanceof Bm))return new Bm(t);this._readableState=new Nm(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),vv.call(this)}function Cm(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Dm(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Dm(t))),function(t,e){e.readingMore||(e.readingMore=!0,jv(jm,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Lm?t=Lm:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Dm(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Rm("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?jv(Hm,t):Hm(t))}function Hm(t){Rm("emit readable"),t.emit("readable"),Gm(t)}function jm(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Wm(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,jv(Vm,e,t))}function Vm(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function $m(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Rm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Wm(this):Dm(this),null;if(0===(t=Um(t,e))&&e.ended)return 0===e.length&&Wm(this),null;var n,i=e.needReadable;return Rm("need readable",i),(0===e.length||e.length-t0?Km(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Wm(this)),null!==n&&this.emit("data",n),n},Bm.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Bm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Rm("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Rm("onunpipe"),t===r&&h()}function s(){Rm("onend"),t.end()}n.endEmitted?jv(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Rm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Gm(t))}}(r);t.on("drain",u);var a=!1;function h(){Rm("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Rm("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==$m(n.pipes,t))&&!a&&(Rm("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Rm("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Rm("onfinish"),t.removeListener("close",p),g()}function g(){Rm("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Rm("pipe resume"),r.resume()),t},Bm.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Jm.prototype._write=function(t,e,r){r(new Error("not implemented"))},Jm.prototype._writev=null,Jm.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,nw(t,e),r&&(e.finished?jv(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Gv(aw,Bm);for(var ow=Object.keys(Jm.prototype),sw=0;sw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Sw.alloc(0);for(var e=Sw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ow(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Sw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Tw,value:function(t,e){return Iw(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Bw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Bw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Cw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Cw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Bw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Bw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Bw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Bw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Bw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Bw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Bw("ERR_STREAM_WRITE_AFTER_END","write after end"),Bw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Bw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Bw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Rw.codes=Nw;var Lw=Rw.codes.ERR_INVALID_OPT_VALUE;var Uw,Dw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Lw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Hw=ww.deprecate,jw=ub;function Fw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}ub.WritableState=sb;var qw={deprecate:Hw},Gw=mw,Kw=ht.Buffer,Ww=r.Uint8Array||function(){};var Vw,$w=xw,zw=Dw.getHighWaterMark,Xw=Rw.codes,Yw=Xw.ERR_INVALID_ARG_TYPE,Jw=Xw.ERR_METHOD_NOT_IMPLEMENTED,Zw=Xw.ERR_MULTIPLE_CALLBACK,Qw=Xw.ERR_STREAM_CANNOT_PIPE,tb=Xw.ERR_STREAM_DESTROYED,eb=Xw.ERR_STREAM_NULL_VALUES,rb=Xw.ERR_STREAM_WRITE_AFTER_END,nb=Xw.ERR_UNKNOWN_ENCODING,ib=$w.errorOrDestroy;function ob(){}function sb(t,e,r){Uw=Uw||gb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Uw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=zw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Zw;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(pb,t,e),t._writableState.errorEmitted=!0,ib(t,n)):(i(n),t._writableState.errorEmitted=!0,ib(t,n),pb(t,e))}(t,r,n,e,i);else{var o=cb(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||fb(t,r),n?process.nextTick(hb,t,r,o,i):hb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new Fw(this)}function ub(t){var e=this instanceof(Uw=Uw||gb);if(!e&&!Vw.call(ub,this))return new ub(t);this._writableState=new sb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Gw.call(this)}function ab(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new tb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),pb(t,e)}function fb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,ab(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new Fw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(ab(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function cb(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function lb(t,e){t._final((function(r){e.pendingcb--,r&&ib(t,r),e.prefinished=!0,t.emit("prefinish"),pb(t,e)}))}function pb(t,e){var r=cb(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(lb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}Zt.exports(ub,Gw),sb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(sb.prototype,"buffer",{get:qw.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Vw=Function.prototype[Symbol.hasInstance],Object.defineProperty(ub,Symbol.hasInstance,{value:function(t){return!!Vw.call(this,t)||this===ub&&(t&&t._writableState instanceof sb)}})):Vw=function(t){return t instanceof this},ub.prototype.pipe=function(){ib(this,new Qw)},ub.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Kw.isBuffer(n)||n instanceof Ww);return s&&!Kw.isBuffer(t)&&(t=function(t){return Kw.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ob),i.ending?function(t,e){var r=new rb;ib(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new eb:"string"==typeof r||e.objectMode||(i=new Yw("chunk",["string","Buffer"],r)),!i||(ib(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Kw.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new nb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(ub.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(ub.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),ub.prototype._write=function(t,e,r){r(new Jw("_write()"))},ub.prototype._writev=null,ub.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,pb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(ub.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(ub.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),ub.prototype.destroy=$w.destroy,ub.prototype._undestroy=$w.undestroy,ub.prototype._destroy=function(t,e){e(t)};var db=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},gb=Eb,yb=aE,vb=jw;Zt.exports(Eb,yb);for(var mb=db(vb.prototype),wb=0;wb>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Pb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Mb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function xb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Rb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Nb(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Bb(t){return t.toString(this.encoding)}function Cb(t){return t&&t.length?this.write(t):""}Ib.StringDecoder=Ab,Ab.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Ab.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Lb=Rw.codes.ERR_STREAM_PREMATURE_CLOSE;function Ub(){}var Db,Hb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===cE.prototype||(e=function(t){return cE.from(t)}(e)),n)s.endEmitted?OE(t,new TE):xE(t,s,e,!0);else if(s.ended)OE(t,new SE);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?xE(t,s,e,!1):LE(t,s)):xE(t,s,e,!1)}else n||(s.reading=!1,LE(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=RE?t=RE:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function BE(t){var e=t._readableState;pE("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(pE("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(CE,t))}function CE(t){var e=t._readableState;pE("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,FE(t)}function LE(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(UE,t,e))}function UE(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function HE(t){pE("readable nexttick read 0"),t.read(0)}function jE(t,e){pE("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),FE(t),e.flowing&&!e.reading&&t.read(0)}function FE(t){var e=t._readableState;for(pE("flow",e.flowing);e.flowing&&null!==t.read(););}function qE(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function GE(t){var e=t._readableState;pE("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(KE,e,t))}function KE(t,e){if(pE("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function WE(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return pE("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?GE(this):BE(this),null;if(0===(t=NE(t,e))&&e.ended)return 0===e.length&&GE(this),null;var n,i=e.needReadable;return pE("need readable",i),(0===e.length||e.length-t0?qE(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&GE(this)),null!==n&&this.emit("data",n),n},PE.prototype._read=function(t){OE(this,new IE("_read()"))},PE.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,pE("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){pE("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,pE("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){pE("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;pE("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&hE(t,"data")&&(e.flowing=!0,FE(t))}}(r);t.on("drain",u);var a=!1;function h(e){pE("ondata");var i=t.write(e);pE("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==WE(n.pipes,t))&&!a&&(pE("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){pE("onerror",e),p(),t.removeListener("error",f),0===hE(t,"error")&&OE(t,e)}function c(){t.removeListener("finish",l),p()}function l(){pE("onfinish"),t.removeListener("close",c),p()}function p(){pE("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(pE("pipe resume"),r.resume()),t},PE.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,pE("on readable",n.length,n.reading),n.length?BE(this):n.reading||process.nextTick(HE,this))),r},PE.prototype.addListener=PE.prototype.on,PE.prototype.removeListener=function(t,e){var r=fE.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(DE,this),r},PE.prototype.removeAllListeners=function(t){var e=fE.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(DE,this),e},PE.prototype.resume=function(){var t=this._readableState;return t.flowing||(pE("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(jE,t,e))}(this,t)),t.paused=!1,this},PE.prototype.pause=function(){return pE("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(pE("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},PE.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(pE("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(pE("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(l_),s||(o.forEach(l_),i(n))}))}));return e.reduce(p_)};!function(t,e){var r=yw;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=aE).Stream=r||e,e.Readable=e,e.Writable=jw,e.Duplex=gb,e.Transform=VE,e.PassThrough=i_,e.finished=Hb,e.pipeline=g_)}(gv,gv.exports);var y_=h.exports.Buffer,v_=gv.exports.Transform;function m_(t){v_.call(this),this._block=y_.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,Zt.exports)(m_,v_),m_.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},m_.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},m_.prototype.update=function(t,e){if(function(t,e){if(!y_.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");y_.isBuffer(t)||(t=y_.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},m_.prototype._update=function(){throw new Error("_update is not implemented")},m_.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},m_.prototype._digest=function(){throw new Error("_digest is not implemented")};var w_=m_,b_=ht.Buffer,E_=Zt.exports,__=w_,S_=new Array(16),I_=[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],T_=[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],O_=[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],A_=[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],k_=[0,1518500249,1859775393,2400959708,2840853838],P_=[1352829926,1548603684,1836072691,2053994217,0];function M_(){__.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function x_(t,e){return t<>>32-e}function R_(t,e,r,n,i,o,s,u){return x_(t+(e^r^n)+o+s|0,u)+i|0}function N_(t,e,r,n,i,o,s,u){return x_(t+(e&r|~e&n)+o+s|0,u)+i|0}function B_(t,e,r,n,i,o,s,u){return x_(t+((e|~r)^n)+o+s|0,u)+i|0}function C_(t,e,r,n,i,o,s,u){return x_(t+(e&n|r&~n)+o+s|0,u)+i|0}function L_(t,e,r,n,i,o,s,u){return x_(t+(e^(r|~n))+o+s|0,u)+i|0}E_(M_,__),M_.prototype._update=function(){for(var t=S_,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=R_(r,n,i,o,s,t[I_[l]],k_[0],O_[l]),d=L_(u,a,h,f,c,t[T_[l]],P_[0],A_[l])):l<32?(p=N_(r,n,i,o,s,t[I_[l]],k_[1],O_[l]),d=C_(u,a,h,f,c,t[T_[l]],P_[1],A_[l])):l<48?(p=B_(r,n,i,o,s,t[I_[l]],k_[2],O_[l]),d=B_(u,a,h,f,c,t[T_[l]],P_[2],A_[l])):l<64?(p=C_(r,n,i,o,s,t[I_[l]],k_[3],O_[l]),d=N_(u,a,h,f,c,t[T_[l]],P_[3],A_[l])):(p=L_(r,n,i,o,s,t[I_[l]],k_[4],O_[l]),d=R_(u,a,h,f,c,t[T_[l]],P_[4],A_[l])),r=s,s=o,o=x_(i,10),i=n,n=p,u=c,c=f,f=x_(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},M_.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=b_.alloc?b_.alloc(20):new b_(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var U_=M_,D_={exports:{}},H_=h.exports.Buffer;function j_(t,e){this._block=H_.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}j_.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=H_.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},j_.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var F_=j_,q_=Zt.exports,G_=F_,K_=h.exports.Buffer,W_=[1518500249,1859775393,-1894007588,-899497514],V_=new Array(80);function $_(){this.init(),this._w=V_,G_.call(this,64,56)}function z_(t){return t<<30|t>>>2}function X_(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}q_($_,G_),$_.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},$_.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+X_(f,i,o,s)+u+r[h]+W_[f];u=s,s=o,o=z_(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},$_.prototype._hash=function(){var t=K_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var Y_=$_,J_=Zt.exports,Z_=F_,Q_=h.exports.Buffer,tS=[1518500249,1859775393,-1894007588,-899497514],eS=new Array(80);function rS(){this.init(),this._w=eS,Z_.call(this,64,56)}function nS(t){return t<<5|t>>>27}function iS(t){return t<<30|t>>>2}function oS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}J_(rS,Z_),rS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},rS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=nS(n)+oS(f,i,o,s)+u+r[h]+tS[f]|0;u=s,s=o,o=iS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},rS.prototype._hash=function(){var t=Q_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var sS=rS,uS=Zt.exports,aS=F_,hS=h.exports.Buffer,fS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cS=new Array(64);function lS(){this.init(),this._w=cS,aS.call(this,64,56)}function pS(t,e,r){return r^t&(e^r)}function dS(t,e,r){return t&e|r&(t|e)}function gS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function yS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function vS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function mS(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}uS(lS,aS),lS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},lS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=mS(e[f-2])+e[f-7]+vS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+yS(s)+pS(s,u,a)+fS[c]+e[c]|0,p=gS(r)+dS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},lS.prototype._hash=function(){var t=hS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var wS=lS,bS=Zt.exports,ES=wS,_S=F_,SS=h.exports.Buffer,IS=new Array(64);function TS(){this.init(),this._w=IS,_S.call(this,64,56)}bS(TS,ES),TS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},TS.prototype._hash=function(){var t=SS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var OS=TS,AS=Zt.exports,kS=F_,PS=h.exports.Buffer,MS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xS=new Array(160);function RS(){this.init(),this._w=xS,kS.call(this,128,112)}function NS(t,e,r){return r^t&(e^r)}function BS(t,e,r){return t&e|r&(t|e)}function CS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function LS(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function US(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function DS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function HS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function jS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function FS(t,e){return t>>>0>>0?1:0}AS(RS,kS),RS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},RS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=US(w,b),_=DS(b,w),S=HS(w=e[m-4],b=e[m-4+1]),I=jS(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],k=e[m-32+1],P=_+O|0,M=E+T+FS(P,_)|0;M=(M=M+S+FS(P=P+I|0,I)|0)+A+FS(P=P+k|0,k)|0,e[m]=M,e[m+1]=P}for(var x=0;x<160;x+=2){M=e[x],P=e[x+1];var R=BS(r,n,i),N=BS(f,c,l),B=CS(r,f),C=CS(f,r),L=LS(s,d),U=LS(d,s),D=MS[x],H=MS[x+1],j=NS(s,u,a),F=NS(d,g,y),q=v+U|0,G=h+L+FS(q,v)|0;G=(G=(G=G+j+FS(q=q+F|0,F)|0)+D+FS(q=q+H|0,H)|0)+M+FS(q=q+P|0,P)|0;var K=C+N|0,W=B+R+FS(K,C)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+G+FS(d=p+q|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+W+FS(f=q+K|0,q)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+FS(this._al,f)|0,this._bh=this._bh+n+FS(this._bl,c)|0,this._ch=this._ch+i+FS(this._cl,l)|0,this._dh=this._dh+o+FS(this._dl,p)|0,this._eh=this._eh+s+FS(this._el,d)|0,this._fh=this._fh+u+FS(this._fl,g)|0,this._gh=this._gh+a+FS(this._gl,y)|0,this._hh=this._hh+h+FS(this._hl,v)|0},RS.prototype._hash=function(){var t=PS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var qS=RS,GS=Zt.exports,KS=qS,WS=F_,VS=h.exports.Buffer,$S=new Array(160);function zS(){this.init(),this._w=$S,WS.call(this,128,112)}GS(zS,KS),zS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},zS.prototype._hash=function(){var t=VS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var XS=zS,YS=D_.exports=function(t){t=t.toLowerCase();var e=YS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};YS.sha=Y_,YS.sha1=sS,YS.sha224=OS,YS.sha256=wS,YS.sha384=XS,YS.sha512=qS;var JS=D_.exports;function ZS(t){return(new U_).update(JS("sha256").update(t).digest()).digest()}var QS,tI=(QS=function(t,e){return QS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},QS(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}QS(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),eI=function(t,e){this.psbt=t,this.masterFp=e},rI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(eI),nI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(rI),iI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new cv,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Bp.sha256(Buffer.from("TapTweak","utf-8"));return Bp.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(xt.exports.pointAddScalar(e,r)).slice(1)},e}(rI),oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=this.createRedeemScript(t),n=ZS(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=ZS(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(rI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(rI),uI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},aI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return lI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new cI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new cI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function UI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,LI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,LI(t.script.length),t.script])}))),r}function DI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,LI(t.script.length),t.script,t.sequence])}));var a=UI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),LI(t.inputs.length),s,a])}var HI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new pI(e,dI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return HI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I;return jI(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new _I,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new iI(e,r):t.additionals.includes("bech32")?new sI(e,r):t.segwit?new oI(e,r):new nI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new cv).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new cv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new cv;BI(h,f),BI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new cv).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}NI(t,r)}}(r),I=function(t){var e,r,n=new cv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new cv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nT(t,e,r){return tT(this,void 0,void 0,(function(){var n,i,o,s;return eT(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function iT(t,e,r,n){return void 0===n&&(n=[]),tT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R=this;return eT(this,(function(N){switch(N.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return tT(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return eT(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>pv?pv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=rT(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,nT(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return nT(t,e)},[4,nT(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),LI(o.length)]),e)];case 1:N.sent(),N.label=2;case 2:N.trys.push([2,8,9,10]),d=rT(o),g=d.next(),N.label=3;case 3:return g.done?[3,7]:(y=g.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?y.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([y.prevout,m,v?Buffer.from([0]):LI(y.script.length)]),[4,nT(t,O)]);case 4:return N.sent(),[4,f?p(Buffer.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:N.sent(),N.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=N.sent(),k={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,nT(t,LI(s.length))];case 11:N.sent(),N.label=12;case 12:N.trys.push([12,17,18,19]),b=rT(s),E=b.next(),N.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),LI(_.script.length),_.script]),[4,nT(t,O)]);case 14:N.sent(),N.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=N.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([LI(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return A=N.sent(),QI(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var oT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},sT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aT(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function hT(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),oT(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return sT(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),LI(r.inputs.length)]),[4,aT(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=uT(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),LI(p.script.length)]),[4,aT(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>pv?pv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=uT(y),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,aT(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function fT(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=JS("sha256").update(JS("sha256").update(DI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function cT(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=wt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var lT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},pT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:pv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var yT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ST={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function IT(t,e){return bT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C,L,U,D,H,j,F,q,G,K,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return ET(this,(function(ht){switch(ht.label){case 0:if(r=wT(wT({},ST),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,mT(t)];case 2:return v=ht.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||fv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),A=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),P=[],M=[],x=[],R=[],N=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},L=T&&!y?fT:iT,U=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=_T(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,L(t,$[1],$[0],c)]);case 7:j=ht.sent(),VI("hw","got trustedInput="+j),(F=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:dv,0),P.push({trustedInput:!0,value:Buffer.from(j,"hex"),sequence:F}),ht.label=8;case 8:q=$[0].outputs,G=$[1],q&&G<=q.length-1&&M.push(q[G]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:dv,0),{script:O,prevout:A,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),ZS(R[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[P[it]]:P,T?X.inputs=[wT(wT({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,hT(t,!T&&N,X,Y,T,!!l&&!b,c,y)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,dT(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,gT(t,U,c)];case 30:ht.sent(),ht.label=31;case 31:return N&&(d(),w(1,0)),[4,cT(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,N&&(N=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},xT={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function RT(t,e){return kT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C;return PT(this,(function(L){switch(L.label){case 0:r=AT(AT({},xT),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?fT:iT,b=Buffer.from(o,"hex"),L.label=1;case 1:L.trys.push([1,7,8,9]),E=MT(n),_=E.next(),L.label=2;case 2:return _.done?[3,6]:(P=_.value,v?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=L.sent(),(A=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:dv,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:A}),L.label=4;case 4:I=P[0].outputs,T=P[1],I&&T<=I.length-1&&d.push(I[T]),L.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=L.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:dv,0),m.inputs.push({script:f,prevout:c,sequence:A});return a?[4,hT(t,!0,m,p,!0)]:[3,12];case 10:return L.sent(),[4,gT(t,b)];case 11:L.sent(),L.label=12;case 12:k=0,L.label=13;case 13:return k=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[k].script,x=Object.assign({},m),R=a?[p[k]]:p,a?x.inputs=[AT(AT({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,hT(t,!a&&y,x,R,a)]):[3,19];case 14:return L.sent(),a?[3,16]:[4,gT(t,b)];case 15:L.sent(),L.label=16;case 16:return[4,cT(t,i[k],s,u)];case 17:N=L.sent(),g.push(a?N.toString("hex"):N.slice(0,N.length-1).toString("hex")),m.inputs[k].script=f,y&&(y=!1),L.label=18;case 18:return k++,[3,13];case 19:return[2,g]}}))}))}var NT=function(){return NT=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,u()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),IT(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),RT(this.transport,t)},t}();function UT(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var DT=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function HT(t){return JS("sha256").update(t).digest()}var jT,FT=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new hI(t.map((function(t){return fI(t)}))),this.values=e,this.valuesTree=new hI(e.map((function(t){return fI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([LI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),qT=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),GT=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},KT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},zT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(jT||(jT={}));var YT,JT,ZT=function(){},QT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=jT.YIELD,n.results=e,n}return VT(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(ZT),tO=function(t){function e(e,r){var n=t.call(this)||this;return n.code=jT.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=LI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,zT([],$T(a.slice(-f)),!1)),Buffer.concat(zT([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],$T(a.slice(0,h)),!1))},e}(ZT),rO=function(t){function e(e){var r=t.call(this)||this;return r.code=jT.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(YT||(YT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(JT||(JT={}));var aO=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return oO(this,void 0,void 0,(function(){var n,i,o;return sO(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,JT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return oO(this,void 0,void 0,(function(){return sO(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(YT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),mt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return oO(this,void 0,void 0,(function(){var o,s;return sO(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new iO((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(YT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return oO(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S;return sO(this,(function(I){switch(I.label){case 0:if(i=new WT(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new iO(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=uO(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=uO(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new hI(i.inputMapCommitments.map((function(t){return fI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new hI(i.outputMapCommitments.map((function(t){return fI(t)}))).getRoot(),[4,this.makeRequest(YT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),LI(i.getGlobalInputCount()),c,LI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=uO(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return oO(this,void 0,void 0,(function(){return sO(this,(function(t){return[2,this.makeRequest(YT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var hO=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},fO=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof qI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||lO(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(Buffer.from([3,0,0,128]))||y.equals(Buffer.from([4,0,0,128])),m=y.equals(Buffer.from([1,0,0,0]))||y.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(c=g.slice(a,4+a),a+=4);var w=CI(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new LT(this.transport)},t.prototype.new=function(){return new qI(new aO(this.transport))},t}();function lO(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var pO=Object.freeze({__proto__:null,default:cO}),dO={},gO={},yO={},vO={};Object.defineProperty(vO,"__esModule",{value:!0});var mO="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wO={},bO={};vO.addCustomErrorDeserializer=function(t,e){bO[t]=e};var EO=vO.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,wO[t]=e,e};function _O(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":mO(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=_O(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}vO.deserializeError=function t(e){if("object"===(void 0===e?"undefined":mO(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=bO[i];if(o)n=o(e);else{var s="Error"===i?Error:wO[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=EO(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},vO.serializeError=function(t){return t?"object"===(void 0===t?"undefined":mO(t))?_O(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(yO,"__esModule",{value:!0}),yO.StatusCodes=yO.DBNotReset=yO.DBWrongPassword=yO.NoDBPathGiven=yO.FirmwareOrAppUpdateRequired=yO.LedgerAPI5xx=yO.LedgerAPI4xx=yO.GenuineCheckFailed=yO.PairingFailed=yO.SyncError=yO.FeeTooHigh=yO.FeeRequired=yO.FeeNotLoaded=yO.CantScanQRCode=yO.ETHAddressNonEIP=yO.WrongAppForCurrency=yO.WrongDeviceForAccount=yO.WebsocketConnectionFailed=yO.WebsocketConnectionError=yO.DeviceShouldStayInApp=yO.TransportWebUSBGestureRequired=yO.TransportInterfaceNotAvailable=yO.TransportOpenUserCancelled=yO.UserRefusedOnDevice=yO.UserRefusedAllowManager=yO.UserRefusedFirmwareUpdate=yO.UserRefusedAddress=yO.UserRefusedDeviceNameChange=yO.UpdateYourApp=yO.UnavailableTezosOriginatedAccountSend=yO.UnavailableTezosOriginatedAccountReceive=yO.RecipientRequired=yO.MCUNotGenuineToDashboard=yO.UnexpectedBootloader=yO.TimeoutTagged=yO.RecommendUndelegation=yO.RecommendSubAccountsToEmpty=yO.PasswordIncorrectError=yO.PasswordsDontMatchError=yO.GasLessThanEstimate=yO.NotSupportedLegacyAddress=yO.NotEnoughGas=yO.NoAccessToCamera=yO.NotEnoughBalanceBecauseDestinationNotCreated=yO.NotEnoughSpendableBalance=yO.NotEnoughBalanceInParentAccount=yO.NotEnoughBalanceToDelegate=yO.NotEnoughBalance=yO.NoAddressesFound=yO.NetworkDown=yO.ManagerUninstallBTCDep=yO.ManagerNotEnoughSpaceError=yO.ManagerFirmwareNotEnoughSpaceError=yO.ManagerDeviceLockedError=yO.ManagerAppDepUninstallRequired=yO.ManagerAppDepInstallRequired=yO.ManagerAppRelyOnBTCError=yO.ManagerAppAlreadyInstalledError=yO.LedgerAPINotAvailable=yO.LedgerAPIErrorWithMessage=yO.LedgerAPIError=yO.UnknownMCU=yO.LatestMCUInstalledError=yO.InvalidAddressBecauseDestinationIsAlsoSource=yO.InvalidAddress=yO.InvalidXRPTag=yO.HardResetFail=yO.FeeEstimationFailed=yO.EthAppPleaseEnableContractData=yO.EnpointConfigError=yO.DisconnectedDeviceDuringOperation=yO.DisconnectedDevice=yO.DeviceSocketNoBulkStatus=yO.DeviceSocketFail=yO.DeviceNameInvalid=yO.DeviceHalted=yO.DeviceInOSUExpected=yO.DeviceOnDashboardUnexpected=yO.DeviceOnDashboardExpected=yO.DeviceNotGenuineError=yO.DeviceGenuineSocketEarlyClose=yO.DeviceAppVerifyNotSupported=yO.CurrencyNotSupported=yO.CashAddrNotSupported=yO.CantOpenDevice=yO.BtcUnmatchedApp=yO.BluetoothRequired=yO.AmountRequired=yO.AccountNotSupported=yO.AccountNameRequiredError=yO.addCustomErrorDeserializer=yO.createCustomErrorClass=yO.deserializeError=yO.serializeError=void 0,yO.TransportError=IO,yO.getAltStatusMessage=OO,yO.TransportStatusError=AO;var SO=vO;function IO(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}yO.serializeError=SO.serializeError,yO.deserializeError=SO.deserializeError,yO.createCustomErrorClass=SO.createCustomErrorClass,yO.addCustomErrorDeserializer=SO.addCustomErrorDeserializer,yO.AccountNameRequiredError=(0,SO.createCustomErrorClass)("AccountNameRequired"),yO.AccountNotSupported=(0,SO.createCustomErrorClass)("AccountNotSupported"),yO.AmountRequired=(0,SO.createCustomErrorClass)("AmountRequired"),yO.BluetoothRequired=(0,SO.createCustomErrorClass)("BluetoothRequired"),yO.BtcUnmatchedApp=(0,SO.createCustomErrorClass)("BtcUnmatchedApp"),yO.CantOpenDevice=(0,SO.createCustomErrorClass)("CantOpenDevice"),yO.CashAddrNotSupported=(0,SO.createCustomErrorClass)("CashAddrNotSupported"),yO.CurrencyNotSupported=(0,SO.createCustomErrorClass)("CurrencyNotSupported"),yO.DeviceAppVerifyNotSupported=(0,SO.createCustomErrorClass)("DeviceAppVerifyNotSupported"),yO.DeviceGenuineSocketEarlyClose=(0,SO.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),yO.DeviceNotGenuineError=(0,SO.createCustomErrorClass)("DeviceNotGenuine"),yO.DeviceOnDashboardExpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardExpected"),yO.DeviceOnDashboardUnexpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardUnexpected"),yO.DeviceInOSUExpected=(0,SO.createCustomErrorClass)("DeviceInOSUExpected"),yO.DeviceHalted=(0,SO.createCustomErrorClass)("DeviceHalted"),yO.DeviceNameInvalid=(0,SO.createCustomErrorClass)("DeviceNameInvalid"),yO.DeviceSocketFail=(0,SO.createCustomErrorClass)("DeviceSocketFail"),yO.DeviceSocketNoBulkStatus=(0,SO.createCustomErrorClass)("DeviceSocketNoBulkStatus"),yO.DisconnectedDevice=(0,SO.createCustomErrorClass)("DisconnectedDevice"),yO.DisconnectedDeviceDuringOperation=(0,SO.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),yO.EnpointConfigError=(0,SO.createCustomErrorClass)("EnpointConfig"),yO.EthAppPleaseEnableContractData=(0,SO.createCustomErrorClass)("EthAppPleaseEnableContractData"),yO.FeeEstimationFailed=(0,SO.createCustomErrorClass)("FeeEstimationFailed"),yO.HardResetFail=(0,SO.createCustomErrorClass)("HardResetFail"),yO.InvalidXRPTag=(0,SO.createCustomErrorClass)("InvalidXRPTag"),yO.InvalidAddress=(0,SO.createCustomErrorClass)("InvalidAddress"),yO.InvalidAddressBecauseDestinationIsAlsoSource=(0,SO.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),yO.LatestMCUInstalledError=(0,SO.createCustomErrorClass)("LatestMCUInstalledError"),yO.UnknownMCU=(0,SO.createCustomErrorClass)("UnknownMCU"),yO.LedgerAPIError=(0,SO.createCustomErrorClass)("LedgerAPIError"),yO.LedgerAPIErrorWithMessage=(0,SO.createCustomErrorClass)("LedgerAPIErrorWithMessage"),yO.LedgerAPINotAvailable=(0,SO.createCustomErrorClass)("LedgerAPINotAvailable"),yO.ManagerAppAlreadyInstalledError=(0,SO.createCustomErrorClass)("ManagerAppAlreadyInstalled"),yO.ManagerAppRelyOnBTCError=(0,SO.createCustomErrorClass)("ManagerAppRelyOnBTC"),yO.ManagerAppDepInstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepInstallRequired"),yO.ManagerAppDepUninstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepUninstallRequired"),yO.ManagerDeviceLockedError=(0,SO.createCustomErrorClass)("ManagerDeviceLocked"),yO.ManagerFirmwareNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),yO.ManagerNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerNotEnoughSpace"),yO.ManagerUninstallBTCDep=(0,SO.createCustomErrorClass)("ManagerUninstallBTCDep"),yO.NetworkDown=(0,SO.createCustomErrorClass)("NetworkDown"),yO.NoAddressesFound=(0,SO.createCustomErrorClass)("NoAddressesFound"),yO.NotEnoughBalance=(0,SO.createCustomErrorClass)("NotEnoughBalance"),yO.NotEnoughBalanceToDelegate=(0,SO.createCustomErrorClass)("NotEnoughBalanceToDelegate"),yO.NotEnoughBalanceInParentAccount=(0,SO.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),yO.NotEnoughSpendableBalance=(0,SO.createCustomErrorClass)("NotEnoughSpendableBalance"),yO.NotEnoughBalanceBecauseDestinationNotCreated=(0,SO.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),yO.NoAccessToCamera=(0,SO.createCustomErrorClass)("NoAccessToCamera"),yO.NotEnoughGas=(0,SO.createCustomErrorClass)("NotEnoughGas"),yO.NotSupportedLegacyAddress=(0,SO.createCustomErrorClass)("NotSupportedLegacyAddress"),yO.GasLessThanEstimate=(0,SO.createCustomErrorClass)("GasLessThanEstimate"),yO.PasswordsDontMatchError=(0,SO.createCustomErrorClass)("PasswordsDontMatch"),yO.PasswordIncorrectError=(0,SO.createCustomErrorClass)("PasswordIncorrect"),yO.RecommendSubAccountsToEmpty=(0,SO.createCustomErrorClass)("RecommendSubAccountsToEmpty"),yO.RecommendUndelegation=(0,SO.createCustomErrorClass)("RecommendUndelegation"),yO.TimeoutTagged=(0,SO.createCustomErrorClass)("TimeoutTagged"),yO.UnexpectedBootloader=(0,SO.createCustomErrorClass)("UnexpectedBootloader"),yO.MCUNotGenuineToDashboard=(0,SO.createCustomErrorClass)("MCUNotGenuineToDashboard"),yO.RecipientRequired=(0,SO.createCustomErrorClass)("RecipientRequired"),yO.UnavailableTezosOriginatedAccountReceive=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),yO.UnavailableTezosOriginatedAccountSend=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),yO.UpdateYourApp=(0,SO.createCustomErrorClass)("UpdateYourApp"),yO.UserRefusedDeviceNameChange=(0,SO.createCustomErrorClass)("UserRefusedDeviceNameChange"),yO.UserRefusedAddress=(0,SO.createCustomErrorClass)("UserRefusedAddress"),yO.UserRefusedFirmwareUpdate=(0,SO.createCustomErrorClass)("UserRefusedFirmwareUpdate"),yO.UserRefusedAllowManager=(0,SO.createCustomErrorClass)("UserRefusedAllowManager"),yO.UserRefusedOnDevice=(0,SO.createCustomErrorClass)("UserRefusedOnDevice"),yO.TransportOpenUserCancelled=(0,SO.createCustomErrorClass)("TransportOpenUserCancelled"),yO.TransportInterfaceNotAvailable=(0,SO.createCustomErrorClass)("TransportInterfaceNotAvailable"),yO.TransportWebUSBGestureRequired=(0,SO.createCustomErrorClass)("TransportWebUSBGestureRequired"),yO.DeviceShouldStayInApp=(0,SO.createCustomErrorClass)("DeviceShouldStayInApp"),yO.WebsocketConnectionError=(0,SO.createCustomErrorClass)("WebsocketConnectionError"),yO.WebsocketConnectionFailed=(0,SO.createCustomErrorClass)("WebsocketConnectionFailed"),yO.WrongDeviceForAccount=(0,SO.createCustomErrorClass)("WrongDeviceForAccount"),yO.WrongAppForCurrency=(0,SO.createCustomErrorClass)("WrongAppForCurrency"),yO.ETHAddressNonEIP=(0,SO.createCustomErrorClass)("ETHAddressNonEIP"),yO.CantScanQRCode=(0,SO.createCustomErrorClass)("CantScanQRCode"),yO.FeeNotLoaded=(0,SO.createCustomErrorClass)("FeeNotLoaded"),yO.FeeRequired=(0,SO.createCustomErrorClass)("FeeRequired"),yO.FeeTooHigh=(0,SO.createCustomErrorClass)("FeeTooHigh"),yO.SyncError=(0,SO.createCustomErrorClass)("SyncError"),yO.PairingFailed=(0,SO.createCustomErrorClass)("PairingFailed"),yO.GenuineCheckFailed=(0,SO.createCustomErrorClass)("GenuineCheckFailed"),yO.LedgerAPI4xx=(0,SO.createCustomErrorClass)("LedgerAPI4xx"),yO.LedgerAPI5xx=(0,SO.createCustomErrorClass)("LedgerAPI5xx"),yO.FirmwareOrAppUpdateRequired=(0,SO.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),yO.NoDBPathGiven=(0,SO.createCustomErrorClass)("NoDBPathGiven"),yO.DBWrongPassword=(0,SO.createCustomErrorClass)("DBWrongPassword"),yO.DBNotReset=(0,SO.createCustomErrorClass)("DBNotReset"),IO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportError",(function(t){return new IO(t.message,t.id)}));var TO=yO.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function OO(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function AO(t){this.name="TransportStatusError";var e=Object.keys(TO).find((function(e){return TO[e]===t}))||"UNKNOWN_ERROR",r=OO(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}AO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new AO(t.statusCode)})),Object.defineProperty(gO,"__esModule",{value:!0}),gO.getAltStatusMessage=gO.StatusCodes=gO.TransportStatusError=gO.TransportError=void 0;var kO,PO=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[xO.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new xO.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new xO.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=NO(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new xO.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return PO(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new xO.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new xO.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();BO.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",BO.ErrorMessage_NoDeviceFound="No Ledger device found",gO.default=BO;var CO={};Object.defineProperty(CO,"__esModule",{value:!0});var LO=yO;function UO(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var DO={data:Buffer.alloc(0),dataLength:0,sequence:0};CO.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([UO(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var HO={};Object.defineProperty(HO,"__esModule",{value:!0});var jO=Object.assign||function(t){for(var e=1;e>8;return GO.find((function(t){return t.productIdMM===r}))},HO.identifyProductName=function(t){var e=qO[t];return GO.find((function(t){return t.id===e}))};var KO=[],WO={};for(var VO in FO){var $O=FO[VO],zO=$O.bluetoothSpec;if(zO)for(var XO=0;XO0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",oA());case 6:case"end":return t.stop()}}),t,this)}))),function(){return iA.apply(this,arguments)});var uA=HO;function aA(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var hA=[{vendorId:uA.ledgerUSBVendorId}];eA.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(dO,"__esModule",{value:!0});var fA=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,lA.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,dA.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,dA.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new gA.DisconnectedDeviceDuringOperation(e.message);throw e}))}},EA=dO.default=wA,_A=Object.freeze(e({__proto__:null,default:EA},[dO]));t.Btc=pO,t.TransportWebUSB=_A,Object.defineProperty(t,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 1df668e173e32cb98345af34f3a44ac89858b318 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 14:36:23 +1100 Subject: [PATCH 10/78] ... --- js/ledger.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index c301047c..f1bc9122 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,9 +2,9 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof y?e:y,o=Object.create(i.prototype),s=new k(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return M()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function y(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(P([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=y.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function A(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function k(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function P(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),A(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;A(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:P(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const i=2147483648;var o=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=i)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[s]+=i;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new o(n)},o.prototype.toPathArray=function(){return this.path},o.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var s=o,u=n(Object.freeze({__proto__:null,default:{}})),a=u.createHash,h={exports:{}},f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p=!1;function d(){p=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+f[i>>12&63]+f[i>>6&63]+f[63&i]);return o.join("")}function y(t){var e;p||d();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=f[e>>2],i+=f[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=f[e>>10],i+=f[e>>4&63],i+=f[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function m(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var w={}.toString,b=Array.isArray||function(t){return"[object Array]"==w.call(t)};I.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=_();function _(){return I.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function S(t,e){if(_()=_())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_().toString(16)+" bytes");return 0|t}function M(t){return!(null==t||!t._isBuffer)}function x(t,e){if(M(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return it(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ot(t).length;default:if(n)return it(t).length;e=(""+e).toLowerCase(),n=!0}}function R(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return $(this,e,r);case"utf8":case"utf-8":return G(this,e,r);case"ascii":return W(this,e,r);case"latin1":case"binary":return V(this,e,r);case"base64":return q(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function N(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=I.from(e,n)),M(e))return 0===e.length?-1:C(t,e,r,n,i);if("number"==typeof e)return e&=255,I.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):C(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function C(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function q(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function G(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=K)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},I.prototype.compare=function(t,e,r,n,i){if(!M(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return L(this,t,e,r);case"utf8":case"utf-8":return U(this,t,e,r);case"ascii":return D(this,t,e,r);case"latin1":case"binary":return H(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var K=4096;function W(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!M(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Z(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function Q(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function tt(t,e,r,n,i){return i||Q(t,0,r,4),m(t,e,r,n,23,4),r+4}function et(t,e,r,n,i){return i||Q(t,0,r,8),m(t,e,r,n,52,8),r+8}I.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},I.prototype.readUInt8=function(t,e){return e||X(t,1,this.length),this[t]},I.prototype.readUInt16LE=function(t,e){return e||X(t,2,this.length),this[t]|this[t+1]<<8},I.prototype.readUInt16BE=function(t,e){return e||X(t,2,this.length),this[t]<<8|this[t+1]},I.prototype.readUInt32LE=function(t,e){return e||X(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},I.prototype.readUInt32BE=function(t,e){return e||X(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},I.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},I.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},I.prototype.readInt8=function(t,e){return e||X(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},I.prototype.readInt16LE=function(t,e){e||X(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt16BE=function(t,e){e||X(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt32LE=function(t,e){return e||X(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},I.prototype.readInt32BE=function(t,e){return e||X(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},I.prototype.readFloatLE=function(t,e){return e||X(t,4,this.length),v(this,t,!0,23,4)},I.prototype.readFloatBE=function(t,e){return e||X(t,4,this.length),v(this,t,!1,23,4)},I.prototype.readDoubleLE=function(t,e){return e||X(t,8,this.length),v(this,t,!0,52,8)},I.prototype.readDoubleBE=function(t,e){return e||X(t,8,this.length),v(this,t,!1,52,8)},I.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},I.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},I.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Z(this,t,e,!0),e+4},I.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},I.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},I.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},I.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Z(this,t,e,!0),e+4},I.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeFloatLE=function(t,e,r){return tt(this,t,e,!0,r)},I.prototype.writeFloatBE=function(t,e,r){return tt(this,t,e,!1,r)},I.prototype.writeDoubleLE=function(t,e,r){return et(this,t,e,!0,r)},I.prototype.writeDoubleBE=function(t,e,r){return et(this,t,e,!1,r)},I.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!I.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ot(t){return function(t){var e,r,n,i,o,s;p||d();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new l(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(rt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function st(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ut(t){return null!=t&&(!!t._isBuffer||at(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&at(t.slice(0,0))}(t))}function at(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ht=n(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:I,SlowBuffer:function(t){return+t!=t&&(t=0),I.alloc(+t)},isBuffer:ut})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}const i=2147483648;var o=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=i)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[s]+=i;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new o(n)},o.prototype.toPathArray=function(){return this.path},o.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var s=o,u=n(Object.freeze({__proto__:null,default:{}})),a=u.createHash,h={exports:{}},f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p=!1;function d(){p=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+f[i>>12&63]+f[i>>6&63]+f[63&i]);return o.join("")}function y(t){var e;p||d();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=f[e>>2],i+=f[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=f[e>>10],i+=f[e>>4&63],i+=f[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function m(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var w={}.toString,b=Array.isArray||function(t){return"[object Array]"==w.call(t)};I.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=_();function _(){return I.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function S(t,e){if(_()=_())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_().toString(16)+" bytes");return 0|t}function M(t){return!(null==t||!t._isBuffer)}function x(t,e){if(M(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return it(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ot(t).length;default:if(n)return it(t).length;e=(""+e).toLowerCase(),n=!0}}function R(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return $(this,e,r);case"utf8":case"utf-8":return K(this,e,r);case"ascii":return W(this,e,r);case"latin1":case"binary":return V(this,e,r);case"base64":return F(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function N(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=I.from(e,n)),M(e))return 0===e.length?-1:C(t,e,r,n,i);if("number"==typeof e)return e&=255,I.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):C(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function C(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function F(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function K(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=G)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},I.prototype.compare=function(t,e,r,n,i){if(!M(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return U(this,t,e,r);case"utf8":case"utf-8":return L(this,t,e,r);case"ascii":return D(this,t,e,r);case"latin1":case"binary":return H(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var G=4096;function W(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!M(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Z(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function Q(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function tt(t,e,r,n,i){return i||Q(t,0,r,4),m(t,e,r,n,23,4),r+4}function et(t,e,r,n,i){return i||Q(t,0,r,8),m(t,e,r,n,52,8),r+8}I.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},I.prototype.readUInt8=function(t,e){return e||X(t,1,this.length),this[t]},I.prototype.readUInt16LE=function(t,e){return e||X(t,2,this.length),this[t]|this[t+1]<<8},I.prototype.readUInt16BE=function(t,e){return e||X(t,2,this.length),this[t]<<8|this[t+1]},I.prototype.readUInt32LE=function(t,e){return e||X(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},I.prototype.readUInt32BE=function(t,e){return e||X(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},I.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},I.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},I.prototype.readInt8=function(t,e){return e||X(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},I.prototype.readInt16LE=function(t,e){e||X(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt16BE=function(t,e){e||X(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt32LE=function(t,e){return e||X(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},I.prototype.readInt32BE=function(t,e){return e||X(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},I.prototype.readFloatLE=function(t,e){return e||X(t,4,this.length),v(this,t,!0,23,4)},I.prototype.readFloatBE=function(t,e){return e||X(t,4,this.length),v(this,t,!1,23,4)},I.prototype.readDoubleLE=function(t,e){return e||X(t,8,this.length),v(this,t,!0,52,8)},I.prototype.readDoubleBE=function(t,e){return e||X(t,8,this.length),v(this,t,!1,52,8)},I.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},I.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},I.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Z(this,t,e,!0),e+4},I.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},I.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},I.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},I.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Z(this,t,e,!0),e+4},I.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeFloatLE=function(t,e,r){return tt(this,t,e,!0,r)},I.prototype.writeFloatBE=function(t,e,r){return tt(this,t,e,!1,r)},I.prototype.writeDoubleLE=function(t,e,r){return et(this,t,e,!0,r)},I.prototype.writeDoubleBE=function(t,e,r){return et(this,t,e,!1,r)},I.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!I.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ot(t){return function(t){var e,r,n,i,o,s;p||d();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new l(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(rt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function st(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ut(t){return null!=t&&(!!t._isBuffer||at(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&at(t.slice(0,0))}(t))}function at(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ht=n(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:I,SlowBuffer:function(t){return+t!=t&&(t=0),I.alloc(+t)},isBuffer:ut})); /*! safe-buffer. MIT License. Feross Aboukhadijeh */ -!function(t,e){var r=ht,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(h,h.exports);var ft=h.exports.Buffer;var ct=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ft.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ft.from(e)),!ft.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,k=0|s[6],P=8191&k,M=k>>>13,x=0|s[7],R=8191&x,N=x>>>13,B=0|s[8],C=8191&B,L=B>>>13,U=0|s[9],D=8191&U,H=U>>>13,j=0|u[0],F=8191&j,q=j>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(c,F))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,F)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,F),i=(i=Math.imul(d,q))+Math.imul(g,F)|0,o=Math.imul(g,q);var vt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,F),i=(i=Math.imul(v,q))+Math.imul(m,F)|0,o=Math.imul(m,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,F),i=(i=Math.imul(b,q))+Math.imul(E,F)|0,o=Math.imul(E,q),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,W)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,F),i=(i=Math.imul(S,q))+Math.imul(I,F)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,W)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,F),i=(i=Math.imul(O,q))+Math.imul(A,F)|0,o=Math.imul(A,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(P,F),i=(i=Math.imul(P,q))+Math.imul(M,F)|0,o=Math.imul(M,q),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,W)|0)+Math.imul(A,K)|0,o=o+Math.imul(A,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(R,F),i=(i=Math.imul(R,q))+Math.imul(N,F)|0,o=Math.imul(N,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,W)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,F),i=(i=Math.imul(C,q))+Math.imul(L,F)|0,o=Math.imul(L,q),n=n+Math.imul(R,K)|0,i=(i=i+Math.imul(R,W)|0)+Math.imul(N,K)|0,o=o+Math.imul(N,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,F),i=(i=Math.imul(D,q))+Math.imul(H,F)|0,o=Math.imul(H,q),n=n+Math.imul(C,K)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(L,K)|0,o=o+Math.imul(L,W)|0,n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,z)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,z)|0,n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,J)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(N,rt)|0,o=o+Math.imul(N,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(L,rt)|0,o=o+Math.imul(L,nt)|0,n=n+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,st)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ct)|0,o=o+Math.imul(A,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(L,ot)|0,o=o+Math.imul(L,st)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ht)|0)+Math.imul(N,at)|0,o=o+Math.imul(N,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(L,at)|0,o=o+Math.imul(L,ht)|0,n=n+Math.imul(R,ct)|0,i=(i=i+Math.imul(R,lt)|0)+Math.imul(N,ct)|0,o=o+Math.imul(N,lt)|0;var xt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(L,ct)|0,o=o+Math.imul(L,lt)|0;var Rt=(h+(n=n+Math.imul(R,dt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(N,dt)|0))<<13)|0;h=((o=o+Math.imul(N,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Nt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(L,dt)|0))<<13)|0;h=((o=o+Math.imul(L,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=kt,a[13]=Pt,a[14]=Mt,a[15]=xt,a[16]=Rt,a[17]=Nt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Rt);var Nt={},Bt="6.5.4",Ct={},Lt=Ut;function Ut(t,e){if(!t)throw new Error(e||"Assertion failed")}Ut.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Dt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Dt),function(t){var e=t,r=Rt.exports,n=Lt,i=Dt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ct);var Ht,jt={exports:{}};function Ft(t){this.rand=t}if(jt.exports=function(t){return Ht||(Ht=new Ft(null)),Ht.generate(t)},jt.exports.Rand=Ft,Ft.prototype.generate=function(t){return this._rand(t)},Ft.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Yt=Xt;function Jt(t,e){this.curve=t,this.type=e,this.precomputed=null}Xt.prototype.point=function(){throw new Error("Not implemented")},Xt.prototype.validate=function(){throw new Error("Not implemented")},Xt.prototype._fixedNafMul=function(t,e){zt(t.precomputed);var r=t._getDoubles(),n=Vt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];zt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Xt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=$t(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Jt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},se.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},se.prototype.pointFromX=function(t,e){(t=new re(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},se.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},se.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ae.prototype.isInfinity=function(){return this.inf},ae.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ae.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ae.prototype.getX=function(){return this.x.fromRed()},ae.prototype.getY=function(){return this.y.fromRed()},ae.prototype.mul=function(t){return t=new re(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ae.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ae.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ae.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ae.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ae.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ne(he,ie.BasePoint),se.prototype.jpoint=function(t,e,r){return new he(this,t,e,r)},he.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},he.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},he.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},he.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},he.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},he.prototype.inspect=function(){return this.isInfinity()?"":""},he.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var fe=Rt.exports,ce=Zt.exports,le=Yt,pe=Ct;function de(t){le.call(this,"mont",t),this.a=new fe(t.a,16).toRed(this.red),this.b=new fe(t.b,16).toRed(this.red),this.i4=new fe(4).toRed(this.red).redInvm(),this.two=new fe(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}ce(de,le);var ge=de;function ye(t,e,r){le.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new fe(e,16),this.z=new fe(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}de.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},ce(ye,le.BasePoint),de.prototype.decodePoint=function(t,e){return this.point(pe.toArray(t,e),1)},de.prototype.point=function(t,e){return new ye(this,t,e)},de.prototype.pointFromJSON=function(t){return ye.fromJSON(this,t)},ye.prototype.precompute=function(){},ye.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ye.fromJSON=function(t,e){return new ye(t,e[0],e[1]||t.one)},ye.prototype.inspect=function(){return this.isInfinity()?"":""},ye.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ye.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ye.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ye.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ye.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ye.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ye.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ve=Ct,me=Rt.exports,we=Zt.exports,be=Yt,Ee=ve.assert;function _e(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,be.call(this,"edwards",t),this.a=new me(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new me(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new me(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ee(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}we(_e,be);var Se=_e;function Ie(t,e,r,n,i){be.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new me(e,16),this.y=new me(r,16),this.z=n?new me(n,16):this.curve.one,this.t=i&&new me(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}_e.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},_e.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},_e.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},_e.prototype.pointFromX=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},_e.prototype.pointFromY=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},_e.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},we(Ie,be.BasePoint),_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},_e.prototype.point=function(t,e,r,n){return new Ie(this,t,e,r,n)},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1],e[2])},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ie.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Ie.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ie.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ie.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Ie.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Ie.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ie.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ie.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ie.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ie.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ie.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ie.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ie.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ie.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ie.prototype.toP=Ie.prototype.normalize,Ie.prototype.mixedAdd=Ie.prototype.add,function(t){var e=t;e.base=Yt,e.short=ue,e.mont=ge,e.edwards=Se}(Gt);var Te={},Oe={},Ae={},ke=Lt,Pe=Zt.exports;function Me(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Re(t){return 1===t.length?"0"+t:t}function Ne(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ae.inherits=Pe,Ae.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Me(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ae.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ae.rotr32=function(t,e){return t>>>e|t<<32-e},Ae.rotl32=function(t,e){return t<>>32-e},Ae.sum32=function(t,e){return t+e>>>0},Ae.sum32_3=function(t,e,r){return t+e+r>>>0},Ae.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ae.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ae.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ae.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ae.sum64_lo=function(t,e,r,n){return e+n>>>0},Ae.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ae.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ae.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ae.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ae.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ae.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ae.shr64_hi=function(t,e,r){return t>>>r},Ae.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Be={},Ce=Ae,Le=Lt;function Ue(){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}Be.BlockHash=Ue,Ue.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},He.g1_256=function(t){return je(t,17)^je(t,19)^t>>>10};var Ke=Ae,We=Be,Ve=He,$e=Ke.rotl32,ze=Ke.sum32,Xe=Ke.sum32_5,Ye=Ve.ft_1,Je=We.BlockHash,Ze=[1518500249,1859775393,2400959708,3395469782];function Qe(){if(!(this instanceof Qe))return new Qe;Je.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ke.inherits(Qe,Je);var tr=Qe;Qe.blockSize=512,Qe.outSize=160,Qe.hmacStrength=80,Qe.padLength=64,Qe.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),bn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var An=On;On.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},On.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=In.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Rn=Rt.exports,Nn=Ct,Bn=Nn.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Bn(t.r&&t.s,"Signature without r or s"),this.r=new Rn(t.r,16),this.s=new Rn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Ln=Cn;function Un(){this.place=0}function Dn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function Hn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Nn.toArray(t,e);var r=new Un;if(48!==t[r.place++])return!1;var n=Dn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Dn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Dn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Rn(o),this.s=new Rn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=Hn(e),r=Hn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];jn(n,e.length),(n=n.concat(e)).push(2),jn(n,r.length);var i=n.concat(r),o=[48];return jn(o,i.length),o=o.concat(i),Nn.encode(o,t)};var Fn=Rt.exports,qn=An,Gn=Ct,Kn=Te,Wn=jt.exports,Vn=Gn.assert,$n=xn,zn=Ln;function Xn(t){if(!(this instanceof Xn))return new Xn(t);"string"==typeof t&&(Vn(Object.prototype.hasOwnProperty.call(Kn,t),"Unknown curve "+t),t=Kn[t]),t instanceof Kn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Yn=Xn;Xn.prototype.keyPair=function(t){return new $n(this,t)},Xn.prototype.keyFromPrivate=function(t,e){return $n.fromPrivate(this,t,e)},Xn.prototype.keyFromPublic=function(t,e){return $n.fromPublic(this,t,e)},Xn.prototype.genKeyPair=function(t){t||(t={});for(var e=new qn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Wn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Fn(2));;){var i=new Fn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Xn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Xn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Fn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new qn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Fn(1)),h=0;;h++){var f=n.k?n.k(h):new Fn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new zn({r:p,s:d,recoveryParam:g})}}}}}},Xn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Fn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new zn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Xn.prototype.recoverPubKey=function(t,e,r,n){Vn((3&r)===r,"The recovery param is more than two bits"),e=new zn(e,n);var i=this.n,o=new Fn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Xn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new zn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Jn=Ct,Zn=Jn.assert,Qn=Jn.parseBytes,ti=Jn.cachedProperty;function ei(t,e){this.eddsa=t,this._secret=Qn(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=Qn(e.pub)}ei.fromPublic=function(t,e){return e instanceof ei?e:new ei(t,{pub:e})},ei.fromSecret=function(t,e){return e instanceof ei?e:new ei(t,{secret:e})},ei.prototype.secret=function(){return this._secret},ti(ei,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ti(ei,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ti(ei,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ti(ei,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ti(ei,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ti(ei,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ei.prototype.sign=function(t){return Zn(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ei.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ei.prototype.getSecret=function(t){return Zn(this._secret,"KeyPair is public only"),Jn.encode(this.secret(),t)},ei.prototype.getPublic=function(t){return Jn.encode(this.pubBytes(),t)};var ri=ei,ni=Rt.exports,ii=Ct,oi=ii.assert,si=ii.cachedProperty,ui=ii.parseBytes;function ai(t,e){this.eddsa=t,"object"!=typeof e&&(e=ui(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),oi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ni&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}si(ai,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),si(ai,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),si(ai,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),si(ai,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),ai.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},ai.prototype.toHex=function(){return ii.encode(this.toBytes(),"hex").toUpperCase()};var hi=ai,fi=Oe,ci=Te,li=Ct,pi=li.assert,di=li.parseBytes,gi=ri,yi=hi;function vi(t){if(pi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof vi))return new vi(t);t=ci[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=fi.sha512}var mi=vi;vi.prototype.sign=function(t,e){t=di(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},vi.prototype.verify=function(t,e,r){t=di(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},vi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Ki(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Oi)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function Hi(t){return 4!==t[0]}function ji(t){return!!Li(t)&&(t.compare(Oi)>0&&t.compare(Ai)<0)}function Fi(t,e){return void 0===t&&void 0!==e?Hi(e):void 0===t||t}function qi(t){return new Si(t)}function Gi(t){return t.toArrayLike(Buffer,"be",32)}function Ki(t){return Ii.curve.decodePoint(t)}function Wi(t,e){return Buffer.from(t._encode(e))}function Vi(t,e,r){if(!Li(t))throw new TypeError(Ci);if(!ji(e))throw new TypeError(Ri);if(void 0!==r&&!Li(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=qi(e),i=qi(t);let o,s;Ti(t,e,(function(t){const e=qi(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Pi),0!==o.isZero()&&(s=e.invm(Pi).mul(i.add(n.mul(o))).umod(Pi),0!==s.isZero()))}),ji,r),s.cmp(Mi)>0&&(s=Pi.sub(s));const u=Buffer.allocUnsafe(64);return Gi(o).copy(u,0),Gi(s).copy(u,32),u}var $i={isPoint:Di,isPointCompressed:function(t){return!!Di(t)&&Hi(t)},isPrivate:ji,pointAdd:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Di(e))throw new TypeError(Ni);const n=Ki(t),i=Ki(e),o=n.add(i);return o.isInfinity()?null:Wi(o,Fi(r,t))},pointAddScalar:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Ui(e))throw new TypeError(Bi);const n=Fi(r,t),i=Ki(t);if(0===e.compare(Oi))return Wi(i,n);const o=qi(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:Wi(u,n)},pointCompress:function(t,e){if(!Di(t))throw new TypeError(Ni);const r=Ki(t);if(r.isInfinity())throw new TypeError(Ni);return Wi(r,Fi(e,t))},pointFromScalar:function(t,e){if(!ji(t))throw new TypeError(Ri);const r=qi(t),n=xi.mul(r);return n.isInfinity()?null:Wi(n,Fi(e))},pointMultiply:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Ui(e))throw new TypeError(Bi);const n=Fi(r,t),i=Ki(t),o=qi(e),s=i.mul(o);return s.isInfinity()?null:Wi(s,n)},privateAdd:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Ui(e))throw new TypeError(Bi);const r=qi(t),n=qi(e),i=Gi(r.add(n).umod(Pi));return ji(i)?i:null},privateSub:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Ui(e))throw new TypeError(Bi);const r=qi(t),n=qi(e),i=Gi(r.sub(n).umod(Pi));return ji(i)?i:null},sign:function(t,e){return Vi(t,e)},signWithEntropy:function(t,e,r){return Vi(t,e,r)},verify:function(t,e,r,n){if(!Li(t))throw new TypeError(Ci);if(!Di(e))throw new TypeError(Ni);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Ai)<0&&r.compare(Ai)<0}(r))throw new TypeError("Expected Signature");const i=Ki(e),o=qi(r.slice(0,32)),s=qi(r.slice(32,64));if(n&&s.cmp(Mi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=qi(t),a=s.invm(Pi),h=u.mul(a).umod(Pi),f=o.mul(a).umod(Pi),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Pi).eq(o)}};try{xt.exports=require("./native")}catch(t){xt.exports=$i}var zi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Xi in zi.Null=zi.Nil,zi)zi[Xi].toJSON=function(t){return t}.bind(null,Xi);var Yi=zi,Ji=Yi;function Zi(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Qi(t){return Ji.Nil(t)?"":Zi(t.constructor)}function to(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function eo(t){return Ji.Function(t)?t.toJSON?t.toJSON():Zi(t):Ji.Array(t)?"Array":t&&Ji.Object(t)?"Object":void 0!==t?t:""}function ro(t,e,r){var n=function(t){return Ji.Function(t)?"":Ji.String(t)?JSON.stringify(t):t&&Ji.Object(t)?"":t}(e);return"Expected "+eo(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function no(t,e,r){r=r||Qi(e),this.message=ro(t,e,r),to(this,no),this.__type=t,this.__value=e,this.__valueTypeName=r}function io(t,e,r,n,i){t?(i=i||Qi(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ro('property "'+eo(r)+o+eo(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',to(this,no),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}no.prototype=Object.create(Error.prototype),no.prototype.constructor=no,io.prototype=Object.create(Error.prototype),io.prototype.constructor=no;var oo={TfTypeError:no,TfPropertyTypeError:io,tfCustomError:function(t,e){return new no(t,{},e)},tfSubError:function(t,e,r){return t instanceof io?(e=e+"."+t.__property,t=new io(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof no&&(t=new io(t.__type,e,r,t.__value,t.__valueTypeName)),to(t),t},tfJSON:eo,getValueTypeName:Qi},so=Yi,uo=oo;function ao(t){return Buffer.isBuffer(t)}function ho(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function fo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw uo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var co=fo.bind(null,so.Array),lo=fo.bind(null,ao),po=fo.bind(null,ho),go=fo.bind(null,so.String);var yo=Math.pow(2,53)-1;var vo={ArrayN:co,Buffer:ao,BufferN:lo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:ho,HexN:po,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-yo&&t<=yo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=yo&&Math.floor(t)===t}};for(var mo in vo)vo[mo].toJSON=function(t){return t}.bind(null,mo);var wo=vo,bo=Yi,Eo=oo.tfJSON,_o=oo.TfTypeError,So=oo.TfPropertyTypeError,Io=oo.tfSubError,To=oo.getValueTypeName,Oo={arrayOf:function(t,e){function r(r,n){return!!bo.Array(r)&&(!bo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw Io(t,r)}}))))))}return t=Ao(t),e=e||{},r.toJSON=function(){var r="["+Eo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return bo.Nil(r)||e(r,n,t)}return e=Ao(e),r.toJSON=function(){return"?"+Eo(e)},r},map:function(t,e){function r(r,n){if(!bo.Object(r))return!1;if(bo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw Io(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw Io(t,i)}}return!0}return t=Ao(t),e&&(e=Ao(e)),r.toJSON=e?function(){return"{"+Eo(e)+": "+Eo(t)+"}"}:function(){return"{"+Eo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ao(t[r]);function n(t,r){if(!bo.Object(t))return!1;if(bo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw Io(t,n)}if(r)for(n in t)if(!e[n])throw new So(void 0,n);return!0}return n.toJSON=function(){return Eo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join(" & ")},e},quacksLike:function(t){function e(e){return t===To(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return!bo.Nil(e)&&(!bo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw Io(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Eo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ao(t){if(bo.String(t))return"?"===t[0]?Oo.maybe(t.slice(1)):bo[t]||Oo.quacksLike(t);if(t&&bo.Object(t)){if(bo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Oo.arrayOf(t[0])}return Oo.object(t)}return bo.Function(t)?t:Oo.value(t)}function ko(t,e,r,n){if(bo.Function(t)){if(t(e,r))return!0;throw new _o(n||t,e)}return ko(Ao(t),e,r)}for(var Po in Oo.oneOf=Oo.anyOf,bo)ko[Po]=bo[Po];for(Po in Oo)ko[Po]=Oo[Po];var Mo=wo;for(Po in Mo)ko[Po]=Mo[Po];ko.compile=Ao,ko.TfTypeError=_o,ko.TfPropertyTypeError=So;var xo=ko,Ro=vt;function No(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Bo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return No(Ro.decode(t),e)},decodeRaw:No,encode:function(t,e,r){return"number"==typeof t?Ro.encode(Bo(t,e,r)):Ro.encode(Bo(t.version,t.privateKey,t.compressed))},encodeRaw:Bo};Object.defineProperty(Ot,"__esModule",{value:!0});const Lo=At,Uo=vt,Do=xt.exports,Ho=xo,jo=Co,Fo=Ho.BufferN(32),qo=Ho.compile({wif:Ho.UInt8,bip32:{public:Ho.UInt32,private:Ho.UInt32}}),Go={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Ko=2147483648,Wo=Math.pow(2,31)-1;function Vo(t){return Ho.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function $o(t){return Ho.UInt32(t)&&t<=Wo}class zo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,Ho(qo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Do.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Lo.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Jo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Uo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return jo.encode(this.network.wif,this.privateKey,!0)}derive(t){Ho(Ho.UInt32,t);const e=t>=Ko,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Lo.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Do.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Do.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Jo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Do.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Yo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return Ho($o,t),this.derive(t+Ko)}derivePath(t){Ho(Vo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Do.sign(t,this.privateKey);{let e=Do.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Do.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Do.verify(t,this.publicKey,e)}}function Xo(t,e,r){return Yo(t,e,r)}function Yo(t,e,r,n,i,o){if(Ho({privateKey:Fo,chainCode:Fo},{privateKey:t,chainCode:e}),r=r||Go,!Do.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new zo(t,void 0,e,r,n,i,o)}function Jo(t,e,r,n,i,o){if(Ho({publicKey:Ho.BufferN(33),chainCode:Fo},{publicKey:t,chainCode:e}),r=r||Go,!Do.isPoint(t))throw new TypeError("Point is not on the curve");return new zo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Uo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Go;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Yo(r.slice(46,78),u,e,i,s,o)}else{a=Jo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Xo,Ot.fromPublicKey=function(t,e,r){return Jo(t,e,r)},Ot.fromSeed=function(t,e){if(Ho(Ho.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Go;const r=Lo.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Xo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var Zo=Ot;Tt.fromSeed=Zo.fromSeed,Tt.fromBase58=Zo.fromBase58,Tt.fromPublicKey=Zo.fromPublicKey,Tt.fromPrivateKey=Zo.fromPrivateKey;var Qo={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ts.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ts.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var es={},rs={},ns={},is={};Object.defineProperty(is,"__esModule",{value:!0}),is.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0});const us=xo,as=Math.pow(2,31)-1;function hs(t){return us.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ss.UInt31=function(t){return us.UInt32(t)&&t<=as},ss.BIP32Path=hs,hs.toJSON=()=>"BIP32 derivation path",ss.Signer=function(t){return(us.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ss.Satoshi=function(t){return us.UInt53(t)&&t<=21e14},ss.ECPoint=us.quacksLike("Point"),ss.Network=us.compile({messagePrefix:us.oneOf(us.Buffer,us.String),bip32:{public:us.UInt32,private:us.UInt32},pubKeyHash:us.UInt8,scriptHash:us.UInt8,wif:us.UInt8}),ss.Buffer256bit=us.BufferN(32),ss.Hash160bit=us.BufferN(20),ss.Hash256bit=us.BufferN(32),ss.Number=us.Number,ss.Array=us.Array,ss.Boolean=us.Boolean,ss.String=us.String,ss.Buffer=us.Buffer,ss.Hex=us.Hex,ss.maybe=us.maybe,ss.tuple=us.tuple,ss.UInt8=us.UInt8,ss.UInt32=us.UInt32,ss.Function=us.Function,ss.BufferN=us.BufferN,ss.Null=us.Null,ss.oneOf=us.oneOf;var fs=h.exports.Buffer;var cs={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=fs.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(os,"__esModule",{value:!0});const ls=ss,ps=cs,ds=xo,gs=Buffer.alloc(1,0);function ys(t){let e=0;for(;0===t[e];)++e;return e===t.length?gs:128&(t=t.slice(e))[0]?Buffer.concat([gs,t],1+t.length):t}function vs(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}os.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=ps.decode(t.slice(0,-1)),i=vs(n.r),o=vs(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},os.encode=function(t,e){ds({signature:ls.BufferN(64),hashType:ls.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=ys(t.slice(0,32)),o=ys(t.slice(32,64));return Buffer.concat([ps.encode(i,o),n])};var ms={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ws=ms;function bs(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ws.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ws.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},_s=ms,Ss={};for(var Is in _s){Ss[_s[Is]]=Is}var Ts=Ss;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=is,r=os,n=ss,i=cs,o=xt.exports,s=Es,u=xo;t.OPS=ms;const a=Ts,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(ns);var Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Os.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(rs,"__esModule",{value:!0});const As=ts,ks=ns,Ps=Os,Ms=xo,xs=ks.OPS;rs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ms({network:Ms.maybe(Ms.Object),output:Ms.maybe(Ms.Buffer),data:Ms.maybe(Ms.arrayOf(Ms.Buffer))},t);const r={name:"embed",network:t.network||As.bitcoin};if(Ps.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Ps.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ms.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});const Ns=ts,Bs=ns,Cs=Os,Ls=Bs.OPS,Us=xo,Ds=xt.exports,Hs=Ls.OP_RESERVED;function js(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Rs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Bs.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ls.OP_0)}e=Object.assign({validate:!0},e||{}),Us({network:Us.maybe(Us.Object),m:Us.maybe(Us.Number),n:Us.maybe(Us.Number),output:Us.maybe(Us.Buffer),pubkeys:Us.maybe(Us.arrayOf(Ds.isPoint)),signatures:Us.maybe(Us.arrayOf(r)),input:Us.maybe(Us.Buffer)},t);const n={network:t.network||Ns.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Bs.decompile(t),n.m=i[0]-Hs,n.n=i[i.length-2]-Hs,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Bs.compile([].concat(Hs+t.m,t.pubkeys,Hs+n.n,Ls.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Bs.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Bs.compile([Ls.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Us.Number(i[0]))throw new TypeError("Output is invalid");if(!Us.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ls.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ds.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!js(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ls.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!js(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Fs={};Object.defineProperty(Fs,"__esModule",{value:!0});const qs=ts,Gs=ns,Ks=Os,Ws=xo,Vs=Gs.OPS,$s=xt.exports;Fs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ws({network:Ws.maybe(Ws.Object),output:Ws.maybe(Ws.Buffer),pubkey:Ws.maybe($s.isPoint),signature:Ws.maybe(Gs.isCanonicalScriptSignature),input:Ws.maybe(Ws.Buffer)},t);const r=Ks.value((()=>Gs.decompile(t.input))),n={name:"p2pk",network:t.network||qs.bitcoin};if(Ks.prop(n,"output",(()=>{if(t.pubkey)return Gs.compile([t.pubkey,Vs.OP_CHECKSIG])})),Ks.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Ks.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Ks.prop(n,"input",(()=>{if(t.signature)return Gs.compile([t.signature])})),Ks.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==Vs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!$s.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Gs.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var zs={},Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=a;function Js(t){try{return Ys("rmd160").update(t).digest()}catch(e){return Ys("ripemd160").update(t).digest()}}function Zs(t){return Ys("sha256").update(t).digest()}Xs.ripemd160=Js,Xs.sha1=function(t){return Ys("sha1").update(t).digest()},Xs.sha256=Zs,Xs.hash160=function(t){return Js(Zs(t))},Xs.hash256=function(t){return Zs(Zs(t))},Object.defineProperty(zs,"__esModule",{value:!0});const Qs=Xs,tu=ts,eu=ns,ru=Os,nu=xo,iu=eu.OPS,ou=xt.exports,su=vt;zs.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),nu({network:nu.maybe(nu.Object),address:nu.maybe(nu.String),hash:nu.maybe(nu.BufferN(20)),output:nu.maybe(nu.BufferN(25)),pubkey:nu.maybe(ou.isPoint),signature:nu.maybe(eu.isCanonicalScriptSignature),input:nu.maybe(nu.Buffer)},t);const r=ru.value((()=>{const e=su.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=ru.value((()=>eu.decompile(t.input))),i=t.network||tu.bitcoin,o={name:"p2pkh",network:i};if(ru.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),su.encode(t)})),ru.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?Qs.hash160(t.pubkey||o.pubkey):void 0)),ru.prop(o,"output",(()=>{if(o.hash)return eu.compile([iu.OP_DUP,iu.OP_HASH160,o.hash,iu.OP_EQUALVERIFY,iu.OP_CHECKSIG])})),ru.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),ru.prop(o,"signature",(()=>{if(t.input)return n()[0]})),ru.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return eu.compile([t.signature,t.pubkey])})),ru.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==iu.OP_DUP||t.output[1]!==iu.OP_HASH160||20!==t.output[2]||t.output[23]!==iu.OP_EQUALVERIFY||t.output[24]!==iu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=Qs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!eu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ou.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=Qs.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var uu={};Object.defineProperty(uu,"__esModule",{value:!0});const au=Xs,hu=ts,fu=ns,cu=Os,lu=xo,pu=fu.OPS,du=vt;uu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),lu({network:lu.maybe(lu.Object),address:lu.maybe(lu.String),hash:lu.maybe(lu.BufferN(20)),output:lu.maybe(lu.BufferN(23)),redeem:lu.maybe({network:lu.maybe(lu.Object),output:lu.maybe(lu.Buffer),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))}),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||hu.bitcoin);const n={network:r},i=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=cu.value((()=>fu.decompile(t.input))),s=cu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:fu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(cu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),du.encode(t)})),cu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?au.hash160(n.redeem.output):void 0)),cu.prop(n,"output",(()=>{if(n.hash)return fu.compile([pu.OP_HASH160,n.hash,pu.OP_EQUAL])})),cu.prop(n,"redeem",(()=>{if(t.input)return s()})),cu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return fu.compile([].concat(fu.decompile(t.redeem.input),t.redeem.output))})),cu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),cu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==pu.OP_HASH160||20!==t.output[1]||t.output[22]!==pu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=fu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=au.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=fu.decompile(t.input);if(!fu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var gu={},yu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vu={},mu=0;mu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Eu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=bu(e)^n>>5}for(e=bu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Eu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Su(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Eu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=bu(n)^s,i+=yu.charAt(s)}for(o=0;o<6;++o)n=bu(n);for(n^=1,o=0;o<6;++o){i+=yu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(gu,"__esModule",{value:!0});const Tu=Xs,Ou=ts,Au=ns,ku=Os,Pu=xo,Mu=Au.OPS,xu=xt.exports,Ru=Iu,Nu=Buffer.alloc(0);gu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Pu({address:Pu.maybe(Pu.String),hash:Pu.maybe(Pu.BufferN(20)),input:Pu.maybe(Pu.BufferN(0)),network:Pu.maybe(Pu.Object),output:Pu.maybe(Pu.BufferN(22)),pubkey:Pu.maybe(xu.isPoint),signature:Pu.maybe(Au.isCanonicalScriptSignature),witness:Pu.maybe(Pu.arrayOf(Pu.Buffer))},t);const r=ku.value((()=>{const e=Ru.decode(t.address),r=e.words.shift(),n=Ru.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Ou.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Ru.toWords(i.hash);return t.unshift(0),Ru.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Tu.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Au.compile([Mu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Nu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Mu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Tu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Au.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Tu.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0});const Cu=Xs,Lu=ts,Uu=ns,Du=Os,Hu=xo,ju=Uu.OPS,Fu=xt.exports,qu=Iu,Gu=Buffer.alloc(0);function Ku(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Fu.isPoint(t))}Bu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Hu({network:Hu.maybe(Hu.Object),address:Hu.maybe(Hu.String),hash:Hu.maybe(Hu.BufferN(32)),output:Hu.maybe(Hu.BufferN(34)),redeem:Hu.maybe({input:Hu.maybe(Hu.Buffer),network:Hu.maybe(Hu.Object),output:Hu.maybe(Hu.Buffer),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))}),input:Hu.maybe(Hu.BufferN(0)),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))},t);const r=Du.value((()=>{const e=qu.decode(t.address),r=e.words.shift(),n=qu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Du.value((()=>Uu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Lu.bitcoin);const o={network:i};if(Du.prop(o,"address",(()=>{if(!o.hash)return;const t=qu.toWords(o.hash);return t.unshift(0),qu.encode(i.bech32,t)})),Du.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Du.prop(o,"output",(()=>{if(o.hash)return Uu.compile([ju.OP_0,o.hash])})),Du.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Gu,witness:t.witness.slice(0,-1)}})),Du.prop(o,"input",(()=>{if(o.witness)return Gu})),Du.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Uu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Gu,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Du.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==ju.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Uu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Uu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Ku)||t.redeem.output&&(Uu.decompile(t.redeem.output)||[]).some(Ku))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Ku)||(Uu.decompile(e)||[]).some(Ku))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(es,"__esModule",{value:!0});const Wu=rs;es.embed=Wu.p2data;const Vu=Rs;es.p2ms=Vu.p2ms;const $u=Fs;es.p2pk=$u.p2pk;const zu=zs;es.p2pkh=zu.p2pkh;const Xu=uu;es.p2sh=Xu.p2sh;const Yu=gu;es.p2wpkh=Yu.p2wpkh;const Ju=Bu;es.p2wsh=Ju.p2wsh,Object.defineProperty(Qo,"__esModule",{value:!0});const Zu=ts,Qu=es,ta=ns,ea=ss,ra=Iu,na=vt,ia=xo;function oa(t){const e=na.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function sa(t){const e=ra.decode(t),r=ra.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}Qo.fromBase58Check=oa,Qo.fromBech32=sa,Qo.toBase58Check=function(t,e){ia(ea.tuple(ea.Hash160bit,ea.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),na.encode(r)},Qo.toBech32=function(t,e,r){const n=ra.toWords(t);return n.unshift(e),ra.encode(r,n)},Qo.fromOutputScript=function(t,e){e=e||Zu.bitcoin;try{return Qu.p2pkh({output:t,network:e}).address}catch(t){}try{return Qu.p2sh({output:t,network:e}).address}catch(t){}try{return Qu.p2wpkh({output:t,network:e}).address}catch(t){}try{return Qu.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ta.toASM(t)+" has no matching Address")},Qo.toOutputScript=function(t,e){let r,n;e=e||Zu.bitcoin;try{r=oa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return Qu.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return Qu.p2sh({hash:r.hash}).output}else{try{n=sa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return Qu.p2wpkh({hash:n.data}).output;if(32===n.data.length)return Qu.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ua={},aa=u.randomBytes;Object.defineProperty(ua,"__esModule",{value:!0});const ha=ts,fa=ss,ca=xt.exports,la=aa,pa=xo,da=Co,ga=pa.maybe(pa.compile({compressed:fa.maybe(fa.Boolean),network:fa.maybe(fa.Network)}));class ya{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ha.bitcoin,void 0!==e&&(this.__Q=ca.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=ca.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return da.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return ca.sign(t,this.__D);{let e=ca.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=ca.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return ca.verify(t,this.publicKey,e)}}function va(t,e){if(pa(fa.Buffer256bit,t),!ca.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return pa(ga,e),new ya(t,void 0,e)}ua.fromPrivateKey=va,ua.fromPublicKey=function(t,e){return pa(ca.isPoint,t),pa(ga,e),new ya(void 0,t,e)},ua.fromWIF=function(t,e){const r=da.decode(t),n=r.version;if(fa.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ha.bitcoin,n!==e.wif)throw new Error("Invalid network version");return va(r.privateKey,{compressed:r.compressed,network:e})},ua.makeRandom=function(t){pa(ga,t),void 0===t&&(t={});const e=t.rng||la;let r;do{r=e(32),pa(fa.Buffer256bit,r)}while(!ca.isPrivate(r));return va(r,t)};var ma={},wa={},ba=h.exports.Buffer;function Ea(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function _a(t){return Ea(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Sa={encode:function t(e,r,n){if(Ea(e),r||(r=ba.allocUnsafe(_a(e))),!ba.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!ba.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ea(o),o},encodingLength:_a};Object.defineProperty(wa,"__esModule",{value:!0});const Ia=ss,Ta=xo,Oa=Sa;function Aa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Aa(n+r,9007199254740991),n+r}function Pa(t,e,r){return Aa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}wa.readUInt64LE=ka,wa.writeUInt64LE=Pa,wa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};wa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ta(Ia.tuple(Ia.Buffer,Ia.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Oa.decode(this.buffer,this.offset);return this.offset+=Oa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Ua.encodingLength(this.ins.length)+Ua.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Da(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Da(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Ua.encodingLength(e)+t.reduce(((t,e)=>t+Da(e)),0)}(e.witness)),0):0)}clone(){const t=new Wa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(La(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return qa;const n=Na.compile(Na.decompile(e).filter((t=>t!==Ba.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Wa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Wa.SIGHASH_SINGLE){if(t>=this.outs.length)return qa;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Wa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=Ha})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ra.hash256(o)}hashForWitnessV0(t,e,r,n){La(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=Fa,u=Fa,a=Fa;if(n&Wa.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ra.hash256(o)),n&Wa.SIGHASH_ANYONECANPAY||(31&n)===Wa.SIGHASH_SINGLE||(31&n)===Wa.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ra.hash256(o)),(31&n)!==Wa.SIGHASH_SINGLE&&(31&n)!==Wa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Da(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ra.hash256(o)}else if((31&n)===Wa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Wa.DEFAULT_SEQUENCE=4294967295,Wa.SIGHASH_ALL=1,Wa.SIGHASH_NONE=2,Wa.SIGHASH_SINGLE=3,Wa.SIGHASH_ANYONECANPAY=128,Wa.ADVANCED_TRANSACTION_MARKER=0,Wa.ADVANCED_TRANSACTION_FLAG=1,Ma.Transaction=Wa;Object.defineProperty(ma,"__esModule",{value:!0});const Va=wa,$a=Xs,za=Ma,Xa=ss,Ya=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=za.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Ja([{getHash:Xa.Function}],t),0===t.length)throw Qa;if(e&&!rh(t))throw th;const r=t.map((t=>t.getHash(e))),n=Ya(r,$a.hash256);return e?$a.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!rh(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+Za.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return $a.hash256(this.toBuffer(!0))}getId(){return Va.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new Va.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(Za.encode(this.transactions.length,e,r.offset),r.offset+=Za.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=Va.reverseBuffer(this.getHash()),e=eh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw Qa;const t=eh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw Qa;if(!this.hasWitnessCommit())throw th;const t=eh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function rh(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ma.Block=eh;var nh={},ih={},oh={},sh={},uh={},ah={},hh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(hh);var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const ch=hh;fh.decode=function(t){if(t.key[0]!==ch.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},fh.encode=function(t){const e=Buffer.from([ch.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},fh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",fh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},fh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=hh;lh.encode=function(t){return{key:Buffer.from([ph.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=hh;dh.decode=function(t){if(t.key[0]!==gh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},dh.encode=function(t){return{key:Buffer.from([gh.InputTypes.FINAL_SCRIPTSIG]),value:t}},dh.expected="Buffer",dh.check=function(t){return Buffer.isBuffer(t)},dh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var yh={};Object.defineProperty(yh,"__esModule",{value:!0});const vh=hh;yh.decode=function(t){if(t.key[0]!==vh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},yh.encode=function(t){return{key:Buffer.from([vh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},yh.expected="Buffer",yh.check=function(t){return Buffer.isBuffer(t)},yh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=hh;mh.decode=function(t){if(t.key[0]!==wh.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([wh.InputTypes.NON_WITNESS_UTXO]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=hh;bh.decode=function(t){if(t.key[0]!==Eh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},bh.encode=function(t){const e=Buffer.from([Eh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},bh.expected="{ pubkey: Buffer; signature: Buffer; }",bh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},bh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=hh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},_h.encode=function(t){return{key:Buffer.from([Sh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},_h.expected="string",_h.check=function(t){return"string"==typeof t},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=hh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ih.encode=function(t){const e=Buffer.from([Th.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ih.expected="number",Ih.check=function(t){return"number"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Oh={},Ah={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Ph(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Mh(t){return Ph(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Ph(e),r||(r=Buffer.allocUnsafe(Mh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Ph(i),i}},kh.encodingLength=Mh,Object.defineProperty(Ah,"__esModule",{value:!0});const xh=kh;function Rh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Nh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ah.range=t=>[...Array(t).keys()],Ah.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Dh={};Object.defineProperty(Dh,"__esModule",{value:!0}),Dh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var Hh={};Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(ah,"__esModule",{value:!0});const Fh=hh,qh=dh,Gh=yh,Kh=mh,Wh=bh,Vh=_h,$h=Ih,zh=Oh,Xh=Uh,Yh=Dh,Jh=Hh,Zh=jh,Qh={unsignedTx:lh,globalXpub:fh,checkPubkey:Yh.makeChecker([])};ah.globals=Qh;const tf={nonWitnessUtxo:Kh,partialSig:Wh,sighashType:$h,finalScriptSig:qh,finalScriptWitness:Gh,porCommitment:Vh,witnessUtxo:zh,bip32Derivation:Xh.makeConverter(Fh.InputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(Fh.InputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(Fh.InputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([Fh.InputTypes.PARTIAL_SIG,Fh.InputTypes.BIP32_DERIVATION])};ah.inputs=tf;const ef={bip32Derivation:Xh.makeConverter(Fh.OutputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(Fh.OutputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(Fh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([Fh.OutputTypes.BIP32_DERIVATION])};ah.outputs=ef,Object.defineProperty(uh,"__esModule",{value:!0});const rf=ah,nf=Ah,of=kh,sf=hh;function uf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function af(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case sf.GlobalTypes.UNSIGNED_TX:if(uf("global",t.key,sf.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case sf.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(rf.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of nf.range(s)){const e={};for(const n of r[t])switch(rf.inputs.checkPubkey(n),n.key[0]){case sf.InputTypes.NON_WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=rf.inputs.nonWitnessUtxo.decode(n);break;case sf.InputTypes.WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=rf.inputs.witnessUtxo.decode(n);break;case sf.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(rf.inputs.partialSig.decode(n));break;case sf.InputTypes.SIGHASH_TYPE:if(uf("input",n.key,sf.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=rf.inputs.sighashType.decode(n);break;case sf.InputTypes.REDEEM_SCRIPT:if(uf("input",n.key,sf.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=rf.inputs.redeemScript.decode(n);break;case sf.InputTypes.WITNESS_SCRIPT:if(uf("input",n.key,sf.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=rf.inputs.witnessScript.decode(n);break;case sf.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.inputs.bip32Derivation.decode(n));break;case sf.InputTypes.FINAL_SCRIPTSIG:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=rf.inputs.finalScriptSig.decode(n);break;case sf.InputTypes.FINAL_SCRIPTWITNESS:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=rf.inputs.finalScriptWitness.decode(n);break;case sf.InputTypes.POR_COMMITMENT:uf("input",n.key,sf.InputTypes.POR_COMMITMENT),e.porCommitment=rf.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of nf.range(u)){const e={};for(const r of n[t])switch(rf.outputs.checkPubkey(r),r.key[0]){case sf.OutputTypes.REDEEM_SCRIPT:if(uf("output",r.key,sf.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=rf.outputs.redeemScript.decode(r);break;case sf.OutputTypes.WITNESS_SCRIPT:if(uf("output",r.key,sf.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=rf.outputs.witnessScript.decode(r);break;case sf.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}uh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=of.decode(t,r);r+=of.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===sf.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of nf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of nf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return af(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},uh.checkKeyBuffer=uf,uh.psbtFromKeyVals=af;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});const ff=ah,cf=Ah;hf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=df({globalMap:t,inputs:e,outputs:r}),s=cf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(cf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const lf=(t,e)=>t.key.compare(e.key);function pf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(lf)}function df({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:pf(t,ff.globals),inputKeyVals:e.map((t=>pf(t,ff.inputs))),outputKeyVals:r.map((t=>pf(t,ff.outputs)))}}hf.psbtToKeyVals=df,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(uh),e(hf)}(sh),Object.defineProperty(oh,"__esModule",{value:!0});const gf=sh;function yf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function vf(t){return t.globalMap.unsignedTx}function mf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}oh.combine=function(t){const e=t[0],r=gf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=vf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=mf(r.globalKeyVals),s=r.inputKeyVals.map(mf),u=r.outputKeyVals.map(mf);for(const t of n){const e=vf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=gf.psbtToKeyVals(t);mf(n.globalKeyVals).forEach(yf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return gf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var wf={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ah;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(wf),Object.defineProperty(ih,"__esModule",{value:!0});const bf=oh,Ef=sh,_f=hh,Sf=wf;ih.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ef.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ef.psbtToBuffer(this)}updateGlobal(t){return Sf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.updateInput(e,r),this}updateOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Sf.checkHasKey(t,this.globalMap.unknownKeyVals,Sf.getEnumLength(_f.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Sf.checkForInput(this.inputs,t);Sf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=bf.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(nh,"__esModule",{value:!0});const If=ih,Tf=kh,Of=wf,Af=Qo,kf=wa,Pf=Xs,Mf=ua,xf=es,Rf=ns,Nf=Ma,Bf={network:ts.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new If.Psbt(new Uf)){this.data=e,this.opts=Object.assign({},Bf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=If.Psbt.fromBuffer(t,Lf),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{Zf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Af.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Xf(t),this.opts.maximumFeeRate=t}setVersion(t){Xf(t),Yf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Xf(t),Yf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Xf(e),Yf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Yf(this.data.inputs,"addInput"),t.witnessScript&&gc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);Zf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&hc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Yf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Af.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(jf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return fc(this.data.inputs,r,e,!0),r}getFeeRate(){return rc("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return rc("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Of.checkForInput(this.data.inputs,0),mc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=nc){const r=Of.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=cc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Wf(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Rf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Of.checkForInput(this.data.inputs,t),r=dc(lc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Rf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||pc(r)||(n=r,Rf.isCanonicalScriptSignature(n)))return;var n;if(!Rf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=uc(t),r=e[e.length-1];if(pc(r))return;if(!Rf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+vc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=lc(r,e,n),{meaningfulScript:o}=dc(i,r,"input",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Of.checkForInput(this.data.inputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=dc(i,r,"output",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Of.checkForOutput(this.data.outputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Of.checkForInput(this.data.inputs,0);return mc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Rf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?oc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Jf(e.pubkey,h,"verify");const f=Mf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of mc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return sc(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=sc(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Rf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Rf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Df(this.__CACHE),this.data.toBuffer()}toHex(){return Df(this.__CACHE),this.data.toHex()}toBase64(){return Df(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&gc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&hc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}nh.Psbt=Cf;const Lf=t=>new Uf(t);class Uf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Nf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Df(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Hf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Mf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function jf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Ff(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const qf=Ff(xf.p2ms),Gf=Ff(xf.p2pk),Kf=Ff(xf.p2pkh),Wf=Ff(xf.p2wpkh),Vf=Ff(xf.p2wsh),$f=Ff(xf.p2sh);function zf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Xf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Yf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Rf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Rf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Rf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Rf.signature.decode(t.signature),i=[];n&Nf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Nf.Transaction.SIGHASH_ALL:break;case Nf.Transaction.SIGHASH_SINGLE:case Nf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Jf(t,e,r){if(!yc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function Zf(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function Qf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const tc=Qf(xf.p2sh,"Redeem script"),ec=Qf(xf.p2wsh,"Witness script");function rc(t,e,r,n){if(!r.every(jf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),fc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function nc(t,e,r,n,i,o){const s=vc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Hf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return Hf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=ac(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function ic(t,e,r,n,i){const o=Of.checkForInput(t,e),{hash:s,sighashType:u,script:a}=oc(e,o,n,!1,i);return Jf(r,a,"sign"),{hash:s,sighashType:u}}function oc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Nf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Nf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Nf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Nf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Nf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=cc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=dc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Wf(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function sc(t,e,r){const n=Of.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function uc(t){let e=0;function r(){const r=Tf.decode(t,e);return e+=Tf.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=uc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=cc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function cc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||hc(t,e,r),n[r]}function lc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return cc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function pc(t){return 33===t.length&&Rf.isCanonicalPubKey(t)}function dc(t,e,r,n,i){const o=$f(t),s=o&&n&&Vf(n),u=Vf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,tc(e,t,n,r),ec(e,n,i,r),gc(a)):u?(a=i,ec(e,t,i,r),gc(a)):o?(a=n,tc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function gc(t){if(Wf(t)||$f(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function yc(t,e){const r=Pf.hash160(t),n=Rf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function vc(t){return Wf(t)?"witnesspubkeyhash":Kf(t)?"pubkeyhash":qf(t)?"multisig":Gf(t)?"pubkey":"nonstandard"}function mc(t){return[...Array(t).keys()]}var wc={},bc={},Ec={},_c={};Object.defineProperty(_c,"__esModule",{value:!0});const Sc=ns,Ic=ns;function Tc(t){return t===Ic.OPS.OP_0||Sc.isCanonicalScriptSignature(t)}function Oc(t,e){const r=Sc.decompile(t);return!(r.length<2)&&(r[0]===Ic.OPS.OP_0&&(e?r.slice(1).every(Tc):r.slice(1).every(Sc.isCanonicalScriptSignature)))}_c.check=Oc,Oc.toJSON=()=>"multisig input";var Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const kc=ns,Pc=ns,Mc=ss,xc=Pc.OPS.OP_RESERVED;function Rc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Pc.OPS.OP_CHECKMULTISIG)return!1;if(!Mc.Number(r[0]))return!1;if(!Mc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Ac.check=Rc,Rc.toJSON=()=>"multi-sig output",Object.defineProperty(Ec,"__esModule",{value:!0});const Nc=_c;Ec.input=Nc;const Bc=Ac;Ec.output=Bc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Lc=ns,Uc=Lc.OPS;function Dc(t){const e=Lc.compile(t);return e.length>1&&e[0]===Uc.OP_RETURN}Cc.check=Dc,Dc.toJSON=()=>"null data output";const Hc={check:Dc};Cc.output=Hc;var jc={},Fc={};Object.defineProperty(Fc,"__esModule",{value:!0});const qc=ns;function Gc(t){const e=qc.decompile(t);return 1===e.length&&qc.isCanonicalScriptSignature(e[0])}Fc.check=Gc,Gc.toJSON=()=>"pubKey input";var Kc={};Object.defineProperty(Kc,"__esModule",{value:!0});const Wc=ns,Vc=ns;function $c(t){const e=Wc.decompile(t);return 2===e.length&&Wc.isCanonicalPubKey(e[0])&&e[1]===Vc.OPS.OP_CHECKSIG}Kc.check=$c,$c.toJSON=()=>"pubKey output",Object.defineProperty(jc,"__esModule",{value:!0});const zc=Fc;jc.input=zc;const Xc=Kc;jc.output=Xc;var Yc={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});const Zc=ns;function Qc(t){const e=Zc.decompile(t);return 2===e.length&&Zc.isCanonicalScriptSignature(e[0])&&Zc.isCanonicalPubKey(e[1])}Jc.check=Qc,Qc.toJSON=()=>"pubKeyHash input";var tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=ns,rl=ns;function nl(t){const e=el.compile(t);return 25===e.length&&e[0]===rl.OPS.OP_DUP&&e[1]===rl.OPS.OP_HASH160&&20===e[2]&&e[23]===rl.OPS.OP_EQUALVERIFY&&e[24]===rl.OPS.OP_CHECKSIG}tl.check=nl,nl.toJSON=()=>"pubKeyHash output",Object.defineProperty(Yc,"__esModule",{value:!0});const il=Jc;Yc.input=il;const ol=tl;Yc.output=ol;var sl={},ul={},al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=ns,fl=ns;function cl(t){const e=hl.compile(t);return 22===e.length&&e[0]===fl.OPS.OP_0&&20===e[1]}al.check=cl,cl.toJSON=()=>"Witness pubKeyHash output";var ll={};Object.defineProperty(ll,"__esModule",{value:!0});const pl=ns,dl=ns;function gl(t){const e=pl.compile(t);return 34===e.length&&e[0]===dl.OPS.OP_0&&32===e[1]}ll.check=gl,gl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(ul,"__esModule",{value:!0});const yl=ns,vl=Ec,ml=jc,wl=Yc,bl=al,El=ll;function _l(t,e){const r=yl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=yl.decompile(yl.compile(r.slice(0,-1))),o=yl.decompile(n);return!!o&&(!!yl.isPushOnly(i)&&(1===r.length?El.check(o)||bl.check(o):!(!wl.input.check(i)||!wl.output.check(o))||(!(!vl.input.check(i,e)||!vl.output.check(o))||!(!ml.input.check(i)||!ml.output.check(o)))))}ul.check=_l,_l.toJSON=()=>"scriptHash input";var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Il=ns,Tl=ns;function Ol(t){const e=Il.compile(t);return 23===e.length&&e[0]===Tl.OPS.OP_HASH160&&20===e[1]&&e[22]===Tl.OPS.OP_EQUAL}Sl.check=Ol,Ol.toJSON=()=>"scriptHash output",Object.defineProperty(sl,"__esModule",{value:!0});const Al=ul;sl.input=Al;const kl=Sl;sl.output=kl;var Pl={},Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const xl=ns,Rl=ns,Nl=ss,Bl=xo,Cl=Buffer.from("aa21a9ed","hex");function Ll(t){const e=xl.compile(t);return e.length>37&&e[0]===Rl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Ml.check=Ll,Ll.toJSON=()=>"Witness commitment output",Ml.encode=function(t){Bl(Nl.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Rl.OPS.OP_RETURN,e])},Ml.decode=function(t){return Bl(Ll,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Pl,"__esModule",{value:!0});const Ul=Ml;Pl.output=Ul;var Dl={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const jl=ns;function Fl(t){const e=jl.decompile(t);return 2===e.length&&jl.isCanonicalScriptSignature(e[0])&&function(t){return jl.isCanonicalPubKey(t)&&33===t.length}(e[1])}Hl.check=Fl,Fl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Dl,"__esModule",{value:!0});const ql=Hl;Dl.input=ql;const Gl=al;Dl.output=Gl;var Kl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Vl=ns,$l=xo,zl=Ec,Xl=jc,Yl=Yc;function Jl(t,e){if($l($l.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=Vl.decompile(r);if(!n||0===n.length)return!1;const i=Vl.compile(t.slice(0,-1));return!(!Yl.input.check(i)||!Yl.output.check(n))||(!(!zl.input.check(i,e)||!zl.output.check(n))||!(!Xl.input.check(i)||!Xl.output.check(n)))}Wl.check=Jl,Jl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Kl,"__esModule",{value:!0});const Zl=Wl;Kl.input=Zl;const Ql=ll;Kl.output=Ql,Object.defineProperty(bc,"__esModule",{value:!0});const tp=ns,ep=Ec,rp=Cc,np=jc,ip=Yc,op=sl,sp=Pl,up=Dl,ap=Kl,hp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};bc.types=hp,bc.output=function(t){if(up.output.check(t))return hp.P2WPKH;if(ap.output.check(t))return hp.P2WSH;if(ip.output.check(t))return hp.P2PKH;if(op.output.check(t))return hp.P2SH;const e=tp.decompile(t);if(!e)throw new TypeError("Invalid script");return ep.output.check(e)?hp.P2MS:np.output.check(e)?hp.P2PK:sp.output.check(e)?hp.WITNESS_COMMITMENT:rp.output.check(e)?hp.NULLDATA:hp.NONSTANDARD},bc.input=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return ip.input.check(r)?hp.P2PKH:op.input.check(r,e)?hp.P2SH:ep.input.check(r,e)?hp.P2MS:np.input.check(r)?hp.P2PK:hp.NONSTANDARD},bc.witness=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return up.input.check(r)?hp.P2WPKH:ap.input.check(r,e)?hp.P2WSH:hp.NONSTANDARD},Object.defineProperty(wc,"__esModule",{value:!0});const fp=Qo,cp=wa,lp=bc,pp=Xs,dp=ua,gp=ts,yp=es,vp=ns,mp=ns,wp=Ma,bp=ss,Ep=xo,_p=lp.types,Sp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Ip(t,e,r){try{Ep(t,e)}catch(t){throw new Error(r)}}class Tp{constructor(t=gp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new wp.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Tp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==_p.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=dp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=vp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ep(Ep.maybe(Ep.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ep(bp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ep(bp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=cp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof wp.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=fp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=vp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Sp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Ip(Ep.Number,e.vin,"sign must include vin parameter as Number (input index)"),Ip(bp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Ip(Ep.maybe(Ep.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires witnessScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||wp.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Pp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ep(bp.Satoshi,a),l.value=a}if(!Pp(l)){const t=function(t,e,r,n){if(r&&n){const i=yp.p2wsh({redeem:{output:n}}),o=yp.p2wsh({output:r}),s=yp.p2sh({redeem:{output:r}}),u=yp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ap(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===_p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:_p.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:_p.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=yp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=yp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ap(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+vp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===_p.P2WPKH&&(o=yp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:_p.P2SH,prevOutScript:n.output,hasWitness:i.type===_p.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=yp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=yp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ap(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===_p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:_p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===_p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===_p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ap(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+vp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===_p.P2WPKH&&(n=yp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===_p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=yp.p2pkh({pubkey:e}).output;return{prevOutType:_p.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:_p.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Pp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(wp.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Op(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ap(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||lp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===_p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Mp(t)&wp.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===wp.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Mp(t)&wp.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Mp(r);return n===wp.Transaction.SIGHASH_NONE||n===wp.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Op(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=lp.input(t,!0),i=lp.witness(e,!0);n===_p.NONSTANDARD&&(n=void 0),i===_p.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case _p.P2WPKH:{const{output:t,pubkey:r,signature:n}=yp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:_p.P2WPKH,pubkeys:[r],signatures:[n]}}case _p.P2PKH:{const{output:e,pubkey:r,signature:n}=yp.p2pkh({input:t});return{prevOutScript:e,prevOutType:_p.P2PKH,pubkeys:[r],signatures:[n]}}case _p.P2PK:{const{signature:e}=yp.p2pk({input:t});return{prevOutType:_p.P2PK,pubkeys:[void 0],signatures:[e]}}case _p.P2MS:{const{m:e,pubkeys:r,signatures:i}=yp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:_p.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===_p.P2SH){const{output:r,redeem:n}=yp.p2sh({input:t,witness:e}),i=lp.output(n.output),o=Op(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:_p.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===_p.P2WSH){const{output:r,redeem:n}=yp.p2wsh({input:t,witness:e}),i=lp.output(n.output);let o;return o=i===_p.P2WPKH?Op(n.input,n.witness,i):Op(vp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:_p.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:_p.NONSTANDARD,prevOutScript:t}}function Ap(t,e){Ep(bp.Buffer,t);const r=lp.output(t);switch(r){case _p.P2PKH:{if(!e)return{type:r};const n=yp.p2pkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2WPKH:{if(!e)return{type:r};const n=yp.p2wpkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2PK:return{type:r,pubkeys:[yp.p2pk({output:t}).pubkey],signatures:[void 0]};case _p.P2MS:{const e=yp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case _p.P2PKH:if(0===n.length)break;if(0===i.length)break;return yp.p2pkh({pubkey:n[0],signature:i[0]});case _p.P2WPKH:if(0===n.length)break;if(0===i.length)break;return yp.p2wpkh({pubkey:n[0],signature:i[0]});case _p.P2PK:if(0===n.length)break;if(0===i.length)break;return yp.p2pk({signature:i[0]});case _p.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||mp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return yp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case _p.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return yp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case _p.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return yp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Pp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Mp(t){return t.readUInt8(t.length-1)}wc.TransactionBuilder=Tp,Object.defineProperty(It,"__esModule",{value:!0});const xp=Tt;It.bip32=xp;const Rp=Qo;It.address=Rp;const Np=Xs;var Bp=It.crypto=Np;const Cp=ua;It.ECPair=Cp;const Lp=ts;It.networks=Lp;const Up=es;It.payments=Up;const Dp=ns;It.script=Dp;var Hp=ma;It.Block=Hp.Block;var jp=nh;It.Psbt=jp.Psbt;var Fp=ns;It.opcodes=Fp.OPS;var qp=Ma;It.Transaction=qp.Transaction;var Gp=wc;It.TransactionBuilder=Gp.TransactionBuilder;var Kp={exports:{}};var Wp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var Vp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Wp,n=Vp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Kp,Kp.exports);const $p=["includePrerelease","loose","rtl"];var zp=t=>t?"object"!=typeof t?{loose:!0}:$p.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Xp=/^[0-9]+$/,Yp=(t,e)=>{const r=Xp.test(t),n=Xp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tYp(e,t)};const Zp=Vp,{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:td}=Wp,{re:ed,t:rd}=Kp.exports,nd=zp,{compareIdentifiers:id}=Jp;class od{constructor(t,e){if(e=nd(e),t instanceof od){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);Zp("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?ed[rd.LOOSE]:ed[rd.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>td||this.major<0)throw new TypeError("Invalid major version");if(this.minor>td||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>td||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var sd=od;const{MAX_LENGTH:ud}=Wp,{re:ad,t:hd}=Kp.exports,fd=sd,cd=zp;var ld=(t,e)=>{if(e=cd(e),t instanceof fd)return t;if("string"!=typeof t)return null;if(t.length>ud)return null;if(!(e.loose?ad[hd.LOOSE]:ad[hd.FULL]).test(t))return null;try{return new fd(t,e)}catch(t){return null}};const pd=ld;var dd=(t,e)=>{const r=pd(t,e);return r?r.version:null};const gd=ld;var yd=(t,e)=>{const r=gd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const vd=sd;var md=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new vd(t,r).inc(e,n).version}catch(t){return null}};const wd=sd;var bd=(t,e,r)=>new wd(t,r).compare(new wd(e,r));const Ed=bd;var _d=(t,e,r)=>0===Ed(t,e,r);const Sd=ld,Id=_d;var Td=(t,e)=>{if(Id(t,e))return null;{const r=Sd(t),n=Sd(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Od=sd;var Ad=(t,e)=>new Od(t,e).major;const kd=sd;var Pd=(t,e)=>new kd(t,e).minor;const Md=sd;var xd=(t,e)=>new Md(t,e).patch;const Rd=ld;var Nd=(t,e)=>{const r=Rd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Bd=bd;var Cd=(t,e,r)=>Bd(e,t,r);const Ld=bd;var Ud=(t,e)=>Ld(t,e,!0);const Dd=sd;var Hd=(t,e,r)=>{const n=new Dd(t,r),i=new Dd(e,r);return n.compare(i)||n.compareBuild(i)};const jd=Hd;var Fd=(t,e)=>t.sort(((t,r)=>jd(t,r,e)));const qd=Hd;var Gd=(t,e)=>t.sort(((t,r)=>qd(r,t,e)));const Kd=bd;var Wd=(t,e,r)=>Kd(t,e,r)>0;const Vd=bd;var $d=(t,e,r)=>Vd(t,e,r)<0;const zd=bd;var Xd=(t,e,r)=>0!==zd(t,e,r);const Yd=bd;var Jd=(t,e,r)=>Yd(t,e,r)>=0;const Zd=bd;var Qd=(t,e,r)=>Zd(t,e,r)<=0;const tg=_d,eg=Xd,rg=Wd,ng=Jd,ig=$d,og=Qd;var sg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return tg(t,r,n);case"!=":return eg(t,r,n);case">":return rg(t,r,n);case">=":return ng(t,r,n);case"<":return ig(t,r,n);case"<=":return og(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const ug=sd,ag=ld,{re:hg,t:fg}=Kp.exports;var cg=(t,e)=>{if(t instanceof ug)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=hg[fg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),hg[fg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;hg[fg.COERCERTL].lastIndex=-1}else r=t.match(hg[fg.COERCE]);return null===r?null:ag(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},lg=pg;function pg(t){var e=this;if(e instanceof pg||(e=new pg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},pg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},pg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},pg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},pg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new pg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},pg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Mg=(t,e,r)=>{const n=t[Ag].get(e);if(n){const e=n.value;if(xg(t,e)){if(Ng(t,n),!t[_g])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Og].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Sg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Sg]&&r>t[Sg]},Rg=t=>{if(t[bg]>t[wg])for(let e=t[Og].tail;t[bg]>t[wg]&&null!==e;){const r=e.prev;Ng(t,e),e=r}},Ng=(t,e)=>{if(e){const r=e.value;t[Ig]&&t[Ig](r.key,r.value),t[bg]-=r.length,t[Ag].delete(r.key),t[Og].removeNode(e)}};class Bg{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Ng(t,r),t[_g]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Lg=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[wg]=t.max||1/0;const e=t.length||Pg;if(this[Eg]="function"!=typeof e?Pg:e,this[_g]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Sg]=t.maxAge||0,this[Ig]=t.dispose,this[Tg]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[wg]=t||1/0,Rg(this)}get max(){return this[wg]}set allowStale(t){this[_g]=!!t}get allowStale(){return this[_g]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Sg]=t,Rg(this)}get maxAge(){return this[Sg]}set lengthCalculator(t){"function"!=typeof t&&(t=Pg),t!==this[Eg]&&(this[Eg]=t,this[bg]=0,this[Og].forEach((t=>{t.length=this[Eg](t.value,t.key),this[bg]+=t.length}))),Rg(this)}get lengthCalculator(){return this[Eg]}get length(){return this[bg]}get itemCount(){return this[Og].length}rforEach(t,e){e=e||this;for(let r=this[Og].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Og].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Og].toArray().map((t=>t.key))}values(){return this[Og].toArray().map((t=>t.value))}reset(){this[Ig]&&this[Og]&&this[Og].length&&this[Og].forEach((t=>this[Ig](t.key,t.value))),this[Ag]=new Map,this[Og]=new mg,this[bg]=0}dump(){return this[Og].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Og]}set(t,e,r){if((r=r||this[Sg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Eg](e,t);if(this[Ag].has(t)){if(i>this[wg])return Ng(this,this[Ag].get(t)),!1;const o=this[Ag].get(t).value;return this[Ig]&&(this[Tg]||this[Ig](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[bg]+=i-o.length,o.length=i,this.get(t),Rg(this),!0}const o=new Bg(t,e,i,n,r);return o.length>this[wg]?(this[Ig]&&this[Ig](t,e),!1):(this[bg]+=o.length,this[Og].unshift(o),this[Ag].set(t,this[Og].head),Rg(this),!0)}has(t){if(!this[Ag].has(t))return!1;const e=this[Ag].get(t).value;return!xg(this,e)}get(t){return Mg(this,t,!0)}peek(t){return Mg(this,t,!1)}pop(){const t=this[Og].tail;return t?(Ng(this,t),t.value):null}del(t){Ng(this,this[Ag].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ag].forEach(((t,e)=>Mg(this,e,!1)))}};class Ug{constructor(t,e){if(e=jg(e),t instanceof Ug)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Ug(t.raw,e);if(t instanceof Fg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Xg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Yg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=Hg.get(e);if(r)return r;const n=this.options.loose,i=n?Kg[Wg.HYPHENRANGELOOSE]:Kg[Wg.HYPHENRANGE];t=t.replace(i,ay(this.options.includePrerelease)),qg("hyphen replace",t),t=t.replace(Kg[Wg.COMPARATORTRIM],Vg),qg("comparator trim",t,Kg[Wg.COMPARATORTRIM]),t=(t=(t=t.replace(Kg[Wg.TILDETRIM],$g)).replace(Kg[Wg.CARETTRIM],zg)).split(/\s+/).join(" ");const o=n?Kg[Wg.COMPARATORLOOSE]:Kg[Wg.COMPARATOR],s=t.split(" ").map((t=>Zg(t,this.options))).join(" ").split(/\s+/).map((t=>uy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Fg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Xg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return Hg.set(e,a),a}intersects(t,e){if(!(t instanceof Ug))throw new TypeError("a Range is required");return this.set.some((r=>Jg(r,e)&&t.set.some((t=>Jg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Gg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Yg=t=>""===t.value,Jg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},Zg=(t,e)=>(qg("comp",t,e),t=ry(t,e),qg("caret",t),t=ty(t,e),qg("tildes",t),t=iy(t,e),qg("xrange",t),t=sy(t,e),qg("stars",t),t),Qg=t=>!t||"x"===t.toLowerCase()||"*"===t,ty=(t,e)=>t.trim().split(/\s+/).map((t=>ey(t,e))).join(" "),ey=(t,e)=>{const r=e.loose?Kg[Wg.TILDELOOSE]:Kg[Wg.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return qg("tilde",t,e,r,n,i,o),Qg(r)?s="":Qg(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Qg(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(qg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,qg("tilde return",s),s}))},ry=(t,e)=>t.trim().split(/\s+/).map((t=>ny(t,e))).join(" "),ny=(t,e)=>{qg("caret",t,e);const r=e.loose?Kg[Wg.CARETLOOSE]:Kg[Wg.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return qg("caret",t,e,r,i,o,s),Qg(r)?u="":Qg(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Qg(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(qg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(qg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),qg("caret return",u),u}))},iy=(t,e)=>(qg("replaceXRanges",t,e),t.split(/\s+/).map((t=>oy(t,e))).join(" ")),oy=(t,e)=>{t=t.trim();const r=e.loose?Kg[Wg.XRANGELOOSE]:Kg[Wg.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{qg("xRange",t,r,n,i,o,s,u);const a=Qg(i),h=a||Qg(o),f=h||Qg(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),qg("xRange return",r),r}))},sy=(t,e)=>(qg("replaceStars",t,e),t.trim().replace(Kg[Wg.STAR],"")),uy=(t,e)=>(qg("replaceGTE0",t,e),t.trim().replace(Kg[e.includePrerelease?Wg.GTE0PRE:Wg.GTE0],"")),ay=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=Qg(n)?"":Qg(i)?`>=${n}.0.0${t?"-0":""}`:Qg(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Qg(h)?"":Qg(f)?`<${+h+1}.0.0-0`:Qg(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),hy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},fy=Symbol("SemVer ANY");class cy{static get ANY(){return fy}constructor(t,e){if(e=py(e),t instanceof cy){if(t.loose===!!e.loose)return t;t=t.value}vy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===fy?this.value="":this.value=this.operator+this.semver.version,vy("comp",this)}parse(t){const e=this.options.loose?dy[gy.COMPARATORLOOSE]:dy[gy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new my(r[2],this.options.loose):this.semver=fy}toString(){return this.value}test(t){if(vy("Comparator.test",t,this.options.loose),this.semver===fy||t===fy)return!0;if("string"==typeof t)try{t=new my(t,this.options)}catch(t){return!1}return yy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof cy))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new wy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new wy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=yy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=yy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var ly=cy;const py=zp,{re:dy,t:gy}=Kp.exports,yy=sg,vy=Vp,my=sd,wy=Dg,by=Dg;var Ey=(t,e,r)=>{try{e=new by(e,r)}catch(t){return!1}return e.test(t)};const _y=Dg;var Sy=(t,e)=>new _y(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Iy=sd,Ty=Dg;var Oy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ty(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Iy(n,r)))})),n};const Ay=sd,ky=Dg;var Py=(t,e,r)=>{let n=null,i=null,o=null;try{o=new ky(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Ay(n,r)))})),n};const My=sd,xy=Dg,Ry=Wd;var Ny=(t,e)=>{t=new xy(t,e);let r=new My("0.0.0");if(t.test(r))return r;if(r=new My("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new My(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Ry(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Ry(r,i)||(r=i)}return r&&t.test(r)?r:null};const By=Dg;var Cy=(t,e)=>{try{return new By(t,e).range||"*"}catch(t){return null}};const Ly=sd,Uy=ly,{ANY:Dy}=Uy,Hy=Dg,jy=Ey,Fy=Wd,qy=$d,Gy=Qd,Ky=Jd;var Wy=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Ly(t,n),e=new Hy(e,n),r){case">":i=Fy,o=Gy,s=qy,u=">",a=">=";break;case"<":i=qy,o=Ky,s=Fy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jy(t,e,n))return!1;for(let r=0;r{t.semver===Dy&&(t=new Uy(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const Vy=Wy;var $y=(t,e,r)=>Vy(t,e,">",r);const zy=Wy;var Xy=(t,e,r)=>zy(t,e,"<",r);const Yy=Dg;var Jy=(t,e,r)=>(t=new Yy(t,r),e=new Yy(e,r),t.intersects(e));const Zy=Ey,Qy=bd;const tv=Dg,ev=ly,{ANY:rv}=ev,nv=Ey,iv=bd,ov=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===rv){if(1===e.length&&e[0].semver===rv)return!0;t=r.includePrerelease?[new ev(">=0.0.0-0")]:[new ev(">=0.0.0")]}if(1===e.length&&e[0].semver===rv){if(r.includePrerelease)return!0;e=[new ev(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=sv(i,e,r):"<"===e.operator||"<="===e.operator?o=uv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=iv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!nv(t,String(i),r))return null;if(o&&!nv(t,String(o),r))return null;for(const n of e)if(!nv(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=sv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!nv(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=uv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!nv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},sv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},uv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var av=(t,e,r={})=>{if(t===e)return!0;t=new tv(t,r),e=new tv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=ov(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const hv=Kp.exports;var fv={re:hv.re,src:hv.src,tokens:hv.t,SEMVER_SPEC_VERSION:Wp.SEMVER_SPEC_VERSION,SemVer:sd,compareIdentifiers:Jp.compareIdentifiers,rcompareIdentifiers:Jp.rcompareIdentifiers,parse:ld,valid:dd,clean:yd,inc:md,diff:Td,major:Ad,minor:Pd,patch:xd,prerelease:Nd,compare:bd,rcompare:Cd,compareLoose:Ud,compareBuild:Hd,sort:Fd,rsort:Gd,gt:Wd,lt:$d,eq:_d,neq:Xd,gte:Jd,lte:Qd,cmp:sg,coerce:cg,Comparator:ly,Range:Dg,satisfies:Ey,toComparators:Sy,maxSatisfying:Oy,minSatisfying:Py,minVersion:Ny,validRange:Cy,outside:Wy,gtr:$y,ltr:Xy,intersects:Jy,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Qy(t,e,r)));for(const t of s){Zy(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Tv(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ov(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Av(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}yv.prototype=Object.create(null),vv.EventEmitter=vv,vv.usingDomains=!1,vv.prototype.domain=void 0,vv.prototype._events=void 0,vv.prototype._maxListeners=void 0,vv.defaultMaxListeners=10,vv.init=function(){this.domain=null,vv.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new yv,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},vv.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},vv.prototype.getMaxListeners=function(){return mv(this)},vv.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:wv(r,f,this);break;case 2:bv(r,f,this,arguments[1]);break;case 3:Ev(r,f,this,arguments[1],arguments[2]);break;case 4:_v(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new yv,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var kv=Object.freeze({__proto__:null,default:vv,EventEmitter:vv});function Pv(){throw new Error("setTimeout has not been defined")}function Mv(){throw new Error("clearTimeout has not been defined")}var xv=Pv,Rv=Mv;function Nv(t){if(xv===setTimeout)return setTimeout(t,0);if((xv===Pv||!xv)&&setTimeout)return xv=setTimeout,setTimeout(t,0);try{return xv(t,0)}catch(e){try{return xv.call(null,t,0)}catch(e){return xv.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xv=setTimeout),"function"==typeof global.clearTimeout&&(Rv=clearTimeout);var Bv,Cv=[],Lv=!1,Uv=-1;function Dv(){Lv&&Bv&&(Lv=!1,Bv.length?Cv=Bv.concat(Cv):Uv=-1,Cv.length&&Hv())}function Hv(){if(!Lv){var t=Nv(Dv);Lv=!0;for(var e=Cv.length;e;){for(Bv=Cv,Cv=[];++Uv1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),nm(e)?r.showHidden=e:e&&_m(r,e),hm(r.showHidden)&&(r.showHidden=!1),hm(r.depth)&&(r.depth=2),hm(r.colors)&&(r.colors=!1),hm(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Jv),Qv(r,t,r.depth)}function Jv(t,e){var r=Yv.styles[e];return r?"["+Yv.colors[r][0]+"m"+t+"["+Yv.colors[r][1]+"m":t}function Zv(t,e){return t}function Qv(t,e,r){if(t.customInspect&&e&&dm(e.inspect)&&e.inspect!==Yv&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return um(n)||(n=Qv(t,n,r)),n}var i=function(t,e){if(hm(e))return t.stylize("undefined","undefined");if(um(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(sm(e))return t.stylize(""+e,"number");if(nm(e))return t.stylize(""+e,"boolean");if(im(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),pm(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tm(e);if(0===o.length){if(dm(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(fm(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(lm(e))return t.stylize(Date.prototype.toString.call(e),"date");if(pm(e))return tm(e)}var a,h="",f=!1,c=["{","}"];(rm(e)&&(f=!0,c=["[","]"]),dm(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return fm(e)&&(h=" "+RegExp.prototype.toString.call(e)),lm(e)&&(h=" "+Date.prototype.toUTCString.call(e)),pm(e)&&(h=" "+tm(e)),0!==o.length||f&&0!=e.length?r<0?fm(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function tm(t){return"["+Error.prototype.toString.call(t)+"]"}function em(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Sm(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=im(r)?Qv(t,a.value,null):Qv(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),hm(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function rm(t){return Array.isArray(t)}function nm(t){return"boolean"==typeof t}function im(t){return null===t}function om(t){return null==t}function sm(t){return"number"==typeof t}function um(t){return"string"==typeof t}function am(t){return"symbol"==typeof t}function hm(t){return void 0===t}function fm(t){return cm(t)&&"[object RegExp]"===vm(t)}function cm(t){return"object"==typeof t&&null!==t}function lm(t){return cm(t)&&"[object Date]"===vm(t)}function pm(t){return cm(t)&&("[object Error]"===vm(t)||t instanceof Error)}function dm(t){return"function"==typeof t}function gm(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function ym(t){return Buffer.isBuffer(t)}function vm(t){return Object.prototype.toString.call(t)}function mm(t){return t<10?"0"+t.toString(10):t.toString(10)}Yv.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]},Yv.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var wm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bm(){var t=new Date,e=[mm(t.getHours()),mm(t.getMinutes()),mm(t.getSeconds())].join(":");return[t.getDate(),wm[t.getMonth()],e].join(" ")}function Em(){console.log("%s - %s",bm(),Wv.apply(null,arguments))}function _m(t,e){if(!e||!cm(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Sm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Im={inherits:Gv,_extend:_m,log:Em,isBuffer:ym,isPrimitive:gm,isFunction:dm,isError:pm,isDate:lm,isObject:cm,isRegExp:fm,isUndefined:hm,isSymbol:am,isString:um,isNumber:sm,isNullOrUndefined:om,isNull:im,isBoolean:nm,isArray:rm,inspect:Yv,deprecate:Vv,format:Wv,debuglog:Xv},Tm=Object.freeze({__proto__:null,format:Wv,deprecate:Vv,debuglog:Xv,inspect:Yv,isArray:rm,isBoolean:nm,isNull:im,isNullOrUndefined:om,isNumber:sm,isString:um,isSymbol:am,isUndefined:hm,isRegExp:fm,isObject:cm,isDate:lm,isError:pm,isFunction:dm,isPrimitive:gm,isBuffer:ym,log:Em,inherits:Gv,_extend:_m,default:Im});function Om(){this.head=null,this.tail=null,this.length=0}Om.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Om.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Om.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Om.prototype.clear=function(){this.head=this.tail=null,this.length=0},Om.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Om.prototype.concat=function(t){if(0===this.length)return I.alloc(0);if(1===this.length)return this.head.data;for(var e=I.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Am=I.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function km(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Am(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Mm;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xm;break;default:return void(this.write=Pm)}this.charBuffer=new I(6),this.charReceived=0,this.charLength=0}function Pm(t){return t.toString(this.encoding)}function Mm(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xm(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}km.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},km.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},km.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Bm.ReadableState=Nm;var Rm=Xv("stream");function Nm(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof aw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Om,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new km(t.encoding),this.encoding=t.encoding)}function Bm(t){if(!(this instanceof Bm))return new Bm(t);this._readableState=new Nm(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),vv.call(this)}function Cm(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Dm(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Dm(t))),function(t,e){e.readingMore||(e.readingMore=!0,jv(jm,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Lm?t=Lm:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Dm(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Rm("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?jv(Hm,t):Hm(t))}function Hm(t){Rm("emit readable"),t.emit("readable"),Gm(t)}function jm(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Wm(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,jv(Vm,e,t))}function Vm(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function $m(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Rm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Wm(this):Dm(this),null;if(0===(t=Um(t,e))&&e.ended)return 0===e.length&&Wm(this),null;var n,i=e.needReadable;return Rm("need readable",i),(0===e.length||e.length-t0?Km(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Wm(this)),null!==n&&this.emit("data",n),n},Bm.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Bm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Rm("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Rm("onunpipe"),t===r&&h()}function s(){Rm("onend"),t.end()}n.endEmitted?jv(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Rm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Gm(t))}}(r);t.on("drain",u);var a=!1;function h(){Rm("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Rm("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==$m(n.pipes,t))&&!a&&(Rm("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Rm("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Rm("onfinish"),t.removeListener("close",p),g()}function g(){Rm("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Rm("pipe resume"),r.resume()),t},Bm.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Jm.prototype._write=function(t,e,r){r(new Error("not implemented"))},Jm.prototype._writev=null,Jm.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,nw(t,e),r&&(e.finished?jv(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Gv(aw,Bm);for(var ow=Object.keys(Jm.prototype),sw=0;sw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Sw.alloc(0);for(var e=Sw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ow(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Sw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Tw,value:function(t,e){return Iw(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Bw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Bw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Cw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Cw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Bw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Bw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Bw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Bw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Bw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Bw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Bw("ERR_STREAM_WRITE_AFTER_END","write after end"),Bw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Bw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Bw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Rw.codes=Nw;var Lw=Rw.codes.ERR_INVALID_OPT_VALUE;var Uw,Dw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Lw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Hw=ww.deprecate,jw=ub;function Fw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}ub.WritableState=sb;var qw={deprecate:Hw},Gw=mw,Kw=ht.Buffer,Ww=r.Uint8Array||function(){};var Vw,$w=xw,zw=Dw.getHighWaterMark,Xw=Rw.codes,Yw=Xw.ERR_INVALID_ARG_TYPE,Jw=Xw.ERR_METHOD_NOT_IMPLEMENTED,Zw=Xw.ERR_MULTIPLE_CALLBACK,Qw=Xw.ERR_STREAM_CANNOT_PIPE,tb=Xw.ERR_STREAM_DESTROYED,eb=Xw.ERR_STREAM_NULL_VALUES,rb=Xw.ERR_STREAM_WRITE_AFTER_END,nb=Xw.ERR_UNKNOWN_ENCODING,ib=$w.errorOrDestroy;function ob(){}function sb(t,e,r){Uw=Uw||gb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Uw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=zw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Zw;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(pb,t,e),t._writableState.errorEmitted=!0,ib(t,n)):(i(n),t._writableState.errorEmitted=!0,ib(t,n),pb(t,e))}(t,r,n,e,i);else{var o=cb(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||fb(t,r),n?process.nextTick(hb,t,r,o,i):hb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new Fw(this)}function ub(t){var e=this instanceof(Uw=Uw||gb);if(!e&&!Vw.call(ub,this))return new ub(t);this._writableState=new sb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Gw.call(this)}function ab(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new tb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),pb(t,e)}function fb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,ab(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new Fw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(ab(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function cb(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function lb(t,e){t._final((function(r){e.pendingcb--,r&&ib(t,r),e.prefinished=!0,t.emit("prefinish"),pb(t,e)}))}function pb(t,e){var r=cb(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(lb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}Zt.exports(ub,Gw),sb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(sb.prototype,"buffer",{get:qw.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Vw=Function.prototype[Symbol.hasInstance],Object.defineProperty(ub,Symbol.hasInstance,{value:function(t){return!!Vw.call(this,t)||this===ub&&(t&&t._writableState instanceof sb)}})):Vw=function(t){return t instanceof this},ub.prototype.pipe=function(){ib(this,new Qw)},ub.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Kw.isBuffer(n)||n instanceof Ww);return s&&!Kw.isBuffer(t)&&(t=function(t){return Kw.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ob),i.ending?function(t,e){var r=new rb;ib(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new eb:"string"==typeof r||e.objectMode||(i=new Yw("chunk",["string","Buffer"],r)),!i||(ib(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Kw.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new nb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(ub.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(ub.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),ub.prototype._write=function(t,e,r){r(new Jw("_write()"))},ub.prototype._writev=null,ub.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,pb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(ub.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(ub.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),ub.prototype.destroy=$w.destroy,ub.prototype._undestroy=$w.undestroy,ub.prototype._destroy=function(t,e){e(t)};var db=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},gb=Eb,yb=aE,vb=jw;Zt.exports(Eb,yb);for(var mb=db(vb.prototype),wb=0;wb>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Pb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Mb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function xb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Rb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Nb(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Bb(t){return t.toString(this.encoding)}function Cb(t){return t&&t.length?this.write(t):""}Ib.StringDecoder=Ab,Ab.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Ab.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Lb=Rw.codes.ERR_STREAM_PREMATURE_CLOSE;function Ub(){}var Db,Hb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===cE.prototype||(e=function(t){return cE.from(t)}(e)),n)s.endEmitted?OE(t,new TE):xE(t,s,e,!0);else if(s.ended)OE(t,new SE);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?xE(t,s,e,!1):LE(t,s)):xE(t,s,e,!1)}else n||(s.reading=!1,LE(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=RE?t=RE:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function BE(t){var e=t._readableState;pE("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(pE("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(CE,t))}function CE(t){var e=t._readableState;pE("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,FE(t)}function LE(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(UE,t,e))}function UE(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function HE(t){pE("readable nexttick read 0"),t.read(0)}function jE(t,e){pE("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),FE(t),e.flowing&&!e.reading&&t.read(0)}function FE(t){var e=t._readableState;for(pE("flow",e.flowing);e.flowing&&null!==t.read(););}function qE(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function GE(t){var e=t._readableState;pE("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(KE,e,t))}function KE(t,e){if(pE("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function WE(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return pE("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?GE(this):BE(this),null;if(0===(t=NE(t,e))&&e.ended)return 0===e.length&&GE(this),null;var n,i=e.needReadable;return pE("need readable",i),(0===e.length||e.length-t0?qE(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&GE(this)),null!==n&&this.emit("data",n),n},PE.prototype._read=function(t){OE(this,new IE("_read()"))},PE.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,pE("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){pE("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,pE("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){pE("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;pE("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&hE(t,"data")&&(e.flowing=!0,FE(t))}}(r);t.on("drain",u);var a=!1;function h(e){pE("ondata");var i=t.write(e);pE("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==WE(n.pipes,t))&&!a&&(pE("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){pE("onerror",e),p(),t.removeListener("error",f),0===hE(t,"error")&&OE(t,e)}function c(){t.removeListener("finish",l),p()}function l(){pE("onfinish"),t.removeListener("close",c),p()}function p(){pE("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(pE("pipe resume"),r.resume()),t},PE.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,pE("on readable",n.length,n.reading),n.length?BE(this):n.reading||process.nextTick(HE,this))),r},PE.prototype.addListener=PE.prototype.on,PE.prototype.removeListener=function(t,e){var r=fE.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(DE,this),r},PE.prototype.removeAllListeners=function(t){var e=fE.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(DE,this),e},PE.prototype.resume=function(){var t=this._readableState;return t.flowing||(pE("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(jE,t,e))}(this,t)),t.paused=!1,this},PE.prototype.pause=function(){return pE("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(pE("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},PE.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(pE("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(pE("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(l_),s||(o.forEach(l_),i(n))}))}));return e.reduce(p_)};!function(t,e){var r=yw;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=aE).Stream=r||e,e.Readable=e,e.Writable=jw,e.Duplex=gb,e.Transform=VE,e.PassThrough=i_,e.finished=Hb,e.pipeline=g_)}(gv,gv.exports);var y_=h.exports.Buffer,v_=gv.exports.Transform;function m_(t){v_.call(this),this._block=y_.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,Zt.exports)(m_,v_),m_.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},m_.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},m_.prototype.update=function(t,e){if(function(t,e){if(!y_.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");y_.isBuffer(t)||(t=y_.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},m_.prototype._update=function(){throw new Error("_update is not implemented")},m_.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},m_.prototype._digest=function(){throw new Error("_digest is not implemented")};var w_=m_,b_=ht.Buffer,E_=Zt.exports,__=w_,S_=new Array(16),I_=[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],T_=[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],O_=[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],A_=[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],k_=[0,1518500249,1859775393,2400959708,2840853838],P_=[1352829926,1548603684,1836072691,2053994217,0];function M_(){__.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function x_(t,e){return t<>>32-e}function R_(t,e,r,n,i,o,s,u){return x_(t+(e^r^n)+o+s|0,u)+i|0}function N_(t,e,r,n,i,o,s,u){return x_(t+(e&r|~e&n)+o+s|0,u)+i|0}function B_(t,e,r,n,i,o,s,u){return x_(t+((e|~r)^n)+o+s|0,u)+i|0}function C_(t,e,r,n,i,o,s,u){return x_(t+(e&n|r&~n)+o+s|0,u)+i|0}function L_(t,e,r,n,i,o,s,u){return x_(t+(e^(r|~n))+o+s|0,u)+i|0}E_(M_,__),M_.prototype._update=function(){for(var t=S_,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=R_(r,n,i,o,s,t[I_[l]],k_[0],O_[l]),d=L_(u,a,h,f,c,t[T_[l]],P_[0],A_[l])):l<32?(p=N_(r,n,i,o,s,t[I_[l]],k_[1],O_[l]),d=C_(u,a,h,f,c,t[T_[l]],P_[1],A_[l])):l<48?(p=B_(r,n,i,o,s,t[I_[l]],k_[2],O_[l]),d=B_(u,a,h,f,c,t[T_[l]],P_[2],A_[l])):l<64?(p=C_(r,n,i,o,s,t[I_[l]],k_[3],O_[l]),d=N_(u,a,h,f,c,t[T_[l]],P_[3],A_[l])):(p=L_(r,n,i,o,s,t[I_[l]],k_[4],O_[l]),d=R_(u,a,h,f,c,t[T_[l]],P_[4],A_[l])),r=s,s=o,o=x_(i,10),i=n,n=p,u=c,c=f,f=x_(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},M_.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=b_.alloc?b_.alloc(20):new b_(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var U_=M_,D_={exports:{}},H_=h.exports.Buffer;function j_(t,e){this._block=H_.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}j_.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=H_.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},j_.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var F_=j_,q_=Zt.exports,G_=F_,K_=h.exports.Buffer,W_=[1518500249,1859775393,-1894007588,-899497514],V_=new Array(80);function $_(){this.init(),this._w=V_,G_.call(this,64,56)}function z_(t){return t<<30|t>>>2}function X_(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}q_($_,G_),$_.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},$_.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+X_(f,i,o,s)+u+r[h]+W_[f];u=s,s=o,o=z_(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},$_.prototype._hash=function(){var t=K_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var Y_=$_,J_=Zt.exports,Z_=F_,Q_=h.exports.Buffer,tS=[1518500249,1859775393,-1894007588,-899497514],eS=new Array(80);function rS(){this.init(),this._w=eS,Z_.call(this,64,56)}function nS(t){return t<<5|t>>>27}function iS(t){return t<<30|t>>>2}function oS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}J_(rS,Z_),rS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},rS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=nS(n)+oS(f,i,o,s)+u+r[h]+tS[f]|0;u=s,s=o,o=iS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},rS.prototype._hash=function(){var t=Q_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var sS=rS,uS=Zt.exports,aS=F_,hS=h.exports.Buffer,fS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cS=new Array(64);function lS(){this.init(),this._w=cS,aS.call(this,64,56)}function pS(t,e,r){return r^t&(e^r)}function dS(t,e,r){return t&e|r&(t|e)}function gS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function yS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function vS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function mS(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}uS(lS,aS),lS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},lS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=mS(e[f-2])+e[f-7]+vS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+yS(s)+pS(s,u,a)+fS[c]+e[c]|0,p=gS(r)+dS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},lS.prototype._hash=function(){var t=hS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var wS=lS,bS=Zt.exports,ES=wS,_S=F_,SS=h.exports.Buffer,IS=new Array(64);function TS(){this.init(),this._w=IS,_S.call(this,64,56)}bS(TS,ES),TS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},TS.prototype._hash=function(){var t=SS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var OS=TS,AS=Zt.exports,kS=F_,PS=h.exports.Buffer,MS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xS=new Array(160);function RS(){this.init(),this._w=xS,kS.call(this,128,112)}function NS(t,e,r){return r^t&(e^r)}function BS(t,e,r){return t&e|r&(t|e)}function CS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function LS(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function US(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function DS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function HS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function jS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function FS(t,e){return t>>>0>>0?1:0}AS(RS,kS),RS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},RS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=US(w,b),_=DS(b,w),S=HS(w=e[m-4],b=e[m-4+1]),I=jS(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],k=e[m-32+1],P=_+O|0,M=E+T+FS(P,_)|0;M=(M=M+S+FS(P=P+I|0,I)|0)+A+FS(P=P+k|0,k)|0,e[m]=M,e[m+1]=P}for(var x=0;x<160;x+=2){M=e[x],P=e[x+1];var R=BS(r,n,i),N=BS(f,c,l),B=CS(r,f),C=CS(f,r),L=LS(s,d),U=LS(d,s),D=MS[x],H=MS[x+1],j=NS(s,u,a),F=NS(d,g,y),q=v+U|0,G=h+L+FS(q,v)|0;G=(G=(G=G+j+FS(q=q+F|0,F)|0)+D+FS(q=q+H|0,H)|0)+M+FS(q=q+P|0,P)|0;var K=C+N|0,W=B+R+FS(K,C)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+G+FS(d=p+q|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+W+FS(f=q+K|0,q)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+FS(this._al,f)|0,this._bh=this._bh+n+FS(this._bl,c)|0,this._ch=this._ch+i+FS(this._cl,l)|0,this._dh=this._dh+o+FS(this._dl,p)|0,this._eh=this._eh+s+FS(this._el,d)|0,this._fh=this._fh+u+FS(this._fl,g)|0,this._gh=this._gh+a+FS(this._gl,y)|0,this._hh=this._hh+h+FS(this._hl,v)|0},RS.prototype._hash=function(){var t=PS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var qS=RS,GS=Zt.exports,KS=qS,WS=F_,VS=h.exports.Buffer,$S=new Array(160);function zS(){this.init(),this._w=$S,WS.call(this,128,112)}GS(zS,KS),zS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},zS.prototype._hash=function(){var t=VS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var XS=zS,YS=D_.exports=function(t){t=t.toLowerCase();var e=YS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};YS.sha=Y_,YS.sha1=sS,YS.sha224=OS,YS.sha256=wS,YS.sha384=XS,YS.sha512=qS;var JS=D_.exports;function ZS(t){return(new U_).update(JS("sha256").update(t).digest()).digest()}var QS,tI=(QS=function(t,e){return QS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},QS(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}QS(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),eI=function(t,e){this.psbt=t,this.masterFp=e},rI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(eI),nI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(rI),iI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new cv,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Bp.sha256(Buffer.from("TapTweak","utf-8"));return Bp.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(xt.exports.pointAddScalar(e,r)).slice(1)},e}(rI),oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=this.createRedeemScript(t),n=ZS(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=ZS(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(rI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(rI),uI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},aI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return lI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new cI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new cI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function UI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,LI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,LI(t.script.length),t.script])}))),r}function DI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,LI(t.script.length),t.script,t.sequence])}));var a=UI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),LI(t.inputs.length),s,a])}var HI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new pI(e,dI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return HI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I;return jI(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new _I,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new iI(e,r):t.additionals.includes("bech32")?new sI(e,r):t.segwit?new oI(e,r):new nI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new cv).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new cv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new cv;BI(h,f),BI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new cv).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}NI(t,r)}}(r),I=function(t){var e,r,n=new cv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new cv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nT(t,e,r){return tT(this,void 0,void 0,(function(){var n,i,o,s;return eT(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function iT(t,e,r,n){return void 0===n&&(n=[]),tT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R=this;return eT(this,(function(N){switch(N.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return tT(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return eT(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>pv?pv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=rT(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,nT(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return nT(t,e)},[4,nT(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),LI(o.length)]),e)];case 1:N.sent(),N.label=2;case 2:N.trys.push([2,8,9,10]),d=rT(o),g=d.next(),N.label=3;case 3:return g.done?[3,7]:(y=g.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?y.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([y.prevout,m,v?Buffer.from([0]):LI(y.script.length)]),[4,nT(t,O)]);case 4:return N.sent(),[4,f?p(Buffer.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:N.sent(),N.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=N.sent(),k={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,nT(t,LI(s.length))];case 11:N.sent(),N.label=12;case 12:N.trys.push([12,17,18,19]),b=rT(s),E=b.next(),N.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),LI(_.script.length),_.script]),[4,nT(t,O)]);case 14:N.sent(),N.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=N.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([LI(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return A=N.sent(),QI(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var oT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},sT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aT(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function hT(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),oT(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return sT(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),LI(r.inputs.length)]),[4,aT(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=uT(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),LI(p.script.length)]),[4,aT(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>pv?pv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=uT(y),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,aT(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function fT(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=JS("sha256").update(JS("sha256").update(DI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function cT(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=wt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var lT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},pT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:pv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var yT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ST={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function IT(t,e){return bT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C,L,U,D,H,j,F,q,G,K,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return ET(this,(function(ht){switch(ht.label){case 0:if(r=wT(wT({},ST),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,mT(t)];case 2:return v=ht.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||fv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),A=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),P=[],M=[],x=[],R=[],N=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},L=T&&!y?fT:iT,U=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=_T(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,L(t,$[1],$[0],c)]);case 7:j=ht.sent(),VI("hw","got trustedInput="+j),(F=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:dv,0),P.push({trustedInput:!0,value:Buffer.from(j,"hex"),sequence:F}),ht.label=8;case 8:q=$[0].outputs,G=$[1],q&&G<=q.length-1&&M.push(q[G]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:dv,0),{script:O,prevout:A,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),ZS(R[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[P[it]]:P,T?X.inputs=[wT(wT({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,hT(t,!T&&N,X,Y,T,!!l&&!b,c,y)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,dT(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,gT(t,U,c)];case 30:ht.sent(),ht.label=31;case 31:return N&&(d(),w(1,0)),[4,cT(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,N&&(N=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},xT={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function RT(t,e){return kT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C;return PT(this,(function(L){switch(L.label){case 0:r=AT(AT({},xT),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?fT:iT,b=Buffer.from(o,"hex"),L.label=1;case 1:L.trys.push([1,7,8,9]),E=MT(n),_=E.next(),L.label=2;case 2:return _.done?[3,6]:(P=_.value,v?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=L.sent(),(A=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:dv,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:A}),L.label=4;case 4:I=P[0].outputs,T=P[1],I&&T<=I.length-1&&d.push(I[T]),L.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=L.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:dv,0),m.inputs.push({script:f,prevout:c,sequence:A});return a?[4,hT(t,!0,m,p,!0)]:[3,12];case 10:return L.sent(),[4,gT(t,b)];case 11:L.sent(),L.label=12;case 12:k=0,L.label=13;case 13:return k=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[k].script,x=Object.assign({},m),R=a?[p[k]]:p,a?x.inputs=[AT(AT({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,hT(t,!a&&y,x,R,a)]):[3,19];case 14:return L.sent(),a?[3,16]:[4,gT(t,b)];case 15:L.sent(),L.label=16;case 16:return[4,cT(t,i[k],s,u)];case 17:N=L.sent(),g.push(a?N.toString("hex"):N.slice(0,N.length-1).toString("hex")),m.inputs[k].script=f,y&&(y=!1),L.label=18;case 18:return k++,[3,13];case 19:return[2,g]}}))}))}var NT=function(){return NT=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,u()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),IT(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),RT(this.transport,t)},t}();function UT(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var DT=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function HT(t){return JS("sha256").update(t).digest()}var jT,FT=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new hI(t.map((function(t){return fI(t)}))),this.values=e,this.valuesTree=new hI(e.map((function(t){return fI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([LI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),qT=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),GT=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},KT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},zT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(jT||(jT={}));var YT,JT,ZT=function(){},QT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=jT.YIELD,n.results=e,n}return VT(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(ZT),tO=function(t){function e(e,r){var n=t.call(this)||this;return n.code=jT.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=LI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,zT([],$T(a.slice(-f)),!1)),Buffer.concat(zT([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],$T(a.slice(0,h)),!1))},e}(ZT),rO=function(t){function e(e){var r=t.call(this)||this;return r.code=jT.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(YT||(YT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(JT||(JT={}));var aO=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return oO(this,void 0,void 0,(function(){var n,i,o;return sO(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,JT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return oO(this,void 0,void 0,(function(){return sO(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(YT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),mt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return oO(this,void 0,void 0,(function(){var o,s;return sO(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new iO((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(YT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return oO(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S;return sO(this,(function(I){switch(I.label){case 0:if(i=new WT(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new iO(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=uO(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=uO(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new hI(i.inputMapCommitments.map((function(t){return fI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new hI(i.outputMapCommitments.map((function(t){return fI(t)}))).getRoot(),[4,this.makeRequest(YT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),LI(i.getGlobalInputCount()),c,LI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=uO(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return oO(this,void 0,void 0,(function(){return sO(this,(function(t){return[2,this.makeRequest(YT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var hO=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},fO=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof qI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||lO(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(Buffer.from([3,0,0,128]))||y.equals(Buffer.from([4,0,0,128])),m=y.equals(Buffer.from([1,0,0,0]))||y.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(c=g.slice(a,4+a),a+=4);var w=CI(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new LT(this.transport)},t.prototype.new=function(){return new qI(new aO(this.transport))},t}();function lO(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var pO=Object.freeze({__proto__:null,default:cO}),dO={},gO={},yO={},vO={};Object.defineProperty(vO,"__esModule",{value:!0});var mO="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wO={},bO={};vO.addCustomErrorDeserializer=function(t,e){bO[t]=e};var EO=vO.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,wO[t]=e,e};function _O(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":mO(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=_O(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}vO.deserializeError=function t(e){if("object"===(void 0===e?"undefined":mO(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=bO[i];if(o)n=o(e);else{var s="Error"===i?Error:wO[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=EO(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},vO.serializeError=function(t){return t?"object"===(void 0===t?"undefined":mO(t))?_O(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(yO,"__esModule",{value:!0}),yO.StatusCodes=yO.DBNotReset=yO.DBWrongPassword=yO.NoDBPathGiven=yO.FirmwareOrAppUpdateRequired=yO.LedgerAPI5xx=yO.LedgerAPI4xx=yO.GenuineCheckFailed=yO.PairingFailed=yO.SyncError=yO.FeeTooHigh=yO.FeeRequired=yO.FeeNotLoaded=yO.CantScanQRCode=yO.ETHAddressNonEIP=yO.WrongAppForCurrency=yO.WrongDeviceForAccount=yO.WebsocketConnectionFailed=yO.WebsocketConnectionError=yO.DeviceShouldStayInApp=yO.TransportWebUSBGestureRequired=yO.TransportInterfaceNotAvailable=yO.TransportOpenUserCancelled=yO.UserRefusedOnDevice=yO.UserRefusedAllowManager=yO.UserRefusedFirmwareUpdate=yO.UserRefusedAddress=yO.UserRefusedDeviceNameChange=yO.UpdateYourApp=yO.UnavailableTezosOriginatedAccountSend=yO.UnavailableTezosOriginatedAccountReceive=yO.RecipientRequired=yO.MCUNotGenuineToDashboard=yO.UnexpectedBootloader=yO.TimeoutTagged=yO.RecommendUndelegation=yO.RecommendSubAccountsToEmpty=yO.PasswordIncorrectError=yO.PasswordsDontMatchError=yO.GasLessThanEstimate=yO.NotSupportedLegacyAddress=yO.NotEnoughGas=yO.NoAccessToCamera=yO.NotEnoughBalanceBecauseDestinationNotCreated=yO.NotEnoughSpendableBalance=yO.NotEnoughBalanceInParentAccount=yO.NotEnoughBalanceToDelegate=yO.NotEnoughBalance=yO.NoAddressesFound=yO.NetworkDown=yO.ManagerUninstallBTCDep=yO.ManagerNotEnoughSpaceError=yO.ManagerFirmwareNotEnoughSpaceError=yO.ManagerDeviceLockedError=yO.ManagerAppDepUninstallRequired=yO.ManagerAppDepInstallRequired=yO.ManagerAppRelyOnBTCError=yO.ManagerAppAlreadyInstalledError=yO.LedgerAPINotAvailable=yO.LedgerAPIErrorWithMessage=yO.LedgerAPIError=yO.UnknownMCU=yO.LatestMCUInstalledError=yO.InvalidAddressBecauseDestinationIsAlsoSource=yO.InvalidAddress=yO.InvalidXRPTag=yO.HardResetFail=yO.FeeEstimationFailed=yO.EthAppPleaseEnableContractData=yO.EnpointConfigError=yO.DisconnectedDeviceDuringOperation=yO.DisconnectedDevice=yO.DeviceSocketNoBulkStatus=yO.DeviceSocketFail=yO.DeviceNameInvalid=yO.DeviceHalted=yO.DeviceInOSUExpected=yO.DeviceOnDashboardUnexpected=yO.DeviceOnDashboardExpected=yO.DeviceNotGenuineError=yO.DeviceGenuineSocketEarlyClose=yO.DeviceAppVerifyNotSupported=yO.CurrencyNotSupported=yO.CashAddrNotSupported=yO.CantOpenDevice=yO.BtcUnmatchedApp=yO.BluetoothRequired=yO.AmountRequired=yO.AccountNotSupported=yO.AccountNameRequiredError=yO.addCustomErrorDeserializer=yO.createCustomErrorClass=yO.deserializeError=yO.serializeError=void 0,yO.TransportError=IO,yO.getAltStatusMessage=OO,yO.TransportStatusError=AO;var SO=vO;function IO(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}yO.serializeError=SO.serializeError,yO.deserializeError=SO.deserializeError,yO.createCustomErrorClass=SO.createCustomErrorClass,yO.addCustomErrorDeserializer=SO.addCustomErrorDeserializer,yO.AccountNameRequiredError=(0,SO.createCustomErrorClass)("AccountNameRequired"),yO.AccountNotSupported=(0,SO.createCustomErrorClass)("AccountNotSupported"),yO.AmountRequired=(0,SO.createCustomErrorClass)("AmountRequired"),yO.BluetoothRequired=(0,SO.createCustomErrorClass)("BluetoothRequired"),yO.BtcUnmatchedApp=(0,SO.createCustomErrorClass)("BtcUnmatchedApp"),yO.CantOpenDevice=(0,SO.createCustomErrorClass)("CantOpenDevice"),yO.CashAddrNotSupported=(0,SO.createCustomErrorClass)("CashAddrNotSupported"),yO.CurrencyNotSupported=(0,SO.createCustomErrorClass)("CurrencyNotSupported"),yO.DeviceAppVerifyNotSupported=(0,SO.createCustomErrorClass)("DeviceAppVerifyNotSupported"),yO.DeviceGenuineSocketEarlyClose=(0,SO.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),yO.DeviceNotGenuineError=(0,SO.createCustomErrorClass)("DeviceNotGenuine"),yO.DeviceOnDashboardExpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardExpected"),yO.DeviceOnDashboardUnexpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardUnexpected"),yO.DeviceInOSUExpected=(0,SO.createCustomErrorClass)("DeviceInOSUExpected"),yO.DeviceHalted=(0,SO.createCustomErrorClass)("DeviceHalted"),yO.DeviceNameInvalid=(0,SO.createCustomErrorClass)("DeviceNameInvalid"),yO.DeviceSocketFail=(0,SO.createCustomErrorClass)("DeviceSocketFail"),yO.DeviceSocketNoBulkStatus=(0,SO.createCustomErrorClass)("DeviceSocketNoBulkStatus"),yO.DisconnectedDevice=(0,SO.createCustomErrorClass)("DisconnectedDevice"),yO.DisconnectedDeviceDuringOperation=(0,SO.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),yO.EnpointConfigError=(0,SO.createCustomErrorClass)("EnpointConfig"),yO.EthAppPleaseEnableContractData=(0,SO.createCustomErrorClass)("EthAppPleaseEnableContractData"),yO.FeeEstimationFailed=(0,SO.createCustomErrorClass)("FeeEstimationFailed"),yO.HardResetFail=(0,SO.createCustomErrorClass)("HardResetFail"),yO.InvalidXRPTag=(0,SO.createCustomErrorClass)("InvalidXRPTag"),yO.InvalidAddress=(0,SO.createCustomErrorClass)("InvalidAddress"),yO.InvalidAddressBecauseDestinationIsAlsoSource=(0,SO.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),yO.LatestMCUInstalledError=(0,SO.createCustomErrorClass)("LatestMCUInstalledError"),yO.UnknownMCU=(0,SO.createCustomErrorClass)("UnknownMCU"),yO.LedgerAPIError=(0,SO.createCustomErrorClass)("LedgerAPIError"),yO.LedgerAPIErrorWithMessage=(0,SO.createCustomErrorClass)("LedgerAPIErrorWithMessage"),yO.LedgerAPINotAvailable=(0,SO.createCustomErrorClass)("LedgerAPINotAvailable"),yO.ManagerAppAlreadyInstalledError=(0,SO.createCustomErrorClass)("ManagerAppAlreadyInstalled"),yO.ManagerAppRelyOnBTCError=(0,SO.createCustomErrorClass)("ManagerAppRelyOnBTC"),yO.ManagerAppDepInstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepInstallRequired"),yO.ManagerAppDepUninstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepUninstallRequired"),yO.ManagerDeviceLockedError=(0,SO.createCustomErrorClass)("ManagerDeviceLocked"),yO.ManagerFirmwareNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),yO.ManagerNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerNotEnoughSpace"),yO.ManagerUninstallBTCDep=(0,SO.createCustomErrorClass)("ManagerUninstallBTCDep"),yO.NetworkDown=(0,SO.createCustomErrorClass)("NetworkDown"),yO.NoAddressesFound=(0,SO.createCustomErrorClass)("NoAddressesFound"),yO.NotEnoughBalance=(0,SO.createCustomErrorClass)("NotEnoughBalance"),yO.NotEnoughBalanceToDelegate=(0,SO.createCustomErrorClass)("NotEnoughBalanceToDelegate"),yO.NotEnoughBalanceInParentAccount=(0,SO.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),yO.NotEnoughSpendableBalance=(0,SO.createCustomErrorClass)("NotEnoughSpendableBalance"),yO.NotEnoughBalanceBecauseDestinationNotCreated=(0,SO.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),yO.NoAccessToCamera=(0,SO.createCustomErrorClass)("NoAccessToCamera"),yO.NotEnoughGas=(0,SO.createCustomErrorClass)("NotEnoughGas"),yO.NotSupportedLegacyAddress=(0,SO.createCustomErrorClass)("NotSupportedLegacyAddress"),yO.GasLessThanEstimate=(0,SO.createCustomErrorClass)("GasLessThanEstimate"),yO.PasswordsDontMatchError=(0,SO.createCustomErrorClass)("PasswordsDontMatch"),yO.PasswordIncorrectError=(0,SO.createCustomErrorClass)("PasswordIncorrect"),yO.RecommendSubAccountsToEmpty=(0,SO.createCustomErrorClass)("RecommendSubAccountsToEmpty"),yO.RecommendUndelegation=(0,SO.createCustomErrorClass)("RecommendUndelegation"),yO.TimeoutTagged=(0,SO.createCustomErrorClass)("TimeoutTagged"),yO.UnexpectedBootloader=(0,SO.createCustomErrorClass)("UnexpectedBootloader"),yO.MCUNotGenuineToDashboard=(0,SO.createCustomErrorClass)("MCUNotGenuineToDashboard"),yO.RecipientRequired=(0,SO.createCustomErrorClass)("RecipientRequired"),yO.UnavailableTezosOriginatedAccountReceive=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),yO.UnavailableTezosOriginatedAccountSend=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),yO.UpdateYourApp=(0,SO.createCustomErrorClass)("UpdateYourApp"),yO.UserRefusedDeviceNameChange=(0,SO.createCustomErrorClass)("UserRefusedDeviceNameChange"),yO.UserRefusedAddress=(0,SO.createCustomErrorClass)("UserRefusedAddress"),yO.UserRefusedFirmwareUpdate=(0,SO.createCustomErrorClass)("UserRefusedFirmwareUpdate"),yO.UserRefusedAllowManager=(0,SO.createCustomErrorClass)("UserRefusedAllowManager"),yO.UserRefusedOnDevice=(0,SO.createCustomErrorClass)("UserRefusedOnDevice"),yO.TransportOpenUserCancelled=(0,SO.createCustomErrorClass)("TransportOpenUserCancelled"),yO.TransportInterfaceNotAvailable=(0,SO.createCustomErrorClass)("TransportInterfaceNotAvailable"),yO.TransportWebUSBGestureRequired=(0,SO.createCustomErrorClass)("TransportWebUSBGestureRequired"),yO.DeviceShouldStayInApp=(0,SO.createCustomErrorClass)("DeviceShouldStayInApp"),yO.WebsocketConnectionError=(0,SO.createCustomErrorClass)("WebsocketConnectionError"),yO.WebsocketConnectionFailed=(0,SO.createCustomErrorClass)("WebsocketConnectionFailed"),yO.WrongDeviceForAccount=(0,SO.createCustomErrorClass)("WrongDeviceForAccount"),yO.WrongAppForCurrency=(0,SO.createCustomErrorClass)("WrongAppForCurrency"),yO.ETHAddressNonEIP=(0,SO.createCustomErrorClass)("ETHAddressNonEIP"),yO.CantScanQRCode=(0,SO.createCustomErrorClass)("CantScanQRCode"),yO.FeeNotLoaded=(0,SO.createCustomErrorClass)("FeeNotLoaded"),yO.FeeRequired=(0,SO.createCustomErrorClass)("FeeRequired"),yO.FeeTooHigh=(0,SO.createCustomErrorClass)("FeeTooHigh"),yO.SyncError=(0,SO.createCustomErrorClass)("SyncError"),yO.PairingFailed=(0,SO.createCustomErrorClass)("PairingFailed"),yO.GenuineCheckFailed=(0,SO.createCustomErrorClass)("GenuineCheckFailed"),yO.LedgerAPI4xx=(0,SO.createCustomErrorClass)("LedgerAPI4xx"),yO.LedgerAPI5xx=(0,SO.createCustomErrorClass)("LedgerAPI5xx"),yO.FirmwareOrAppUpdateRequired=(0,SO.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),yO.NoDBPathGiven=(0,SO.createCustomErrorClass)("NoDBPathGiven"),yO.DBWrongPassword=(0,SO.createCustomErrorClass)("DBWrongPassword"),yO.DBNotReset=(0,SO.createCustomErrorClass)("DBNotReset"),IO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportError",(function(t){return new IO(t.message,t.id)}));var TO=yO.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function OO(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function AO(t){this.name="TransportStatusError";var e=Object.keys(TO).find((function(e){return TO[e]===t}))||"UNKNOWN_ERROR",r=OO(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}AO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new AO(t.statusCode)})),Object.defineProperty(gO,"__esModule",{value:!0}),gO.getAltStatusMessage=gO.StatusCodes=gO.TransportStatusError=gO.TransportError=void 0;var kO,PO=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[xO.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new xO.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new xO.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=NO(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new xO.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return PO(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new xO.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new xO.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();BO.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",BO.ErrorMessage_NoDeviceFound="No Ledger device found",gO.default=BO;var CO={};Object.defineProperty(CO,"__esModule",{value:!0});var LO=yO;function UO(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var DO={data:Buffer.alloc(0),dataLength:0,sequence:0};CO.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([UO(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var HO={};Object.defineProperty(HO,"__esModule",{value:!0});var jO=Object.assign||function(t){for(var e=1;e>8;return GO.find((function(t){return t.productIdMM===r}))},HO.identifyProductName=function(t){var e=qO[t];return GO.find((function(t){return t.id===e}))};var KO=[],WO={};for(var VO in FO){var $O=FO[VO],zO=$O.bluetoothSpec;if(zO)for(var XO=0;XO0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",oA());case 6:case"end":return t.stop()}}),t,this)}))),function(){return iA.apply(this,arguments)});var uA=HO;function aA(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var hA=[{vendorId:uA.ledgerUSBVendorId}];eA.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(dO,"__esModule",{value:!0});var fA=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,lA.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,dA.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,dA.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new gA.DisconnectedDeviceDuringOperation(e.message);throw e}))}},EA=dO.default=wA,_A=Object.freeze(e({__proto__:null,default:EA},[dO]));t.Btc=pO,t.TransportWebUSB=_A,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,e){var r=ht,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(h,h.exports);var ft=h.exports.Buffer;var ct=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ft.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ft.from(e)),!ft.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,k=0|s[6],P=8191&k,M=k>>>13,x=0|s[7],R=8191&x,N=x>>>13,B=0|s[8],C=8191&B,U=B>>>13,L=0|s[9],D=8191&L,H=L>>>13,j=0|u[0],q=8191&j,F=j>>>13,K=0|u[1],G=8191&K,W=K>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(c,q))|0)+((8191&(i=(i=Math.imul(c,F))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,F))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,F))+Math.imul(g,q)|0,o=Math.imul(g,F);var vt=(h+(n=n+Math.imul(c,G)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,G)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,F))+Math.imul(m,q)|0,o=Math.imul(m,F),n=n+Math.imul(d,G)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,W)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,F))+Math.imul(E,q)|0,o=Math.imul(E,F),n=n+Math.imul(v,G)|0,i=(i=i+Math.imul(v,W)|0)+Math.imul(m,G)|0,o=o+Math.imul(m,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,F))+Math.imul(I,q)|0,o=Math.imul(I,F),n=n+Math.imul(b,G)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(E,G)|0,o=o+Math.imul(E,W)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,F))+Math.imul(A,q)|0,o=Math.imul(A,F),n=n+Math.imul(S,G)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,G)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(P,q),i=(i=Math.imul(P,F))+Math.imul(M,q)|0,o=Math.imul(M,F),n=n+Math.imul(O,G)|0,i=(i=i+Math.imul(O,W)|0)+Math.imul(A,G)|0,o=o+Math.imul(A,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(R,q),i=(i=Math.imul(R,F))+Math.imul(N,q)|0,o=Math.imul(N,F),n=n+Math.imul(P,G)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,W)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,q),i=(i=Math.imul(C,F))+Math.imul(U,q)|0,o=Math.imul(U,F),n=n+Math.imul(R,G)|0,i=(i=i+Math.imul(R,W)|0)+Math.imul(N,G)|0,o=o+Math.imul(N,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,q),i=(i=Math.imul(D,F))+Math.imul(H,q)|0,o=Math.imul(H,F),n=n+Math.imul(C,G)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,z)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,G),i=(i=Math.imul(D,W))+Math.imul(H,G)|0,o=Math.imul(H,W),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(N,rt)|0,o=o+Math.imul(N,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,st)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ct)|0,o=o+Math.imul(A,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ht)|0)+Math.imul(N,at)|0,o=o+Math.imul(N,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(R,ct)|0,i=(i=i+Math.imul(R,lt)|0)+Math.imul(N,ct)|0,o=o+Math.imul(N,lt)|0;var xt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Rt=(h+(n=n+Math.imul(R,dt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(N,dt)|0))<<13)|0;h=((o=o+Math.imul(N,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Nt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=kt,a[13]=Pt,a[14]=Mt,a[15]=xt,a[16]=Rt,a[17]=Nt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Rt);var Nt={},Bt="6.5.4",Ct={},Ut=Lt;function Lt(t,e){if(!t)throw new Error(e||"Assertion failed")}Lt.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Dt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Dt),function(t){var e=t,r=Rt.exports,n=Ut,i=Dt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ct);var Ht,jt={exports:{}};function qt(t){this.rand=t}if(jt.exports=function(t){return Ht||(Ht=new qt(null)),Ht.generate(t)},jt.exports.Rand=qt,qt.prototype.generate=function(t){return this._rand(t)},qt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Yt=Xt;function Jt(t,e){this.curve=t,this.type=e,this.precomputed=null}Xt.prototype.point=function(){throw new Error("Not implemented")},Xt.prototype.validate=function(){throw new Error("Not implemented")},Xt.prototype._fixedNafMul=function(t,e){zt(t.precomputed);var r=t._getDoubles(),n=Vt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];zt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Xt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=$t(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Jt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},se.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},se.prototype.pointFromX=function(t,e){(t=new re(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},se.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},se.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ae.prototype.isInfinity=function(){return this.inf},ae.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ae.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ae.prototype.getX=function(){return this.x.fromRed()},ae.prototype.getY=function(){return this.y.fromRed()},ae.prototype.mul=function(t){return t=new re(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ae.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ae.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ae.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ae.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ae.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ne(he,ie.BasePoint),se.prototype.jpoint=function(t,e,r){return new he(this,t,e,r)},he.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},he.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},he.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},he.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},he.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},he.prototype.inspect=function(){return this.isInfinity()?"":""},he.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var fe=Rt.exports,ce=Zt.exports,le=Yt,pe=Ct;function de(t){le.call(this,"mont",t),this.a=new fe(t.a,16).toRed(this.red),this.b=new fe(t.b,16).toRed(this.red),this.i4=new fe(4).toRed(this.red).redInvm(),this.two=new fe(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}ce(de,le);var ge=de;function ye(t,e,r){le.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new fe(e,16),this.z=new fe(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}de.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},ce(ye,le.BasePoint),de.prototype.decodePoint=function(t,e){return this.point(pe.toArray(t,e),1)},de.prototype.point=function(t,e){return new ye(this,t,e)},de.prototype.pointFromJSON=function(t){return ye.fromJSON(this,t)},ye.prototype.precompute=function(){},ye.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ye.fromJSON=function(t,e){return new ye(t,e[0],e[1]||t.one)},ye.prototype.inspect=function(){return this.isInfinity()?"":""},ye.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ye.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ye.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ye.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ye.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ye.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ye.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ve=Ct,me=Rt.exports,we=Zt.exports,be=Yt,Ee=ve.assert;function _e(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,be.call(this,"edwards",t),this.a=new me(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new me(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new me(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ee(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}we(_e,be);var Se=_e;function Ie(t,e,r,n,i){be.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new me(e,16),this.y=new me(r,16),this.z=n?new me(n,16):this.curve.one,this.t=i&&new me(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}_e.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},_e.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},_e.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},_e.prototype.pointFromX=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},_e.prototype.pointFromY=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},_e.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},we(Ie,be.BasePoint),_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},_e.prototype.point=function(t,e,r,n){return new Ie(this,t,e,r,n)},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1],e[2])},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ie.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Ie.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ie.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ie.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Ie.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Ie.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ie.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ie.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ie.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ie.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ie.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ie.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ie.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ie.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ie.prototype.toP=Ie.prototype.normalize,Ie.prototype.mixedAdd=Ie.prototype.add,function(t){var e=t;e.base=Yt,e.short=ue,e.mont=ge,e.edwards=Se}(Kt);var Te={},Oe={},Ae={},ke=Ut,Pe=Zt.exports;function Me(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Re(t){return 1===t.length?"0"+t:t}function Ne(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ae.inherits=Pe,Ae.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Me(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ae.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ae.rotr32=function(t,e){return t>>>e|t<<32-e},Ae.rotl32=function(t,e){return t<>>32-e},Ae.sum32=function(t,e){return t+e>>>0},Ae.sum32_3=function(t,e,r){return t+e+r>>>0},Ae.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ae.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ae.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ae.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ae.sum64_lo=function(t,e,r,n){return e+n>>>0},Ae.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ae.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ae.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ae.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ae.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ae.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ae.shr64_hi=function(t,e,r){return t>>>r},Ae.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Be={},Ce=Ae,Ue=Ut;function Le(){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}Be.BlockHash=Le,Le.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},He.g1_256=function(t){return je(t,17)^je(t,19)^t>>>10};var Ge=Ae,We=Be,Ve=He,$e=Ge.rotl32,ze=Ge.sum32,Xe=Ge.sum32_5,Ye=Ve.ft_1,Je=We.BlockHash,Ze=[1518500249,1859775393,2400959708,3395469782];function Qe(){if(!(this instanceof Qe))return new Qe;Je.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ge.inherits(Qe,Je);var tr=Qe;Qe.blockSize=512,Qe.outSize=160,Qe.hmacStrength=80,Qe.padLength=64,Qe.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),bn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var An=On;On.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},On.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=In.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Rn=Rt.exports,Nn=Ct,Bn=Nn.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Bn(t.r&&t.s,"Signature without r or s"),this.r=new Rn(t.r,16),this.s=new Rn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Un=Cn;function Ln(){this.place=0}function Dn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function Hn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Nn.toArray(t,e);var r=new Ln;if(48!==t[r.place++])return!1;var n=Dn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Dn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Dn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Rn(o),this.s=new Rn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=Hn(e),r=Hn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];jn(n,e.length),(n=n.concat(e)).push(2),jn(n,r.length);var i=n.concat(r),o=[48];return jn(o,i.length),o=o.concat(i),Nn.encode(o,t)};var qn=Rt.exports,Fn=An,Kn=Ct,Gn=Te,Wn=jt.exports,Vn=Kn.assert,$n=xn,zn=Un;function Xn(t){if(!(this instanceof Xn))return new Xn(t);"string"==typeof t&&(Vn(Object.prototype.hasOwnProperty.call(Gn,t),"Unknown curve "+t),t=Gn[t]),t instanceof Gn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Yn=Xn;Xn.prototype.keyPair=function(t){return new $n(this,t)},Xn.prototype.keyFromPrivate=function(t,e){return $n.fromPrivate(this,t,e)},Xn.prototype.keyFromPublic=function(t,e){return $n.fromPublic(this,t,e)},Xn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Fn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Wn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new qn(2));;){var i=new qn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Xn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Xn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new qn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Fn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new qn(1)),h=0;;h++){var f=n.k?n.k(h):new qn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new zn({r:p,s:d,recoveryParam:g})}}}}}},Xn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new qn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new zn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Xn.prototype.recoverPubKey=function(t,e,r,n){Vn((3&r)===r,"The recovery param is more than two bits"),e=new zn(e,n);var i=this.n,o=new qn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Xn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new zn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Jn=Ct,Zn=Jn.assert,Qn=Jn.parseBytes,ti=Jn.cachedProperty;function ei(t,e){this.eddsa=t,this._secret=Qn(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=Qn(e.pub)}ei.fromPublic=function(t,e){return e instanceof ei?e:new ei(t,{pub:e})},ei.fromSecret=function(t,e){return e instanceof ei?e:new ei(t,{secret:e})},ei.prototype.secret=function(){return this._secret},ti(ei,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ti(ei,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ti(ei,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ti(ei,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ti(ei,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ti(ei,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ei.prototype.sign=function(t){return Zn(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ei.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ei.prototype.getSecret=function(t){return Zn(this._secret,"KeyPair is public only"),Jn.encode(this.secret(),t)},ei.prototype.getPublic=function(t){return Jn.encode(this.pubBytes(),t)};var ri=ei,ni=Rt.exports,ii=Ct,oi=ii.assert,si=ii.cachedProperty,ui=ii.parseBytes;function ai(t,e){this.eddsa=t,"object"!=typeof e&&(e=ui(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),oi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ni&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}si(ai,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),si(ai,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),si(ai,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),si(ai,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),ai.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},ai.prototype.toHex=function(){return ii.encode(this.toBytes(),"hex").toUpperCase()};var hi=ai,fi=Oe,ci=Te,li=Ct,pi=li.assert,di=li.parseBytes,gi=ri,yi=hi;function vi(t){if(pi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof vi))return new vi(t);t=ci[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=fi.sha512}var mi=vi;vi.prototype.sign=function(t,e){t=di(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},vi.prototype.verify=function(t,e,r){t=di(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},vi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Gi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Oi)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function Hi(t){return 4!==t[0]}function ji(t){return!!Ui(t)&&(t.compare(Oi)>0&&t.compare(Ai)<0)}function qi(t,e){return void 0===t&&void 0!==e?Hi(e):void 0===t||t}function Fi(t){return new Si(t)}function Ki(t){return t.toArrayLike(Buffer,"be",32)}function Gi(t){return Ii.curve.decodePoint(t)}function Wi(t,e){return Buffer.from(t._encode(e))}function Vi(t,e,r){if(!Ui(t))throw new TypeError(Ci);if(!ji(e))throw new TypeError(Ri);if(void 0!==r&&!Ui(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Fi(e),i=Fi(t);let o,s;Ti(t,e,(function(t){const e=Fi(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Pi),0!==o.isZero()&&(s=e.invm(Pi).mul(i.add(n.mul(o))).umod(Pi),0!==s.isZero()))}),ji,r),s.cmp(Mi)>0&&(s=Pi.sub(s));const u=Buffer.allocUnsafe(64);return Ki(o).copy(u,0),Ki(s).copy(u,32),u}var $i={isPoint:Di,isPointCompressed:function(t){return!!Di(t)&&Hi(t)},isPrivate:ji,pointAdd:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Di(e))throw new TypeError(Ni);const n=Gi(t),i=Gi(e),o=n.add(i);return o.isInfinity()?null:Wi(o,qi(r,t))},pointAddScalar:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t);if(0===e.compare(Oi))return Wi(i,n);const o=Fi(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:Wi(u,n)},pointCompress:function(t,e){if(!Di(t))throw new TypeError(Ni);const r=Gi(t);if(r.isInfinity())throw new TypeError(Ni);return Wi(r,qi(e,t))},pointFromScalar:function(t,e){if(!ji(t))throw new TypeError(Ri);const r=Fi(t),n=xi.mul(r);return n.isInfinity()?null:Wi(n,qi(e))},pointMultiply:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t),o=Fi(e),s=i.mul(o);return s.isInfinity()?null:Wi(s,n)},privateAdd:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.add(n).umod(Pi));return ji(i)?i:null},privateSub:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.sub(n).umod(Pi));return ji(i)?i:null},sign:function(t,e){return Vi(t,e)},signWithEntropy:function(t,e,r){return Vi(t,e,r)},verify:function(t,e,r,n){if(!Ui(t))throw new TypeError(Ci);if(!Di(e))throw new TypeError(Ni);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Ai)<0&&r.compare(Ai)<0}(r))throw new TypeError("Expected Signature");const i=Gi(e),o=Fi(r.slice(0,32)),s=Fi(r.slice(32,64));if(n&&s.cmp(Mi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Fi(t),a=s.invm(Pi),h=u.mul(a).umod(Pi),f=o.mul(a).umod(Pi),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Pi).eq(o)}};try{xt.exports=require("./native")}catch(t){xt.exports=$i}var zi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Xi in zi.Null=zi.Nil,zi)zi[Xi].toJSON=function(t){return t}.bind(null,Xi);var Yi=zi,Ji=Yi;function Zi(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Qi(t){return Ji.Nil(t)?"":Zi(t.constructor)}function to(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function eo(t){return Ji.Function(t)?t.toJSON?t.toJSON():Zi(t):Ji.Array(t)?"Array":t&&Ji.Object(t)?"Object":void 0!==t?t:""}function ro(t,e,r){var n=function(t){return Ji.Function(t)?"":Ji.String(t)?JSON.stringify(t):t&&Ji.Object(t)?"":t}(e);return"Expected "+eo(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function no(t,e,r){r=r||Qi(e),this.message=ro(t,e,r),to(this,no),this.__type=t,this.__value=e,this.__valueTypeName=r}function io(t,e,r,n,i){t?(i=i||Qi(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ro('property "'+eo(r)+o+eo(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',to(this,no),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}no.prototype=Object.create(Error.prototype),no.prototype.constructor=no,io.prototype=Object.create(Error.prototype),io.prototype.constructor=no;var oo={TfTypeError:no,TfPropertyTypeError:io,tfCustomError:function(t,e){return new no(t,{},e)},tfSubError:function(t,e,r){return t instanceof io?(e=e+"."+t.__property,t=new io(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof no&&(t=new io(t.__type,e,r,t.__value,t.__valueTypeName)),to(t),t},tfJSON:eo,getValueTypeName:Qi},so=Yi,uo=oo;function ao(t){return Buffer.isBuffer(t)}function ho(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function fo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw uo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var co=fo.bind(null,so.Array),lo=fo.bind(null,ao),po=fo.bind(null,ho),go=fo.bind(null,so.String);var yo=Math.pow(2,53)-1;var vo={ArrayN:co,Buffer:ao,BufferN:lo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:ho,HexN:po,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-yo&&t<=yo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=yo&&Math.floor(t)===t}};for(var mo in vo)vo[mo].toJSON=function(t){return t}.bind(null,mo);var wo=vo,bo=Yi,Eo=oo.tfJSON,_o=oo.TfTypeError,So=oo.TfPropertyTypeError,Io=oo.tfSubError,To=oo.getValueTypeName,Oo={arrayOf:function(t,e){function r(r,n){return!!bo.Array(r)&&(!bo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw Io(t,r)}}))))))}return t=Ao(t),e=e||{},r.toJSON=function(){var r="["+Eo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return bo.Nil(r)||e(r,n,t)}return e=Ao(e),r.toJSON=function(){return"?"+Eo(e)},r},map:function(t,e){function r(r,n){if(!bo.Object(r))return!1;if(bo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw Io(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw Io(t,i)}}return!0}return t=Ao(t),e&&(e=Ao(e)),r.toJSON=e?function(){return"{"+Eo(e)+": "+Eo(t)+"}"}:function(){return"{"+Eo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ao(t[r]);function n(t,r){if(!bo.Object(t))return!1;if(bo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw Io(t,n)}if(r)for(n in t)if(!e[n])throw new So(void 0,n);return!0}return n.toJSON=function(){return Eo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join(" & ")},e},quacksLike:function(t){function e(e){return t===To(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return!bo.Nil(e)&&(!bo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw Io(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Eo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ao(t){if(bo.String(t))return"?"===t[0]?Oo.maybe(t.slice(1)):bo[t]||Oo.quacksLike(t);if(t&&bo.Object(t)){if(bo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Oo.arrayOf(t[0])}return Oo.object(t)}return bo.Function(t)?t:Oo.value(t)}function ko(t,e,r,n){if(bo.Function(t)){if(t(e,r))return!0;throw new _o(n||t,e)}return ko(Ao(t),e,r)}for(var Po in Oo.oneOf=Oo.anyOf,bo)ko[Po]=bo[Po];for(Po in Oo)ko[Po]=Oo[Po];var Mo=wo;for(Po in Mo)ko[Po]=Mo[Po];ko.compile=Ao,ko.TfTypeError=_o,ko.TfPropertyTypeError=So;var xo=ko,Ro=vt;function No(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Bo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return No(Ro.decode(t),e)},decodeRaw:No,encode:function(t,e,r){return"number"==typeof t?Ro.encode(Bo(t,e,r)):Ro.encode(Bo(t.version,t.privateKey,t.compressed))},encodeRaw:Bo};Object.defineProperty(Ot,"__esModule",{value:!0});const Uo=At,Lo=vt,Do=xt.exports,Ho=xo,jo=Co,qo=Ho.BufferN(32),Fo=Ho.compile({wif:Ho.UInt8,bip32:{public:Ho.UInt32,private:Ho.UInt32}}),Ko={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Go=2147483648,Wo=Math.pow(2,31)-1;function Vo(t){return Ho.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function $o(t){return Ho.UInt32(t)&&t<=Wo}class zo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,Ho(Fo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Do.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Uo.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Jo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Lo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return jo.encode(this.network.wif,this.privateKey,!0)}derive(t){Ho(Ho.UInt32,t);const e=t>=Go,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Uo.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Do.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Do.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Jo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Do.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Yo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return Ho($o,t),this.derive(t+Go)}derivePath(t){Ho(Vo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Do.sign(t,this.privateKey);{let e=Do.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Do.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Do.verify(t,this.publicKey,e)}}function Xo(t,e,r){return Yo(t,e,r)}function Yo(t,e,r,n,i,o){if(Ho({privateKey:qo,chainCode:qo},{privateKey:t,chainCode:e}),r=r||Ko,!Do.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new zo(t,void 0,e,r,n,i,o)}function Jo(t,e,r,n,i,o){if(Ho({publicKey:Ho.BufferN(33),chainCode:qo},{publicKey:t,chainCode:e}),r=r||Ko,!Do.isPoint(t))throw new TypeError("Point is not on the curve");return new zo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Lo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Ko;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Yo(r.slice(46,78),u,e,i,s,o)}else{a=Jo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Xo,Ot.fromPublicKey=function(t,e,r){return Jo(t,e,r)},Ot.fromSeed=function(t,e){if(Ho(Ho.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Ko;const r=Uo.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Xo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var Zo=Ot;Tt.fromSeed=Zo.fromSeed,Tt.fromBase58=Zo.fromBase58,Tt.fromPublicKey=Zo.fromPublicKey,Tt.fromPrivateKey=Zo.fromPrivateKey;var Qo={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ts.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ts.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var es={},rs={},ns={},is={};Object.defineProperty(is,"__esModule",{value:!0}),is.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0});const us=xo,as=Math.pow(2,31)-1;function hs(t){return us.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ss.UInt31=function(t){return us.UInt32(t)&&t<=as},ss.BIP32Path=hs,hs.toJSON=()=>"BIP32 derivation path",ss.Signer=function(t){return(us.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ss.Satoshi=function(t){return us.UInt53(t)&&t<=21e14},ss.ECPoint=us.quacksLike("Point"),ss.Network=us.compile({messagePrefix:us.oneOf(us.Buffer,us.String),bip32:{public:us.UInt32,private:us.UInt32},pubKeyHash:us.UInt8,scriptHash:us.UInt8,wif:us.UInt8}),ss.Buffer256bit=us.BufferN(32),ss.Hash160bit=us.BufferN(20),ss.Hash256bit=us.BufferN(32),ss.Number=us.Number,ss.Array=us.Array,ss.Boolean=us.Boolean,ss.String=us.String,ss.Buffer=us.Buffer,ss.Hex=us.Hex,ss.maybe=us.maybe,ss.tuple=us.tuple,ss.UInt8=us.UInt8,ss.UInt32=us.UInt32,ss.Function=us.Function,ss.BufferN=us.BufferN,ss.Null=us.Null,ss.oneOf=us.oneOf;var fs=h.exports.Buffer;var cs={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=fs.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(os,"__esModule",{value:!0});const ls=ss,ps=cs,ds=xo,gs=Buffer.alloc(1,0);function ys(t){let e=0;for(;0===t[e];)++e;return e===t.length?gs:128&(t=t.slice(e))[0]?Buffer.concat([gs,t],1+t.length):t}function vs(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}os.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=ps.decode(t.slice(0,-1)),i=vs(n.r),o=vs(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},os.encode=function(t,e){ds({signature:ls.BufferN(64),hashType:ls.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=ys(t.slice(0,32)),o=ys(t.slice(32,64));return Buffer.concat([ps.encode(i,o),n])};var ms={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ws=ms;function bs(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ws.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ws.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},_s=ms,Ss={};for(var Is in _s){Ss[_s[Is]]=Is}var Ts=Ss;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=is,r=os,n=ss,i=cs,o=xt.exports,s=Es,u=xo;t.OPS=ms;const a=Ts,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(ns);var Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Os.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(rs,"__esModule",{value:!0});const As=ts,ks=ns,Ps=Os,Ms=xo,xs=ks.OPS;rs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ms({network:Ms.maybe(Ms.Object),output:Ms.maybe(Ms.Buffer),data:Ms.maybe(Ms.arrayOf(Ms.Buffer))},t);const r={name:"embed",network:t.network||As.bitcoin};if(Ps.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Ps.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ms.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});const Ns=ts,Bs=ns,Cs=Os,Us=Bs.OPS,Ls=xo,Ds=xt.exports,Hs=Us.OP_RESERVED;function js(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Rs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Bs.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Us.OP_0)}e=Object.assign({validate:!0},e||{}),Ls({network:Ls.maybe(Ls.Object),m:Ls.maybe(Ls.Number),n:Ls.maybe(Ls.Number),output:Ls.maybe(Ls.Buffer),pubkeys:Ls.maybe(Ls.arrayOf(Ds.isPoint)),signatures:Ls.maybe(Ls.arrayOf(r)),input:Ls.maybe(Ls.Buffer)},t);const n={network:t.network||Ns.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Bs.decompile(t),n.m=i[0]-Hs,n.n=i[i.length-2]-Hs,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Bs.compile([].concat(Hs+t.m,t.pubkeys,Hs+n.n,Us.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Bs.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Bs.compile([Us.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Ls.Number(i[0]))throw new TypeError("Output is invalid");if(!Ls.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Us.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ds.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!js(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Us.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!js(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var qs={};Object.defineProperty(qs,"__esModule",{value:!0});const Fs=ts,Ks=ns,Gs=Os,Ws=xo,Vs=Ks.OPS,$s=xt.exports;qs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ws({network:Ws.maybe(Ws.Object),output:Ws.maybe(Ws.Buffer),pubkey:Ws.maybe($s.isPoint),signature:Ws.maybe(Ks.isCanonicalScriptSignature),input:Ws.maybe(Ws.Buffer)},t);const r=Gs.value((()=>Ks.decompile(t.input))),n={name:"p2pk",network:t.network||Fs.bitcoin};if(Gs.prop(n,"output",(()=>{if(t.pubkey)return Ks.compile([t.pubkey,Vs.OP_CHECKSIG])})),Gs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Gs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Gs.prop(n,"input",(()=>{if(t.signature)return Ks.compile([t.signature])})),Gs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==Vs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!$s.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Ks.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var zs={},Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=a;function Js(t){try{return Ys("rmd160").update(t).digest()}catch(e){return Ys("ripemd160").update(t).digest()}}function Zs(t){return Ys("sha256").update(t).digest()}Xs.ripemd160=Js,Xs.sha1=function(t){return Ys("sha1").update(t).digest()},Xs.sha256=Zs,Xs.hash160=function(t){return Js(Zs(t))},Xs.hash256=function(t){return Zs(Zs(t))},Object.defineProperty(zs,"__esModule",{value:!0});const Qs=Xs,tu=ts,eu=ns,ru=Os,nu=xo,iu=eu.OPS,ou=xt.exports,su=vt;zs.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),nu({network:nu.maybe(nu.Object),address:nu.maybe(nu.String),hash:nu.maybe(nu.BufferN(20)),output:nu.maybe(nu.BufferN(25)),pubkey:nu.maybe(ou.isPoint),signature:nu.maybe(eu.isCanonicalScriptSignature),input:nu.maybe(nu.Buffer)},t);const r=ru.value((()=>{const e=su.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=ru.value((()=>eu.decompile(t.input))),i=t.network||tu.bitcoin,o={name:"p2pkh",network:i};if(ru.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),su.encode(t)})),ru.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?Qs.hash160(t.pubkey||o.pubkey):void 0)),ru.prop(o,"output",(()=>{if(o.hash)return eu.compile([iu.OP_DUP,iu.OP_HASH160,o.hash,iu.OP_EQUALVERIFY,iu.OP_CHECKSIG])})),ru.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),ru.prop(o,"signature",(()=>{if(t.input)return n()[0]})),ru.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return eu.compile([t.signature,t.pubkey])})),ru.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==iu.OP_DUP||t.output[1]!==iu.OP_HASH160||20!==t.output[2]||t.output[23]!==iu.OP_EQUALVERIFY||t.output[24]!==iu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=Qs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!eu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ou.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=Qs.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var uu={};Object.defineProperty(uu,"__esModule",{value:!0});const au=Xs,hu=ts,fu=ns,cu=Os,lu=xo,pu=fu.OPS,du=vt;uu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),lu({network:lu.maybe(lu.Object),address:lu.maybe(lu.String),hash:lu.maybe(lu.BufferN(20)),output:lu.maybe(lu.BufferN(23)),redeem:lu.maybe({network:lu.maybe(lu.Object),output:lu.maybe(lu.Buffer),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))}),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||hu.bitcoin);const n={network:r},i=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=cu.value((()=>fu.decompile(t.input))),s=cu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:fu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(cu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),du.encode(t)})),cu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?au.hash160(n.redeem.output):void 0)),cu.prop(n,"output",(()=>{if(n.hash)return fu.compile([pu.OP_HASH160,n.hash,pu.OP_EQUAL])})),cu.prop(n,"redeem",(()=>{if(t.input)return s()})),cu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return fu.compile([].concat(fu.decompile(t.redeem.input),t.redeem.output))})),cu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),cu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==pu.OP_HASH160||20!==t.output[1]||t.output[22]!==pu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=fu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=au.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=fu.decompile(t.input);if(!fu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var gu={},yu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vu={},mu=0;mu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Eu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=bu(e)^n>>5}for(e=bu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Eu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Su(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Eu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=bu(n)^s,i+=yu.charAt(s)}for(o=0;o<6;++o)n=bu(n);for(n^=1,o=0;o<6;++o){i+=yu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(gu,"__esModule",{value:!0});const Tu=Xs,Ou=ts,Au=ns,ku=Os,Pu=xo,Mu=Au.OPS,xu=xt.exports,Ru=Iu,Nu=Buffer.alloc(0);gu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Pu({address:Pu.maybe(Pu.String),hash:Pu.maybe(Pu.BufferN(20)),input:Pu.maybe(Pu.BufferN(0)),network:Pu.maybe(Pu.Object),output:Pu.maybe(Pu.BufferN(22)),pubkey:Pu.maybe(xu.isPoint),signature:Pu.maybe(Au.isCanonicalScriptSignature),witness:Pu.maybe(Pu.arrayOf(Pu.Buffer))},t);const r=ku.value((()=>{const e=Ru.decode(t.address),r=e.words.shift(),n=Ru.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Ou.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Ru.toWords(i.hash);return t.unshift(0),Ru.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Tu.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Au.compile([Mu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Nu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Mu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Tu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Au.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Tu.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0});const Cu=Xs,Uu=ts,Lu=ns,Du=Os,Hu=xo,ju=Lu.OPS,qu=xt.exports,Fu=Iu,Ku=Buffer.alloc(0);function Gu(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!qu.isPoint(t))}Bu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Hu({network:Hu.maybe(Hu.Object),address:Hu.maybe(Hu.String),hash:Hu.maybe(Hu.BufferN(32)),output:Hu.maybe(Hu.BufferN(34)),redeem:Hu.maybe({input:Hu.maybe(Hu.Buffer),network:Hu.maybe(Hu.Object),output:Hu.maybe(Hu.Buffer),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))}),input:Hu.maybe(Hu.BufferN(0)),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))},t);const r=Du.value((()=>{const e=Fu.decode(t.address),r=e.words.shift(),n=Fu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Du.value((()=>Lu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Uu.bitcoin);const o={network:i};if(Du.prop(o,"address",(()=>{if(!o.hash)return;const t=Fu.toWords(o.hash);return t.unshift(0),Fu.encode(i.bech32,t)})),Du.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Du.prop(o,"output",(()=>{if(o.hash)return Lu.compile([ju.OP_0,o.hash])})),Du.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ku,witness:t.witness.slice(0,-1)}})),Du.prop(o,"input",(()=>{if(o.witness)return Ku})),Du.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Lu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Ku,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Du.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==ju.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Lu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Lu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Gu)||t.redeem.output&&(Lu.decompile(t.redeem.output)||[]).some(Gu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Gu)||(Lu.decompile(e)||[]).some(Gu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(es,"__esModule",{value:!0});const Wu=rs;es.embed=Wu.p2data;const Vu=Rs;es.p2ms=Vu.p2ms;const $u=qs;es.p2pk=$u.p2pk;const zu=zs;es.p2pkh=zu.p2pkh;const Xu=uu;es.p2sh=Xu.p2sh;const Yu=gu;es.p2wpkh=Yu.p2wpkh;const Ju=Bu;es.p2wsh=Ju.p2wsh,Object.defineProperty(Qo,"__esModule",{value:!0});const Zu=ts,Qu=es,ta=ns,ea=ss,ra=Iu,na=vt,ia=xo;function oa(t){const e=na.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function sa(t){const e=ra.decode(t),r=ra.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}Qo.fromBase58Check=oa,Qo.fromBech32=sa,Qo.toBase58Check=function(t,e){ia(ea.tuple(ea.Hash160bit,ea.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),na.encode(r)},Qo.toBech32=function(t,e,r){const n=ra.toWords(t);return n.unshift(e),ra.encode(r,n)},Qo.fromOutputScript=function(t,e){e=e||Zu.bitcoin;try{return Qu.p2pkh({output:t,network:e}).address}catch(t){}try{return Qu.p2sh({output:t,network:e}).address}catch(t){}try{return Qu.p2wpkh({output:t,network:e}).address}catch(t){}try{return Qu.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ta.toASM(t)+" has no matching Address")},Qo.toOutputScript=function(t,e){let r,n;e=e||Zu.bitcoin;try{r=oa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return Qu.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return Qu.p2sh({hash:r.hash}).output}else{try{n=sa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return Qu.p2wpkh({hash:n.data}).output;if(32===n.data.length)return Qu.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ua={},aa=u.randomBytes;Object.defineProperty(ua,"__esModule",{value:!0});const ha=ts,fa=ss,ca=xt.exports,la=aa,pa=xo,da=Co,ga=pa.maybe(pa.compile({compressed:fa.maybe(fa.Boolean),network:fa.maybe(fa.Network)}));class ya{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ha.bitcoin,void 0!==e&&(this.__Q=ca.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=ca.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return da.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return ca.sign(t,this.__D);{let e=ca.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=ca.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return ca.verify(t,this.publicKey,e)}}function va(t,e){if(pa(fa.Buffer256bit,t),!ca.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return pa(ga,e),new ya(t,void 0,e)}ua.fromPrivateKey=va,ua.fromPublicKey=function(t,e){return pa(ca.isPoint,t),pa(ga,e),new ya(void 0,t,e)},ua.fromWIF=function(t,e){const r=da.decode(t),n=r.version;if(fa.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ha.bitcoin,n!==e.wif)throw new Error("Invalid network version");return va(r.privateKey,{compressed:r.compressed,network:e})},ua.makeRandom=function(t){pa(ga,t),void 0===t&&(t={});const e=t.rng||la;let r;do{r=e(32),pa(fa.Buffer256bit,r)}while(!ca.isPrivate(r));return va(r,t)};var ma={},wa={},ba=h.exports.Buffer;function Ea(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function _a(t){return Ea(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Sa={encode:function t(e,r,n){if(Ea(e),r||(r=ba.allocUnsafe(_a(e))),!ba.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!ba.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ea(o),o},encodingLength:_a};Object.defineProperty(wa,"__esModule",{value:!0});const Ia=ss,Ta=xo,Oa=Sa;function Aa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Aa(n+r,9007199254740991),n+r}function Pa(t,e,r){return Aa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}wa.readUInt64LE=ka,wa.writeUInt64LE=Pa,wa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};wa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ta(Ia.tuple(Ia.Buffer,Ia.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Oa.decode(this.buffer,this.offset);return this.offset+=Oa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+La.encodingLength(this.ins.length)+La.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Da(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Da(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return La.encodingLength(e)+t.reduce(((t,e)=>t+Da(e)),0)}(e.witness)),0):0)}clone(){const t=new Wa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return Fa;const n=Na.compile(Na.decompile(e).filter((t=>t!==Ba.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Wa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Wa.SIGHASH_SINGLE){if(t>=this.outs.length)return Fa;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Wa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=Ha})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ra.hash256(o)}hashForWitnessV0(t,e,r,n){Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=qa,u=qa,a=qa;if(n&Wa.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ra.hash256(o)),n&Wa.SIGHASH_ANYONECANPAY||(31&n)===Wa.SIGHASH_SINGLE||(31&n)===Wa.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ra.hash256(o)),(31&n)!==Wa.SIGHASH_SINGLE&&(31&n)!==Wa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Da(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ra.hash256(o)}else if((31&n)===Wa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Wa.DEFAULT_SEQUENCE=4294967295,Wa.SIGHASH_ALL=1,Wa.SIGHASH_NONE=2,Wa.SIGHASH_SINGLE=3,Wa.SIGHASH_ANYONECANPAY=128,Wa.ADVANCED_TRANSACTION_MARKER=0,Wa.ADVANCED_TRANSACTION_FLAG=1,Ma.Transaction=Wa;Object.defineProperty(ma,"__esModule",{value:!0});const Va=wa,$a=Xs,za=Ma,Xa=ss,Ya=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=za.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Ja([{getHash:Xa.Function}],t),0===t.length)throw Qa;if(e&&!rh(t))throw th;const r=t.map((t=>t.getHash(e))),n=Ya(r,$a.hash256);return e?$a.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!rh(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+Za.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return $a.hash256(this.toBuffer(!0))}getId(){return Va.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new Va.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(Za.encode(this.transactions.length,e,r.offset),r.offset+=Za.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=Va.reverseBuffer(this.getHash()),e=eh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw Qa;const t=eh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw Qa;if(!this.hasWitnessCommit())throw th;const t=eh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function rh(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ma.Block=eh;var nh={},ih={},oh={},sh={},uh={},ah={},hh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(hh);var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const ch=hh;fh.decode=function(t){if(t.key[0]!==ch.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},fh.encode=function(t){const e=Buffer.from([ch.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},fh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",fh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},fh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=hh;lh.encode=function(t){return{key:Buffer.from([ph.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=hh;dh.decode=function(t){if(t.key[0]!==gh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},dh.encode=function(t){return{key:Buffer.from([gh.InputTypes.FINAL_SCRIPTSIG]),value:t}},dh.expected="Buffer",dh.check=function(t){return Buffer.isBuffer(t)},dh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var yh={};Object.defineProperty(yh,"__esModule",{value:!0});const vh=hh;yh.decode=function(t){if(t.key[0]!==vh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},yh.encode=function(t){return{key:Buffer.from([vh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},yh.expected="Buffer",yh.check=function(t){return Buffer.isBuffer(t)},yh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=hh;mh.decode=function(t){if(t.key[0]!==wh.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([wh.InputTypes.NON_WITNESS_UTXO]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=hh;bh.decode=function(t){if(t.key[0]!==Eh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},bh.encode=function(t){const e=Buffer.from([Eh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},bh.expected="{ pubkey: Buffer; signature: Buffer; }",bh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},bh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=hh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},_h.encode=function(t){return{key:Buffer.from([Sh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},_h.expected="string",_h.check=function(t){return"string"==typeof t},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=hh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ih.encode=function(t){const e=Buffer.from([Th.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ih.expected="number",Ih.check=function(t){return"number"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Oh={},Ah={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Ph(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Mh(t){return Ph(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Ph(e),r||(r=Buffer.allocUnsafe(Mh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Ph(i),i}},kh.encodingLength=Mh,Object.defineProperty(Ah,"__esModule",{value:!0});const xh=kh;function Rh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Nh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ah.range=t=>[...Array(t).keys()],Ah.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Dh={};Object.defineProperty(Dh,"__esModule",{value:!0}),Dh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var Hh={};Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(ah,"__esModule",{value:!0});const qh=hh,Fh=dh,Kh=yh,Gh=mh,Wh=bh,Vh=_h,$h=Ih,zh=Oh,Xh=Lh,Yh=Dh,Jh=Hh,Zh=jh,Qh={unsignedTx:lh,globalXpub:fh,checkPubkey:Yh.makeChecker([])};ah.globals=Qh;const tf={nonWitnessUtxo:Gh,partialSig:Wh,sighashType:$h,finalScriptSig:Fh,finalScriptWitness:Kh,porCommitment:Vh,witnessUtxo:zh,bip32Derivation:Xh.makeConverter(qh.InputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.InputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.InputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.InputTypes.PARTIAL_SIG,qh.InputTypes.BIP32_DERIVATION])};ah.inputs=tf;const ef={bip32Derivation:Xh.makeConverter(qh.OutputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.OutputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.OutputTypes.BIP32_DERIVATION])};ah.outputs=ef,Object.defineProperty(uh,"__esModule",{value:!0});const rf=ah,nf=Ah,of=kh,sf=hh;function uf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function af(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case sf.GlobalTypes.UNSIGNED_TX:if(uf("global",t.key,sf.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case sf.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(rf.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of nf.range(s)){const e={};for(const n of r[t])switch(rf.inputs.checkPubkey(n),n.key[0]){case sf.InputTypes.NON_WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=rf.inputs.nonWitnessUtxo.decode(n);break;case sf.InputTypes.WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=rf.inputs.witnessUtxo.decode(n);break;case sf.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(rf.inputs.partialSig.decode(n));break;case sf.InputTypes.SIGHASH_TYPE:if(uf("input",n.key,sf.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=rf.inputs.sighashType.decode(n);break;case sf.InputTypes.REDEEM_SCRIPT:if(uf("input",n.key,sf.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=rf.inputs.redeemScript.decode(n);break;case sf.InputTypes.WITNESS_SCRIPT:if(uf("input",n.key,sf.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=rf.inputs.witnessScript.decode(n);break;case sf.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.inputs.bip32Derivation.decode(n));break;case sf.InputTypes.FINAL_SCRIPTSIG:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=rf.inputs.finalScriptSig.decode(n);break;case sf.InputTypes.FINAL_SCRIPTWITNESS:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=rf.inputs.finalScriptWitness.decode(n);break;case sf.InputTypes.POR_COMMITMENT:uf("input",n.key,sf.InputTypes.POR_COMMITMENT),e.porCommitment=rf.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of nf.range(u)){const e={};for(const r of n[t])switch(rf.outputs.checkPubkey(r),r.key[0]){case sf.OutputTypes.REDEEM_SCRIPT:if(uf("output",r.key,sf.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=rf.outputs.redeemScript.decode(r);break;case sf.OutputTypes.WITNESS_SCRIPT:if(uf("output",r.key,sf.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=rf.outputs.witnessScript.decode(r);break;case sf.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}uh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=of.decode(t,r);r+=of.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===sf.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of nf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of nf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return af(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},uh.checkKeyBuffer=uf,uh.psbtFromKeyVals=af;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});const ff=ah,cf=Ah;hf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=df({globalMap:t,inputs:e,outputs:r}),s=cf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(cf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const lf=(t,e)=>t.key.compare(e.key);function pf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(lf)}function df({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:pf(t,ff.globals),inputKeyVals:e.map((t=>pf(t,ff.inputs))),outputKeyVals:r.map((t=>pf(t,ff.outputs)))}}hf.psbtToKeyVals=df,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(uh),e(hf)}(sh),Object.defineProperty(oh,"__esModule",{value:!0});const gf=sh;function yf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function vf(t){return t.globalMap.unsignedTx}function mf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}oh.combine=function(t){const e=t[0],r=gf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=vf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=mf(r.globalKeyVals),s=r.inputKeyVals.map(mf),u=r.outputKeyVals.map(mf);for(const t of n){const e=vf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=gf.psbtToKeyVals(t);mf(n.globalKeyVals).forEach(yf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return gf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var wf={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ah;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(wf),Object.defineProperty(ih,"__esModule",{value:!0});const bf=oh,Ef=sh,_f=hh,Sf=wf;ih.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ef.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ef.psbtToBuffer(this)}updateGlobal(t){return Sf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.updateInput(e,r),this}updateOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Sf.checkHasKey(t,this.globalMap.unknownKeyVals,Sf.getEnumLength(_f.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Sf.checkForInput(this.inputs,t);Sf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=bf.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(nh,"__esModule",{value:!0});const If=ih,Tf=kh,Of=wf,Af=Qo,kf=wa,Pf=Xs,Mf=ua,xf=es,Rf=ns,Nf=Ma,Bf={network:ts.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new If.Psbt(new Lf)){this.data=e,this.opts=Object.assign({},Bf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=If.Psbt.fromBuffer(t,Uf),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{Zf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Af.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Xf(t),this.opts.maximumFeeRate=t}setVersion(t){Xf(t),Yf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Xf(t),Yf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Xf(e),Yf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Yf(this.data.inputs,"addInput"),t.witnessScript&&gc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);Zf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&hc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Yf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Af.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(jf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return fc(this.data.inputs,r,e,!0),r}getFeeRate(){return rc("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return rc("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Of.checkForInput(this.data.inputs,0),mc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=nc){const r=Of.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=cc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Wf(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Rf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Of.checkForInput(this.data.inputs,t),r=dc(lc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Rf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||pc(r)||(n=r,Rf.isCanonicalScriptSignature(n)))return;var n;if(!Rf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=uc(t),r=e[e.length-1];if(pc(r))return;if(!Rf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+vc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=lc(r,e,n),{meaningfulScript:o}=dc(i,r,"input",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Of.checkForInput(this.data.inputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=dc(i,r,"output",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Of.checkForOutput(this.data.outputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Of.checkForInput(this.data.inputs,0);return mc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Rf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?oc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Jf(e.pubkey,h,"verify");const f=Mf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of mc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return sc(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=sc(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Rf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Rf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Df(this.__CACHE),this.data.toBuffer()}toHex(){return Df(this.__CACHE),this.data.toHex()}toBase64(){return Df(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&gc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&hc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}nh.Psbt=Cf;const Uf=t=>new Lf(t);class Lf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Nf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Df(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Hf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Mf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function jf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function qf(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Ff=qf(xf.p2ms),Kf=qf(xf.p2pk),Gf=qf(xf.p2pkh),Wf=qf(xf.p2wpkh),Vf=qf(xf.p2wsh),$f=qf(xf.p2sh);function zf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Xf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Yf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Rf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Rf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Rf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Rf.signature.decode(t.signature),i=[];n&Nf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Nf.Transaction.SIGHASH_ALL:break;case Nf.Transaction.SIGHASH_SINGLE:case Nf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Jf(t,e,r){if(!yc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function Zf(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function Qf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const tc=Qf(xf.p2sh,"Redeem script"),ec=Qf(xf.p2wsh,"Witness script");function rc(t,e,r,n){if(!r.every(jf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),fc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function nc(t,e,r,n,i,o){const s=vc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Hf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return Hf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=ac(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function ic(t,e,r,n,i){const o=Of.checkForInput(t,e),{hash:s,sighashType:u,script:a}=oc(e,o,n,!1,i);return Jf(r,a,"sign"),{hash:s,sighashType:u}}function oc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Nf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Nf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Nf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Nf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Nf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=cc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=dc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Wf(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function sc(t,e,r){const n=Of.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function uc(t){let e=0;function r(){const r=Tf.decode(t,e);return e+=Tf.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=uc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=cc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function cc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||hc(t,e,r),n[r]}function lc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return cc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function pc(t){return 33===t.length&&Rf.isCanonicalPubKey(t)}function dc(t,e,r,n,i){const o=$f(t),s=o&&n&&Vf(n),u=Vf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,tc(e,t,n,r),ec(e,n,i,r),gc(a)):u?(a=i,ec(e,t,i,r),gc(a)):o?(a=n,tc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function gc(t){if(Wf(t)||$f(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function yc(t,e){const r=Pf.hash160(t),n=Rf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function vc(t){return Wf(t)?"witnesspubkeyhash":Gf(t)?"pubkeyhash":Ff(t)?"multisig":Kf(t)?"pubkey":"nonstandard"}function mc(t){return[...Array(t).keys()]}var wc={},bc={},Ec={},_c={};Object.defineProperty(_c,"__esModule",{value:!0});const Sc=ns,Ic=ns;function Tc(t){return t===Ic.OPS.OP_0||Sc.isCanonicalScriptSignature(t)}function Oc(t,e){const r=Sc.decompile(t);return!(r.length<2)&&(r[0]===Ic.OPS.OP_0&&(e?r.slice(1).every(Tc):r.slice(1).every(Sc.isCanonicalScriptSignature)))}_c.check=Oc,Oc.toJSON=()=>"multisig input";var Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const kc=ns,Pc=ns,Mc=ss,xc=Pc.OPS.OP_RESERVED;function Rc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Pc.OPS.OP_CHECKMULTISIG)return!1;if(!Mc.Number(r[0]))return!1;if(!Mc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Ac.check=Rc,Rc.toJSON=()=>"multi-sig output",Object.defineProperty(Ec,"__esModule",{value:!0});const Nc=_c;Ec.input=Nc;const Bc=Ac;Ec.output=Bc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Uc=ns,Lc=Uc.OPS;function Dc(t){const e=Uc.compile(t);return e.length>1&&e[0]===Lc.OP_RETURN}Cc.check=Dc,Dc.toJSON=()=>"null data output";const Hc={check:Dc};Cc.output=Hc;var jc={},qc={};Object.defineProperty(qc,"__esModule",{value:!0});const Fc=ns;function Kc(t){const e=Fc.decompile(t);return 1===e.length&&Fc.isCanonicalScriptSignature(e[0])}qc.check=Kc,Kc.toJSON=()=>"pubKey input";var Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});const Wc=ns,Vc=ns;function $c(t){const e=Wc.decompile(t);return 2===e.length&&Wc.isCanonicalPubKey(e[0])&&e[1]===Vc.OPS.OP_CHECKSIG}Gc.check=$c,$c.toJSON=()=>"pubKey output",Object.defineProperty(jc,"__esModule",{value:!0});const zc=qc;jc.input=zc;const Xc=Gc;jc.output=Xc;var Yc={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});const Zc=ns;function Qc(t){const e=Zc.decompile(t);return 2===e.length&&Zc.isCanonicalScriptSignature(e[0])&&Zc.isCanonicalPubKey(e[1])}Jc.check=Qc,Qc.toJSON=()=>"pubKeyHash input";var tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=ns,rl=ns;function nl(t){const e=el.compile(t);return 25===e.length&&e[0]===rl.OPS.OP_DUP&&e[1]===rl.OPS.OP_HASH160&&20===e[2]&&e[23]===rl.OPS.OP_EQUALVERIFY&&e[24]===rl.OPS.OP_CHECKSIG}tl.check=nl,nl.toJSON=()=>"pubKeyHash output",Object.defineProperty(Yc,"__esModule",{value:!0});const il=Jc;Yc.input=il;const ol=tl;Yc.output=ol;var sl={},ul={},al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=ns,fl=ns;function cl(t){const e=hl.compile(t);return 22===e.length&&e[0]===fl.OPS.OP_0&&20===e[1]}al.check=cl,cl.toJSON=()=>"Witness pubKeyHash output";var ll={};Object.defineProperty(ll,"__esModule",{value:!0});const pl=ns,dl=ns;function gl(t){const e=pl.compile(t);return 34===e.length&&e[0]===dl.OPS.OP_0&&32===e[1]}ll.check=gl,gl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(ul,"__esModule",{value:!0});const yl=ns,vl=Ec,ml=jc,wl=Yc,bl=al,El=ll;function _l(t,e){const r=yl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=yl.decompile(yl.compile(r.slice(0,-1))),o=yl.decompile(n);return!!o&&(!!yl.isPushOnly(i)&&(1===r.length?El.check(o)||bl.check(o):!(!wl.input.check(i)||!wl.output.check(o))||(!(!vl.input.check(i,e)||!vl.output.check(o))||!(!ml.input.check(i)||!ml.output.check(o)))))}ul.check=_l,_l.toJSON=()=>"scriptHash input";var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Il=ns,Tl=ns;function Ol(t){const e=Il.compile(t);return 23===e.length&&e[0]===Tl.OPS.OP_HASH160&&20===e[1]&&e[22]===Tl.OPS.OP_EQUAL}Sl.check=Ol,Ol.toJSON=()=>"scriptHash output",Object.defineProperty(sl,"__esModule",{value:!0});const Al=ul;sl.input=Al;const kl=Sl;sl.output=kl;var Pl={},Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const xl=ns,Rl=ns,Nl=ss,Bl=xo,Cl=Buffer.from("aa21a9ed","hex");function Ul(t){const e=xl.compile(t);return e.length>37&&e[0]===Rl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Ml.check=Ul,Ul.toJSON=()=>"Witness commitment output",Ml.encode=function(t){Bl(Nl.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Rl.OPS.OP_RETURN,e])},Ml.decode=function(t){return Bl(Ul,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Pl,"__esModule",{value:!0});const Ll=Ml;Pl.output=Ll;var Dl={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const jl=ns;function ql(t){const e=jl.decompile(t);return 2===e.length&&jl.isCanonicalScriptSignature(e[0])&&function(t){return jl.isCanonicalPubKey(t)&&33===t.length}(e[1])}Hl.check=ql,ql.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Dl,"__esModule",{value:!0});const Fl=Hl;Dl.input=Fl;const Kl=al;Dl.output=Kl;var Gl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Vl=ns,$l=xo,zl=Ec,Xl=jc,Yl=Yc;function Jl(t,e){if($l($l.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=Vl.decompile(r);if(!n||0===n.length)return!1;const i=Vl.compile(t.slice(0,-1));return!(!Yl.input.check(i)||!Yl.output.check(n))||(!(!zl.input.check(i,e)||!zl.output.check(n))||!(!Xl.input.check(i)||!Xl.output.check(n)))}Wl.check=Jl,Jl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Gl,"__esModule",{value:!0});const Zl=Wl;Gl.input=Zl;const Ql=ll;Gl.output=Ql,Object.defineProperty(bc,"__esModule",{value:!0});const tp=ns,ep=Ec,rp=Cc,np=jc,ip=Yc,op=sl,sp=Pl,up=Dl,ap=Gl,hp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};bc.types=hp,bc.output=function(t){if(up.output.check(t))return hp.P2WPKH;if(ap.output.check(t))return hp.P2WSH;if(ip.output.check(t))return hp.P2PKH;if(op.output.check(t))return hp.P2SH;const e=tp.decompile(t);if(!e)throw new TypeError("Invalid script");return ep.output.check(e)?hp.P2MS:np.output.check(e)?hp.P2PK:sp.output.check(e)?hp.WITNESS_COMMITMENT:rp.output.check(e)?hp.NULLDATA:hp.NONSTANDARD},bc.input=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return ip.input.check(r)?hp.P2PKH:op.input.check(r,e)?hp.P2SH:ep.input.check(r,e)?hp.P2MS:np.input.check(r)?hp.P2PK:hp.NONSTANDARD},bc.witness=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return up.input.check(r)?hp.P2WPKH:ap.input.check(r,e)?hp.P2WSH:hp.NONSTANDARD},Object.defineProperty(wc,"__esModule",{value:!0});const fp=Qo,cp=wa,lp=bc,pp=Xs,dp=ua,gp=ts,yp=es,vp=ns,mp=ns,wp=Ma,bp=ss,Ep=xo,_p=lp.types,Sp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Ip(t,e,r){try{Ep(t,e)}catch(t){throw new Error(r)}}class Tp{constructor(t=gp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new wp.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Tp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==_p.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=dp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=vp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ep(Ep.maybe(Ep.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ep(bp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ep(bp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=cp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof wp.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=fp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=vp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Sp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Ip(Ep.Number,e.vin,"sign must include vin parameter as Number (input index)"),Ip(bp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Ip(Ep.maybe(Ep.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires witnessScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||wp.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Pp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ep(bp.Satoshi,a),l.value=a}if(!Pp(l)){const t=function(t,e,r,n){if(r&&n){const i=yp.p2wsh({redeem:{output:n}}),o=yp.p2wsh({output:r}),s=yp.p2sh({redeem:{output:r}}),u=yp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ap(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===_p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:_p.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:_p.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=yp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=yp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ap(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+vp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===_p.P2WPKH&&(o=yp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:_p.P2SH,prevOutScript:n.output,hasWitness:i.type===_p.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=yp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=yp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ap(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===_p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:_p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===_p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===_p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ap(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+vp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===_p.P2WPKH&&(n=yp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===_p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=yp.p2pkh({pubkey:e}).output;return{prevOutType:_p.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:_p.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Pp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(wp.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Op(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ap(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||lp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===_p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Mp(t)&wp.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===wp.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Mp(t)&wp.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Mp(r);return n===wp.Transaction.SIGHASH_NONE||n===wp.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Op(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=lp.input(t,!0),i=lp.witness(e,!0);n===_p.NONSTANDARD&&(n=void 0),i===_p.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case _p.P2WPKH:{const{output:t,pubkey:r,signature:n}=yp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:_p.P2WPKH,pubkeys:[r],signatures:[n]}}case _p.P2PKH:{const{output:e,pubkey:r,signature:n}=yp.p2pkh({input:t});return{prevOutScript:e,prevOutType:_p.P2PKH,pubkeys:[r],signatures:[n]}}case _p.P2PK:{const{signature:e}=yp.p2pk({input:t});return{prevOutType:_p.P2PK,pubkeys:[void 0],signatures:[e]}}case _p.P2MS:{const{m:e,pubkeys:r,signatures:i}=yp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:_p.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===_p.P2SH){const{output:r,redeem:n}=yp.p2sh({input:t,witness:e}),i=lp.output(n.output),o=Op(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:_p.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===_p.P2WSH){const{output:r,redeem:n}=yp.p2wsh({input:t,witness:e}),i=lp.output(n.output);let o;return o=i===_p.P2WPKH?Op(n.input,n.witness,i):Op(vp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:_p.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:_p.NONSTANDARD,prevOutScript:t}}function Ap(t,e){Ep(bp.Buffer,t);const r=lp.output(t);switch(r){case _p.P2PKH:{if(!e)return{type:r};const n=yp.p2pkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2WPKH:{if(!e)return{type:r};const n=yp.p2wpkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2PK:return{type:r,pubkeys:[yp.p2pk({output:t}).pubkey],signatures:[void 0]};case _p.P2MS:{const e=yp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case _p.P2PKH:if(0===n.length)break;if(0===i.length)break;return yp.p2pkh({pubkey:n[0],signature:i[0]});case _p.P2WPKH:if(0===n.length)break;if(0===i.length)break;return yp.p2wpkh({pubkey:n[0],signature:i[0]});case _p.P2PK:if(0===n.length)break;if(0===i.length)break;return yp.p2pk({signature:i[0]});case _p.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||mp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return yp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case _p.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return yp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case _p.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return yp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Pp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Mp(t){return t.readUInt8(t.length-1)}wc.TransactionBuilder=Tp,Object.defineProperty(It,"__esModule",{value:!0});const xp=Tt;It.bip32=xp;const Rp=Qo;It.address=Rp;const Np=Xs;var Bp=It.crypto=Np;const Cp=ua;It.ECPair=Cp;const Up=ts;It.networks=Up;const Lp=es;It.payments=Lp;const Dp=ns;It.script=Dp;var Hp=ma;It.Block=Hp.Block;var jp=nh;It.Psbt=jp.Psbt;var qp=ns;It.opcodes=qp.OPS;var Fp=Ma;It.Transaction=Fp.Transaction;var Kp=wc;It.TransactionBuilder=Kp.TransactionBuilder;var Gp={exports:{}};var Wp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var Vp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Wp,n=Vp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Gp,Gp.exports);const $p=["includePrerelease","loose","rtl"];var zp=t=>t?"object"!=typeof t?{loose:!0}:$p.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Xp=/^[0-9]+$/,Yp=(t,e)=>{const r=Xp.test(t),n=Xp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tYp(e,t)};const Zp=Vp,{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:td}=Wp,{re:ed,t:rd}=Gp.exports,nd=zp,{compareIdentifiers:id}=Jp;class od{constructor(t,e){if(e=nd(e),t instanceof od){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);Zp("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?ed[rd.LOOSE]:ed[rd.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>td||this.major<0)throw new TypeError("Invalid major version");if(this.minor>td||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>td||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var sd=od;const{MAX_LENGTH:ud}=Wp,{re:ad,t:hd}=Gp.exports,fd=sd,cd=zp;var ld=(t,e)=>{if(e=cd(e),t instanceof fd)return t;if("string"!=typeof t)return null;if(t.length>ud)return null;if(!(e.loose?ad[hd.LOOSE]:ad[hd.FULL]).test(t))return null;try{return new fd(t,e)}catch(t){return null}};const pd=ld;var dd=(t,e)=>{const r=pd(t,e);return r?r.version:null};const gd=ld;var yd=(t,e)=>{const r=gd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const vd=sd;var md=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new vd(t,r).inc(e,n).version}catch(t){return null}};const wd=sd;var bd=(t,e,r)=>new wd(t,r).compare(new wd(e,r));const Ed=bd;var _d=(t,e,r)=>0===Ed(t,e,r);const Sd=ld,Id=_d;var Td=(t,e)=>{if(Id(t,e))return null;{const r=Sd(t),n=Sd(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Od=sd;var Ad=(t,e)=>new Od(t,e).major;const kd=sd;var Pd=(t,e)=>new kd(t,e).minor;const Md=sd;var xd=(t,e)=>new Md(t,e).patch;const Rd=ld;var Nd=(t,e)=>{const r=Rd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Bd=bd;var Cd=(t,e,r)=>Bd(e,t,r);const Ud=bd;var Ld=(t,e)=>Ud(t,e,!0);const Dd=sd;var Hd=(t,e,r)=>{const n=new Dd(t,r),i=new Dd(e,r);return n.compare(i)||n.compareBuild(i)};const jd=Hd;var qd=(t,e)=>t.sort(((t,r)=>jd(t,r,e)));const Fd=Hd;var Kd=(t,e)=>t.sort(((t,r)=>Fd(r,t,e)));const Gd=bd;var Wd=(t,e,r)=>Gd(t,e,r)>0;const Vd=bd;var $d=(t,e,r)=>Vd(t,e,r)<0;const zd=bd;var Xd=(t,e,r)=>0!==zd(t,e,r);const Yd=bd;var Jd=(t,e,r)=>Yd(t,e,r)>=0;const Zd=bd;var Qd=(t,e,r)=>Zd(t,e,r)<=0;const tg=_d,eg=Xd,rg=Wd,ng=Jd,ig=$d,og=Qd;var sg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return tg(t,r,n);case"!=":return eg(t,r,n);case">":return rg(t,r,n);case">=":return ng(t,r,n);case"<":return ig(t,r,n);case"<=":return og(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const ug=sd,ag=ld,{re:hg,t:fg}=Gp.exports;var cg=(t,e)=>{if(t instanceof ug)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=hg[fg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),hg[fg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;hg[fg.COERCERTL].lastIndex=-1}else r=t.match(hg[fg.COERCE]);return null===r?null:ag(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},lg=pg;function pg(t){var e=this;if(e instanceof pg||(e=new pg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},pg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},pg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},pg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},pg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new pg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},pg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Mg=(t,e,r)=>{const n=t[Ag].get(e);if(n){const e=n.value;if(xg(t,e)){if(Ng(t,n),!t[_g])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Og].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Sg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Sg]&&r>t[Sg]},Rg=t=>{if(t[bg]>t[wg])for(let e=t[Og].tail;t[bg]>t[wg]&&null!==e;){const r=e.prev;Ng(t,e),e=r}},Ng=(t,e)=>{if(e){const r=e.value;t[Ig]&&t[Ig](r.key,r.value),t[bg]-=r.length,t[Ag].delete(r.key),t[Og].removeNode(e)}};class Bg{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Ng(t,r),t[_g]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Ug=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[wg]=t.max||1/0;const e=t.length||Pg;if(this[Eg]="function"!=typeof e?Pg:e,this[_g]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Sg]=t.maxAge||0,this[Ig]=t.dispose,this[Tg]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[wg]=t||1/0,Rg(this)}get max(){return this[wg]}set allowStale(t){this[_g]=!!t}get allowStale(){return this[_g]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Sg]=t,Rg(this)}get maxAge(){return this[Sg]}set lengthCalculator(t){"function"!=typeof t&&(t=Pg),t!==this[Eg]&&(this[Eg]=t,this[bg]=0,this[Og].forEach((t=>{t.length=this[Eg](t.value,t.key),this[bg]+=t.length}))),Rg(this)}get lengthCalculator(){return this[Eg]}get length(){return this[bg]}get itemCount(){return this[Og].length}rforEach(t,e){e=e||this;for(let r=this[Og].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Og].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Og].toArray().map((t=>t.key))}values(){return this[Og].toArray().map((t=>t.value))}reset(){this[Ig]&&this[Og]&&this[Og].length&&this[Og].forEach((t=>this[Ig](t.key,t.value))),this[Ag]=new Map,this[Og]=new mg,this[bg]=0}dump(){return this[Og].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Og]}set(t,e,r){if((r=r||this[Sg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Eg](e,t);if(this[Ag].has(t)){if(i>this[wg])return Ng(this,this[Ag].get(t)),!1;const o=this[Ag].get(t).value;return this[Ig]&&(this[Tg]||this[Ig](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[bg]+=i-o.length,o.length=i,this.get(t),Rg(this),!0}const o=new Bg(t,e,i,n,r);return o.length>this[wg]?(this[Ig]&&this[Ig](t,e),!1):(this[bg]+=o.length,this[Og].unshift(o),this[Ag].set(t,this[Og].head),Rg(this),!0)}has(t){if(!this[Ag].has(t))return!1;const e=this[Ag].get(t).value;return!xg(this,e)}get(t){return Mg(this,t,!0)}peek(t){return Mg(this,t,!1)}pop(){const t=this[Og].tail;return t?(Ng(this,t),t.value):null}del(t){Ng(this,this[Ag].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ag].forEach(((t,e)=>Mg(this,e,!1)))}};class Lg{constructor(t,e){if(e=jg(e),t instanceof Lg)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Lg(t.raw,e);if(t instanceof qg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Xg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Yg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=Hg.get(e);if(r)return r;const n=this.options.loose,i=n?Gg[Wg.HYPHENRANGELOOSE]:Gg[Wg.HYPHENRANGE];t=t.replace(i,ay(this.options.includePrerelease)),Fg("hyphen replace",t),t=t.replace(Gg[Wg.COMPARATORTRIM],Vg),Fg("comparator trim",t,Gg[Wg.COMPARATORTRIM]),t=(t=(t=t.replace(Gg[Wg.TILDETRIM],$g)).replace(Gg[Wg.CARETTRIM],zg)).split(/\s+/).join(" ");const o=n?Gg[Wg.COMPARATORLOOSE]:Gg[Wg.COMPARATOR],s=t.split(" ").map((t=>Zg(t,this.options))).join(" ").split(/\s+/).map((t=>uy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new qg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Xg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return Hg.set(e,a),a}intersects(t,e){if(!(t instanceof Lg))throw new TypeError("a Range is required");return this.set.some((r=>Jg(r,e)&&t.set.some((t=>Jg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Kg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Yg=t=>""===t.value,Jg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},Zg=(t,e)=>(Fg("comp",t,e),t=ry(t,e),Fg("caret",t),t=ty(t,e),Fg("tildes",t),t=iy(t,e),Fg("xrange",t),t=sy(t,e),Fg("stars",t),t),Qg=t=>!t||"x"===t.toLowerCase()||"*"===t,ty=(t,e)=>t.trim().split(/\s+/).map((t=>ey(t,e))).join(" "),ey=(t,e)=>{const r=e.loose?Gg[Wg.TILDELOOSE]:Gg[Wg.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Fg("tilde",t,e,r,n,i,o),Qg(r)?s="":Qg(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Qg(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Fg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Fg("tilde return",s),s}))},ry=(t,e)=>t.trim().split(/\s+/).map((t=>ny(t,e))).join(" "),ny=(t,e)=>{Fg("caret",t,e);const r=e.loose?Gg[Wg.CARETLOOSE]:Gg[Wg.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Fg("caret",t,e,r,i,o,s),Qg(r)?u="":Qg(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Qg(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Fg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Fg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Fg("caret return",u),u}))},iy=(t,e)=>(Fg("replaceXRanges",t,e),t.split(/\s+/).map((t=>oy(t,e))).join(" ")),oy=(t,e)=>{t=t.trim();const r=e.loose?Gg[Wg.XRANGELOOSE]:Gg[Wg.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Fg("xRange",t,r,n,i,o,s,u);const a=Qg(i),h=a||Qg(o),f=h||Qg(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Fg("xRange return",r),r}))},sy=(t,e)=>(Fg("replaceStars",t,e),t.trim().replace(Gg[Wg.STAR],"")),uy=(t,e)=>(Fg("replaceGTE0",t,e),t.trim().replace(Gg[e.includePrerelease?Wg.GTE0PRE:Wg.GTE0],"")),ay=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=Qg(n)?"":Qg(i)?`>=${n}.0.0${t?"-0":""}`:Qg(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Qg(h)?"":Qg(f)?`<${+h+1}.0.0-0`:Qg(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),hy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},fy=Symbol("SemVer ANY");class cy{static get ANY(){return fy}constructor(t,e){if(e=py(e),t instanceof cy){if(t.loose===!!e.loose)return t;t=t.value}vy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===fy?this.value="":this.value=this.operator+this.semver.version,vy("comp",this)}parse(t){const e=this.options.loose?dy[gy.COMPARATORLOOSE]:dy[gy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new my(r[2],this.options.loose):this.semver=fy}toString(){return this.value}test(t){if(vy("Comparator.test",t,this.options.loose),this.semver===fy||t===fy)return!0;if("string"==typeof t)try{t=new my(t,this.options)}catch(t){return!1}return yy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof cy))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new wy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new wy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=yy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=yy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var ly=cy;const py=zp,{re:dy,t:gy}=Gp.exports,yy=sg,vy=Vp,my=sd,wy=Dg,by=Dg;var Ey=(t,e,r)=>{try{e=new by(e,r)}catch(t){return!1}return e.test(t)};const _y=Dg;var Sy=(t,e)=>new _y(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Iy=sd,Ty=Dg;var Oy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ty(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Iy(n,r)))})),n};const Ay=sd,ky=Dg;var Py=(t,e,r)=>{let n=null,i=null,o=null;try{o=new ky(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Ay(n,r)))})),n};const My=sd,xy=Dg,Ry=Wd;var Ny=(t,e)=>{t=new xy(t,e);let r=new My("0.0.0");if(t.test(r))return r;if(r=new My("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new My(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Ry(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Ry(r,i)||(r=i)}return r&&t.test(r)?r:null};const By=Dg;var Cy=(t,e)=>{try{return new By(t,e).range||"*"}catch(t){return null}};const Uy=sd,Ly=ly,{ANY:Dy}=Ly,Hy=Dg,jy=Ey,qy=Wd,Fy=$d,Ky=Qd,Gy=Jd;var Wy=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Uy(t,n),e=new Hy(e,n),r){case">":i=qy,o=Ky,s=Fy,u=">",a=">=";break;case"<":i=Fy,o=Gy,s=qy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jy(t,e,n))return!1;for(let r=0;r{t.semver===Dy&&(t=new Ly(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const Vy=Wy;var $y=(t,e,r)=>Vy(t,e,">",r);const zy=Wy;var Xy=(t,e,r)=>zy(t,e,"<",r);const Yy=Dg;var Jy=(t,e,r)=>(t=new Yy(t,r),e=new Yy(e,r),t.intersects(e));const Zy=Ey,Qy=bd;const tv=Dg,ev=ly,{ANY:rv}=ev,nv=Ey,iv=bd,ov=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===rv){if(1===e.length&&e[0].semver===rv)return!0;t=r.includePrerelease?[new ev(">=0.0.0-0")]:[new ev(">=0.0.0")]}if(1===e.length&&e[0].semver===rv){if(r.includePrerelease)return!0;e=[new ev(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=sv(i,e,r):"<"===e.operator||"<="===e.operator?o=uv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=iv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!nv(t,String(i),r))return null;if(o&&!nv(t,String(o),r))return null;for(const n of e)if(!nv(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=sv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!nv(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=uv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!nv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},sv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},uv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var av=(t,e,r={})=>{if(t===e)return!0;t=new tv(t,r),e=new tv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=ov(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const hv=Gp.exports;var fv={re:hv.re,src:hv.src,tokens:hv.t,SEMVER_SPEC_VERSION:Wp.SEMVER_SPEC_VERSION,SemVer:sd,compareIdentifiers:Jp.compareIdentifiers,rcompareIdentifiers:Jp.rcompareIdentifiers,parse:ld,valid:dd,clean:yd,inc:md,diff:Td,major:Ad,minor:Pd,patch:xd,prerelease:Nd,compare:bd,rcompare:Cd,compareLoose:Ld,compareBuild:Hd,sort:qd,rsort:Kd,gt:Wd,lt:$d,eq:_d,neq:Xd,gte:Jd,lte:Qd,cmp:sg,coerce:cg,Comparator:ly,Range:Dg,satisfies:Ey,toComparators:Sy,maxSatisfying:Oy,minSatisfying:Py,minVersion:Ny,validRange:Cy,outside:Wy,gtr:$y,ltr:Xy,intersects:Jy,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Qy(t,e,r)));for(const t of s){Zy(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Tv(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ov(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Av(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}yv.prototype=Object.create(null),vv.EventEmitter=vv,vv.usingDomains=!1,vv.prototype.domain=void 0,vv.prototype._events=void 0,vv.prototype._maxListeners=void 0,vv.defaultMaxListeners=10,vv.init=function(){this.domain=null,vv.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new yv,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},vv.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},vv.prototype.getMaxListeners=function(){return mv(this)},vv.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:wv(r,f,this);break;case 2:bv(r,f,this,arguments[1]);break;case 3:Ev(r,f,this,arguments[1],arguments[2]);break;case 4:_v(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new yv,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var kv=Object.freeze({__proto__:null,default:vv,EventEmitter:vv});function Pv(){throw new Error("setTimeout has not been defined")}function Mv(){throw new Error("clearTimeout has not been defined")}var xv=Pv,Rv=Mv;function Nv(t){if(xv===setTimeout)return setTimeout(t,0);if((xv===Pv||!xv)&&setTimeout)return xv=setTimeout,setTimeout(t,0);try{return xv(t,0)}catch(e){try{return xv.call(null,t,0)}catch(e){return xv.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xv=setTimeout),"function"==typeof global.clearTimeout&&(Rv=clearTimeout);var Bv,Cv=[],Uv=!1,Lv=-1;function Dv(){Uv&&Bv&&(Uv=!1,Bv.length?Cv=Bv.concat(Cv):Lv=-1,Cv.length&&Hv())}function Hv(){if(!Uv){var t=Nv(Dv);Uv=!0;for(var e=Cv.length;e;){for(Bv=Cv,Cv=[];++Lv1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),nm(e)?r.showHidden=e:e&&_m(r,e),hm(r.showHidden)&&(r.showHidden=!1),hm(r.depth)&&(r.depth=2),hm(r.colors)&&(r.colors=!1),hm(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Jv),Qv(r,t,r.depth)}function Jv(t,e){var r=Yv.styles[e];return r?"["+Yv.colors[r][0]+"m"+t+"["+Yv.colors[r][1]+"m":t}function Zv(t,e){return t}function Qv(t,e,r){if(t.customInspect&&e&&dm(e.inspect)&&e.inspect!==Yv&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return um(n)||(n=Qv(t,n,r)),n}var i=function(t,e){if(hm(e))return t.stylize("undefined","undefined");if(um(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(sm(e))return t.stylize(""+e,"number");if(nm(e))return t.stylize(""+e,"boolean");if(im(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),pm(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tm(e);if(0===o.length){if(dm(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(fm(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(lm(e))return t.stylize(Date.prototype.toString.call(e),"date");if(pm(e))return tm(e)}var a,h="",f=!1,c=["{","}"];(rm(e)&&(f=!0,c=["[","]"]),dm(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return fm(e)&&(h=" "+RegExp.prototype.toString.call(e)),lm(e)&&(h=" "+Date.prototype.toUTCString.call(e)),pm(e)&&(h=" "+tm(e)),0!==o.length||f&&0!=e.length?r<0?fm(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function tm(t){return"["+Error.prototype.toString.call(t)+"]"}function em(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Sm(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=im(r)?Qv(t,a.value,null):Qv(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),hm(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function rm(t){return Array.isArray(t)}function nm(t){return"boolean"==typeof t}function im(t){return null===t}function om(t){return null==t}function sm(t){return"number"==typeof t}function um(t){return"string"==typeof t}function am(t){return"symbol"==typeof t}function hm(t){return void 0===t}function fm(t){return cm(t)&&"[object RegExp]"===vm(t)}function cm(t){return"object"==typeof t&&null!==t}function lm(t){return cm(t)&&"[object Date]"===vm(t)}function pm(t){return cm(t)&&("[object Error]"===vm(t)||t instanceof Error)}function dm(t){return"function"==typeof t}function gm(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function ym(t){return Buffer.isBuffer(t)}function vm(t){return Object.prototype.toString.call(t)}function mm(t){return t<10?"0"+t.toString(10):t.toString(10)}Yv.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]},Yv.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var wm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bm(){var t=new Date,e=[mm(t.getHours()),mm(t.getMinutes()),mm(t.getSeconds())].join(":");return[t.getDate(),wm[t.getMonth()],e].join(" ")}function Em(){console.log("%s - %s",bm(),Wv.apply(null,arguments))}function _m(t,e){if(!e||!cm(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Sm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Im={inherits:Kv,_extend:_m,log:Em,isBuffer:ym,isPrimitive:gm,isFunction:dm,isError:pm,isDate:lm,isObject:cm,isRegExp:fm,isUndefined:hm,isSymbol:am,isString:um,isNumber:sm,isNullOrUndefined:om,isNull:im,isBoolean:nm,isArray:rm,inspect:Yv,deprecate:Vv,format:Wv,debuglog:Xv},Tm=Object.freeze({__proto__:null,format:Wv,deprecate:Vv,debuglog:Xv,inspect:Yv,isArray:rm,isBoolean:nm,isNull:im,isNullOrUndefined:om,isNumber:sm,isString:um,isSymbol:am,isUndefined:hm,isRegExp:fm,isObject:cm,isDate:lm,isError:pm,isFunction:dm,isPrimitive:gm,isBuffer:ym,log:Em,inherits:Kv,_extend:_m,default:Im});function Om(){this.head=null,this.tail=null,this.length=0}Om.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Om.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Om.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Om.prototype.clear=function(){this.head=this.tail=null,this.length=0},Om.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Om.prototype.concat=function(t){if(0===this.length)return I.alloc(0);if(1===this.length)return this.head.data;for(var e=I.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Am=I.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function km(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Am(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Mm;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xm;break;default:return void(this.write=Pm)}this.charBuffer=new I(6),this.charReceived=0,this.charLength=0}function Pm(t){return t.toString(this.encoding)}function Mm(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xm(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}km.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},km.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},km.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Bm.ReadableState=Nm;var Rm=Xv("stream");function Nm(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof aw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Om,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new km(t.encoding),this.encoding=t.encoding)}function Bm(t){if(!(this instanceof Bm))return new Bm(t);this._readableState=new Nm(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),vv.call(this)}function Cm(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Dm(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Dm(t))),function(t,e){e.readingMore||(e.readingMore=!0,jv(jm,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Um?t=Um:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Dm(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Rm("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?jv(Hm,t):Hm(t))}function Hm(t){Rm("emit readable"),t.emit("readable"),Km(t)}function jm(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Wm(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,jv(Vm,e,t))}function Vm(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function $m(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Rm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Wm(this):Dm(this),null;if(0===(t=Lm(t,e))&&e.ended)return 0===e.length&&Wm(this),null;var n,i=e.needReadable;return Rm("need readable",i),(0===e.length||e.length-t0?Gm(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Wm(this)),null!==n&&this.emit("data",n),n},Bm.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Bm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Rm("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Rm("onunpipe"),t===r&&h()}function s(){Rm("onend"),t.end()}n.endEmitted?jv(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Rm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Km(t))}}(r);t.on("drain",u);var a=!1;function h(){Rm("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Rm("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==$m(n.pipes,t))&&!a&&(Rm("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Rm("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Rm("onfinish"),t.removeListener("close",p),g()}function g(){Rm("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Rm("pipe resume"),r.resume()),t},Bm.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Jm.prototype._write=function(t,e,r){r(new Error("not implemented"))},Jm.prototype._writev=null,Jm.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,nw(t,e),r&&(e.finished?jv(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Kv(aw,Bm);for(var ow=Object.keys(Jm.prototype),sw=0;sw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Sw.alloc(0);for(var e=Sw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ow(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Sw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Tw,value:function(t,e){return Iw(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Bw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Bw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Cw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Cw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Bw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Bw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Bw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Bw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Bw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Bw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Bw("ERR_STREAM_WRITE_AFTER_END","write after end"),Bw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Bw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Bw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Rw.codes=Nw;var Uw=Rw.codes.ERR_INVALID_OPT_VALUE;var Lw,Dw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Uw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Hw=ww.deprecate,jw=ub;function qw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}ub.WritableState=sb;var Fw={deprecate:Hw},Kw=mw,Gw=ht.Buffer,Ww=r.Uint8Array||function(){};var Vw,$w=xw,zw=Dw.getHighWaterMark,Xw=Rw.codes,Yw=Xw.ERR_INVALID_ARG_TYPE,Jw=Xw.ERR_METHOD_NOT_IMPLEMENTED,Zw=Xw.ERR_MULTIPLE_CALLBACK,Qw=Xw.ERR_STREAM_CANNOT_PIPE,tb=Xw.ERR_STREAM_DESTROYED,eb=Xw.ERR_STREAM_NULL_VALUES,rb=Xw.ERR_STREAM_WRITE_AFTER_END,nb=Xw.ERR_UNKNOWN_ENCODING,ib=$w.errorOrDestroy;function ob(){}function sb(t,e,r){Lw=Lw||gb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Lw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=zw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Zw;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(pb,t,e),t._writableState.errorEmitted=!0,ib(t,n)):(i(n),t._writableState.errorEmitted=!0,ib(t,n),pb(t,e))}(t,r,n,e,i);else{var o=cb(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||fb(t,r),n?process.nextTick(hb,t,r,o,i):hb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new qw(this)}function ub(t){var e=this instanceof(Lw=Lw||gb);if(!e&&!Vw.call(ub,this))return new ub(t);this._writableState=new sb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Kw.call(this)}function ab(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new tb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),pb(t,e)}function fb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,ab(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new qw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(ab(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function cb(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function lb(t,e){t._final((function(r){e.pendingcb--,r&&ib(t,r),e.prefinished=!0,t.emit("prefinish"),pb(t,e)}))}function pb(t,e){var r=cb(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(lb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}Zt.exports(ub,Kw),sb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(sb.prototype,"buffer",{get:Fw.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Vw=Function.prototype[Symbol.hasInstance],Object.defineProperty(ub,Symbol.hasInstance,{value:function(t){return!!Vw.call(this,t)||this===ub&&(t&&t._writableState instanceof sb)}})):Vw=function(t){return t instanceof this},ub.prototype.pipe=function(){ib(this,new Qw)},ub.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Gw.isBuffer(n)||n instanceof Ww);return s&&!Gw.isBuffer(t)&&(t=function(t){return Gw.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ob),i.ending?function(t,e){var r=new rb;ib(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new eb:"string"==typeof r||e.objectMode||(i=new Yw("chunk",["string","Buffer"],r)),!i||(ib(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Gw.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new nb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(ub.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(ub.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),ub.prototype._write=function(t,e,r){r(new Jw("_write()"))},ub.prototype._writev=null,ub.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,pb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(ub.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(ub.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),ub.prototype.destroy=$w.destroy,ub.prototype._undestroy=$w.undestroy,ub.prototype._destroy=function(t,e){e(t)};var db=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},gb=Eb,yb=aE,vb=jw;Zt.exports(Eb,yb);for(var mb=db(vb.prototype),wb=0;wb>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Pb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Mb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function xb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Rb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Nb(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Bb(t){return t.toString(this.encoding)}function Cb(t){return t&&t.length?this.write(t):""}Ib.StringDecoder=Ab,Ab.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Ab.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Ub=Rw.codes.ERR_STREAM_PREMATURE_CLOSE;function Lb(){}var Db,Hb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===cE.prototype||(e=function(t){return cE.from(t)}(e)),n)s.endEmitted?OE(t,new TE):xE(t,s,e,!0);else if(s.ended)OE(t,new SE);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?xE(t,s,e,!1):UE(t,s)):xE(t,s,e,!1)}else n||(s.reading=!1,UE(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=RE?t=RE:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function BE(t){var e=t._readableState;pE("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(pE("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(CE,t))}function CE(t){var e=t._readableState;pE("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,qE(t)}function UE(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(LE,t,e))}function LE(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function HE(t){pE("readable nexttick read 0"),t.read(0)}function jE(t,e){pE("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),qE(t),e.flowing&&!e.reading&&t.read(0)}function qE(t){var e=t._readableState;for(pE("flow",e.flowing);e.flowing&&null!==t.read(););}function FE(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function KE(t){var e=t._readableState;pE("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(GE,e,t))}function GE(t,e){if(pE("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function WE(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return pE("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?KE(this):BE(this),null;if(0===(t=NE(t,e))&&e.ended)return 0===e.length&&KE(this),null;var n,i=e.needReadable;return pE("need readable",i),(0===e.length||e.length-t0?FE(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&KE(this)),null!==n&&this.emit("data",n),n},PE.prototype._read=function(t){OE(this,new IE("_read()"))},PE.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,pE("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){pE("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,pE("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){pE("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;pE("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&hE(t,"data")&&(e.flowing=!0,qE(t))}}(r);t.on("drain",u);var a=!1;function h(e){pE("ondata");var i=t.write(e);pE("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==WE(n.pipes,t))&&!a&&(pE("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){pE("onerror",e),p(),t.removeListener("error",f),0===hE(t,"error")&&OE(t,e)}function c(){t.removeListener("finish",l),p()}function l(){pE("onfinish"),t.removeListener("close",c),p()}function p(){pE("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(pE("pipe resume"),r.resume()),t},PE.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,pE("on readable",n.length,n.reading),n.length?BE(this):n.reading||process.nextTick(HE,this))),r},PE.prototype.addListener=PE.prototype.on,PE.prototype.removeListener=function(t,e){var r=fE.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(DE,this),r},PE.prototype.removeAllListeners=function(t){var e=fE.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(DE,this),e},PE.prototype.resume=function(){var t=this._readableState;return t.flowing||(pE("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(jE,t,e))}(this,t)),t.paused=!1,this},PE.prototype.pause=function(){return pE("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(pE("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},PE.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(pE("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(pE("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(l_),s||(o.forEach(l_),i(n))}))}));return e.reduce(p_)};!function(t,e){var r=yw;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=aE).Stream=r||e,e.Readable=e,e.Writable=jw,e.Duplex=gb,e.Transform=VE,e.PassThrough=i_,e.finished=Hb,e.pipeline=g_)}(gv,gv.exports);var y_=h.exports.Buffer,v_=gv.exports.Transform;function m_(t){v_.call(this),this._block=y_.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,Zt.exports)(m_,v_),m_.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},m_.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},m_.prototype.update=function(t,e){if(function(t,e){if(!y_.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");y_.isBuffer(t)||(t=y_.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},m_.prototype._update=function(){throw new Error("_update is not implemented")},m_.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},m_.prototype._digest=function(){throw new Error("_digest is not implemented")};var w_=m_,b_=ht.Buffer,E_=Zt.exports,__=w_,S_=new Array(16),I_=[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],T_=[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],O_=[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],A_=[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],k_=[0,1518500249,1859775393,2400959708,2840853838],P_=[1352829926,1548603684,1836072691,2053994217,0];function M_(){__.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function x_(t,e){return t<>>32-e}function R_(t,e,r,n,i,o,s,u){return x_(t+(e^r^n)+o+s|0,u)+i|0}function N_(t,e,r,n,i,o,s,u){return x_(t+(e&r|~e&n)+o+s|0,u)+i|0}function B_(t,e,r,n,i,o,s,u){return x_(t+((e|~r)^n)+o+s|0,u)+i|0}function C_(t,e,r,n,i,o,s,u){return x_(t+(e&n|r&~n)+o+s|0,u)+i|0}function U_(t,e,r,n,i,o,s,u){return x_(t+(e^(r|~n))+o+s|0,u)+i|0}E_(M_,__),M_.prototype._update=function(){for(var t=S_,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=R_(r,n,i,o,s,t[I_[l]],k_[0],O_[l]),d=U_(u,a,h,f,c,t[T_[l]],P_[0],A_[l])):l<32?(p=N_(r,n,i,o,s,t[I_[l]],k_[1],O_[l]),d=C_(u,a,h,f,c,t[T_[l]],P_[1],A_[l])):l<48?(p=B_(r,n,i,o,s,t[I_[l]],k_[2],O_[l]),d=B_(u,a,h,f,c,t[T_[l]],P_[2],A_[l])):l<64?(p=C_(r,n,i,o,s,t[I_[l]],k_[3],O_[l]),d=N_(u,a,h,f,c,t[T_[l]],P_[3],A_[l])):(p=U_(r,n,i,o,s,t[I_[l]],k_[4],O_[l]),d=R_(u,a,h,f,c,t[T_[l]],P_[4],A_[l])),r=s,s=o,o=x_(i,10),i=n,n=p,u=c,c=f,f=x_(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},M_.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=b_.alloc?b_.alloc(20):new b_(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var L_=M_,D_={exports:{}},H_=h.exports.Buffer;function j_(t,e){this._block=H_.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}j_.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=H_.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},j_.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var q_=j_,F_=Zt.exports,K_=q_,G_=h.exports.Buffer,W_=[1518500249,1859775393,-1894007588,-899497514],V_=new Array(80);function $_(){this.init(),this._w=V_,K_.call(this,64,56)}function z_(t){return t<<30|t>>>2}function X_(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}F_($_,K_),$_.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},$_.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+X_(f,i,o,s)+u+r[h]+W_[f];u=s,s=o,o=z_(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},$_.prototype._hash=function(){var t=G_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var Y_=$_,J_=Zt.exports,Z_=q_,Q_=h.exports.Buffer,tS=[1518500249,1859775393,-1894007588,-899497514],eS=new Array(80);function rS(){this.init(),this._w=eS,Z_.call(this,64,56)}function nS(t){return t<<5|t>>>27}function iS(t){return t<<30|t>>>2}function oS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}J_(rS,Z_),rS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},rS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=nS(n)+oS(f,i,o,s)+u+r[h]+tS[f]|0;u=s,s=o,o=iS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},rS.prototype._hash=function(){var t=Q_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var sS=rS,uS=Zt.exports,aS=q_,hS=h.exports.Buffer,fS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cS=new Array(64);function lS(){this.init(),this._w=cS,aS.call(this,64,56)}function pS(t,e,r){return r^t&(e^r)}function dS(t,e,r){return t&e|r&(t|e)}function gS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function yS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function vS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function mS(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}uS(lS,aS),lS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},lS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=mS(e[f-2])+e[f-7]+vS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+yS(s)+pS(s,u,a)+fS[c]+e[c]|0,p=gS(r)+dS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},lS.prototype._hash=function(){var t=hS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var wS=lS,bS=Zt.exports,ES=wS,_S=q_,SS=h.exports.Buffer,IS=new Array(64);function TS(){this.init(),this._w=IS,_S.call(this,64,56)}bS(TS,ES),TS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},TS.prototype._hash=function(){var t=SS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var OS=TS,AS=Zt.exports,kS=q_,PS=h.exports.Buffer,MS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xS=new Array(160);function RS(){this.init(),this._w=xS,kS.call(this,128,112)}function NS(t,e,r){return r^t&(e^r)}function BS(t,e,r){return t&e|r&(t|e)}function CS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function US(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function LS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function DS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function HS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function jS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function qS(t,e){return t>>>0>>0?1:0}AS(RS,kS),RS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},RS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=LS(w,b),_=DS(b,w),S=HS(w=e[m-4],b=e[m-4+1]),I=jS(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],k=e[m-32+1],P=_+O|0,M=E+T+qS(P,_)|0;M=(M=M+S+qS(P=P+I|0,I)|0)+A+qS(P=P+k|0,k)|0,e[m]=M,e[m+1]=P}for(var x=0;x<160;x+=2){M=e[x],P=e[x+1];var R=BS(r,n,i),N=BS(f,c,l),B=CS(r,f),C=CS(f,r),U=US(s,d),L=US(d,s),D=MS[x],H=MS[x+1],j=NS(s,u,a),q=NS(d,g,y),F=v+L|0,K=h+U+qS(F,v)|0;K=(K=(K=K+j+qS(F=F+q|0,q)|0)+D+qS(F=F+H|0,H)|0)+M+qS(F=F+P|0,P)|0;var G=C+N|0,W=B+R+qS(G,C)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+K+qS(d=p+F|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=K+W+qS(f=F+G|0,F)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+qS(this._al,f)|0,this._bh=this._bh+n+qS(this._bl,c)|0,this._ch=this._ch+i+qS(this._cl,l)|0,this._dh=this._dh+o+qS(this._dl,p)|0,this._eh=this._eh+s+qS(this._el,d)|0,this._fh=this._fh+u+qS(this._fl,g)|0,this._gh=this._gh+a+qS(this._gl,y)|0,this._hh=this._hh+h+qS(this._hl,v)|0},RS.prototype._hash=function(){var t=PS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var FS=RS,KS=Zt.exports,GS=FS,WS=q_,VS=h.exports.Buffer,$S=new Array(160);function zS(){this.init(),this._w=$S,WS.call(this,128,112)}KS(zS,GS),zS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},zS.prototype._hash=function(){var t=VS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var XS=zS,YS=D_.exports=function(t){t=t.toLowerCase();var e=YS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};YS.sha=Y_,YS.sha1=sS,YS.sha224=OS,YS.sha256=wS,YS.sha384=XS,YS.sha512=FS;var JS=D_.exports;function ZS(t){return(new L_).update(JS("sha256").update(t).digest()).digest()}var QS,tI=(QS=function(t,e){return QS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},QS(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}QS(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),eI=function(t,e){this.psbt=t,this.masterFp=e},rI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(eI),nI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(rI),iI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new cv,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Bp.sha256(Buffer.from("TapTweak","utf-8"));return Bp.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(xt.exports.pointAddScalar(e,r)).slice(1)},e}(rI),oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=this.createRedeemScript(t),n=ZS(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=ZS(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(rI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(rI),uI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},aI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return lI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new cI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new cI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function LI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,UI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,UI(t.script.length),t.script])}))),r}function DI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,UI(t.script.length),t.script,t.sequence])}));var a=LI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),UI(t.inputs.length),s,a])}var HI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new pI(e,dI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return HI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I;return jI(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new _I,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new iI(e,r):t.additionals.includes("bech32")?new sI(e,r):t.segwit?new oI(e,r):new nI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new cv).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new cv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new cv;BI(h,f),BI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new cv).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}NI(t,r)}}(r),I=function(t){var e,r,n=new cv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new cv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nT(t,e,r){return tT(this,void 0,void 0,(function(){var n,i,o,s;return eT(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function iT(t,e,r,n){return void 0===n&&(n=[]),tT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R=this;return eT(this,(function(N){switch(N.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return tT(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return eT(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>pv?pv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=rT(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,nT(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return nT(t,e)},[4,nT(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(o.length)]),e)];case 1:N.sent(),N.label=2;case 2:N.trys.push([2,8,9,10]),d=rT(o),g=d.next(),N.label=3;case 3:return g.done?[3,7]:(y=g.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?y.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([y.prevout,m,v?Buffer.from([0]):UI(y.script.length)]),[4,nT(t,O)]);case 4:return N.sent(),[4,f?p(Buffer.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:N.sent(),N.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=N.sent(),k={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,nT(t,UI(s.length))];case 11:N.sent(),N.label=12;case 12:N.trys.push([12,17,18,19]),b=rT(s),E=b.next(),N.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),UI(_.script.length),_.script]),[4,nT(t,O)]);case 14:N.sent(),N.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=N.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([UI(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return A=N.sent(),QI(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var oT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},sT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aT(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function hT(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),oT(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return sT(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(r.inputs.length)]),[4,aT(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=uT(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),UI(p.script.length)]),[4,aT(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>pv?pv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=uT(y),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,aT(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function fT(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=JS("sha256").update(JS("sha256").update(DI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function cT(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=wt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var lT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},pT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:pv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var yT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ST={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function IT(t,e){return bT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C,U,L,D,H,j,q,F,K,G,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return ET(this,(function(ht){switch(ht.label){case 0:if(r=wT(wT({},ST),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,mT(t)];case 2:return v=ht.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||fv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),A=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),P=[],M=[],x=[],R=[],N=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},U=T&&!y?fT:iT,L=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=_T(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:j=ht.sent(),VI("hw","got trustedInput="+j),(q=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:dv,0),P.push({trustedInput:!0,value:Buffer.from(j,"hex"),sequence:q}),ht.label=8;case 8:F=$[0].outputs,K=$[1],F&&K<=F.length-1&&M.push(F[K]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return G=ht.sent(),ut={error:G},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:dv,0),{script:O,prevout:A,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),ZS(R[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[P[it]]:P,T?X.inputs=[wT(wT({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,hT(t,!T&&N,X,Y,T,!!l&&!b,c,y)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,dT(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,gT(t,L,c)];case 30:ht.sent(),ht.label=31;case 31:return N&&(d(),w(1,0)),[4,cT(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,N&&(N=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},xT={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function RT(t,e){return kT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C;return PT(this,(function(U){switch(U.label){case 0:r=AT(AT({},xT),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?fT:iT,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),E=MT(n),_=E.next(),U.label=2;case 2:return _.done?[3,6]:(P=_.value,v?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=U.sent(),(A=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:dv,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:A}),U.label=4;case 4:I=P[0].outputs,T=P[1],I&&T<=I.length-1&&d.push(I[T]),U.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=U.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:dv,0),m.inputs.push({script:f,prevout:c,sequence:A});return a?[4,hT(t,!0,m,p,!0)]:[3,12];case 10:return U.sent(),[4,gT(t,b)];case 11:U.sent(),U.label=12;case 12:k=0,U.label=13;case 13:return k=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[k].script,x=Object.assign({},m),R=a?[p[k]]:p,a?x.inputs=[AT(AT({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,hT(t,!a&&y,x,R,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,gT(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,cT(t,i[k],s,u)];case 17:N=U.sent(),g.push(a?N.toString("hex"):N.slice(0,N.length-1).toString("hex")),m.inputs[k].script=f,y&&(y=!1),U.label=18;case 18:return k++,[3,13];case 19:return[2,g]}}))}))}var NT=function(){return NT=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,u()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),IT(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),RT(this.transport,t)},t}();function LT(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var DT=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function HT(t){return JS("sha256").update(t).digest()}var jT,qT=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new hI(t.map((function(t){return fI(t)}))),this.values=e,this.valuesTree=new hI(e.map((function(t){return fI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([UI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),FT=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),KT=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},GT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},zT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(jT||(jT={}));var YT,JT,ZT=function(){},QT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=jT.YIELD,n.results=e,n}return VT(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(ZT),tO=function(t){function e(e,r){var n=t.call(this)||this;return n.code=jT.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=UI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,zT([],$T(a.slice(-f)),!1)),Buffer.concat(zT([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],$T(a.slice(0,h)),!1))},e}(ZT),rO=function(t){function e(e){var r=t.call(this)||this;return r.code=jT.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(YT||(YT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(JT||(JT={}));var aO=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return oO(this,void 0,void 0,(function(){var n,i,o;return sO(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,JT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return oO(this,void 0,void 0,(function(){return sO(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(YT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),mt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return oO(this,void 0,void 0,(function(){var o,s;return sO(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new iO((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(YT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return oO(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S;return sO(this,(function(I){switch(I.label){case 0:if(i=new WT(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new iO(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=uO(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=uO(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new hI(i.inputMapCommitments.map((function(t){return fI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new hI(i.outputMapCommitments.map((function(t){return fI(t)}))).getRoot(),[4,this.makeRequest(YT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),UI(i.getGlobalInputCount()),c,UI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=uO(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return oO(this,void 0,void 0,(function(){return sO(this,(function(t){return[2,this.makeRequest(YT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var hO=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},fO=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof FI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||lO(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(Buffer.from([3,0,0,128]))||y.equals(Buffer.from([4,0,0,128])),m=y.equals(Buffer.from([1,0,0,0]))||y.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(c=g.slice(a,4+a),a+=4);var w=CI(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new UT(this.transport)},t.prototype.new=function(){return new FI(new aO(this.transport))},t}();function lO(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var pO=Object.freeze({__proto__:null,default:cO}),dO={},gO={},yO={},vO={};Object.defineProperty(vO,"__esModule",{value:!0});var mO="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wO={},bO={};vO.addCustomErrorDeserializer=function(t,e){bO[t]=e};var EO=vO.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,wO[t]=e,e};function _O(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":mO(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=_O(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}vO.deserializeError=function t(e){if("object"===(void 0===e?"undefined":mO(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=bO[i];if(o)n=o(e);else{var s="Error"===i?Error:wO[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=EO(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},vO.serializeError=function(t){return t?"object"===(void 0===t?"undefined":mO(t))?_O(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(yO,"__esModule",{value:!0}),yO.StatusCodes=yO.DBNotReset=yO.DBWrongPassword=yO.NoDBPathGiven=yO.FirmwareOrAppUpdateRequired=yO.LedgerAPI5xx=yO.LedgerAPI4xx=yO.GenuineCheckFailed=yO.PairingFailed=yO.SyncError=yO.FeeTooHigh=yO.FeeRequired=yO.FeeNotLoaded=yO.CantScanQRCode=yO.ETHAddressNonEIP=yO.WrongAppForCurrency=yO.WrongDeviceForAccount=yO.WebsocketConnectionFailed=yO.WebsocketConnectionError=yO.DeviceShouldStayInApp=yO.TransportWebUSBGestureRequired=yO.TransportInterfaceNotAvailable=yO.TransportOpenUserCancelled=yO.UserRefusedOnDevice=yO.UserRefusedAllowManager=yO.UserRefusedFirmwareUpdate=yO.UserRefusedAddress=yO.UserRefusedDeviceNameChange=yO.UpdateYourApp=yO.UnavailableTezosOriginatedAccountSend=yO.UnavailableTezosOriginatedAccountReceive=yO.RecipientRequired=yO.MCUNotGenuineToDashboard=yO.UnexpectedBootloader=yO.TimeoutTagged=yO.RecommendUndelegation=yO.RecommendSubAccountsToEmpty=yO.PasswordIncorrectError=yO.PasswordsDontMatchError=yO.GasLessThanEstimate=yO.NotSupportedLegacyAddress=yO.NotEnoughGas=yO.NoAccessToCamera=yO.NotEnoughBalanceBecauseDestinationNotCreated=yO.NotEnoughSpendableBalance=yO.NotEnoughBalanceInParentAccount=yO.NotEnoughBalanceToDelegate=yO.NotEnoughBalance=yO.NoAddressesFound=yO.NetworkDown=yO.ManagerUninstallBTCDep=yO.ManagerNotEnoughSpaceError=yO.ManagerFirmwareNotEnoughSpaceError=yO.ManagerDeviceLockedError=yO.ManagerAppDepUninstallRequired=yO.ManagerAppDepInstallRequired=yO.ManagerAppRelyOnBTCError=yO.ManagerAppAlreadyInstalledError=yO.LedgerAPINotAvailable=yO.LedgerAPIErrorWithMessage=yO.LedgerAPIError=yO.UnknownMCU=yO.LatestMCUInstalledError=yO.InvalidAddressBecauseDestinationIsAlsoSource=yO.InvalidAddress=yO.InvalidXRPTag=yO.HardResetFail=yO.FeeEstimationFailed=yO.EthAppPleaseEnableContractData=yO.EnpointConfigError=yO.DisconnectedDeviceDuringOperation=yO.DisconnectedDevice=yO.DeviceSocketNoBulkStatus=yO.DeviceSocketFail=yO.DeviceNameInvalid=yO.DeviceHalted=yO.DeviceInOSUExpected=yO.DeviceOnDashboardUnexpected=yO.DeviceOnDashboardExpected=yO.DeviceNotGenuineError=yO.DeviceGenuineSocketEarlyClose=yO.DeviceAppVerifyNotSupported=yO.CurrencyNotSupported=yO.CashAddrNotSupported=yO.CantOpenDevice=yO.BtcUnmatchedApp=yO.BluetoothRequired=yO.AmountRequired=yO.AccountNotSupported=yO.AccountNameRequiredError=yO.addCustomErrorDeserializer=yO.createCustomErrorClass=yO.deserializeError=yO.serializeError=void 0,yO.TransportError=IO,yO.getAltStatusMessage=OO,yO.TransportStatusError=AO;var SO=vO;function IO(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}yO.serializeError=SO.serializeError,yO.deserializeError=SO.deserializeError,yO.createCustomErrorClass=SO.createCustomErrorClass,yO.addCustomErrorDeserializer=SO.addCustomErrorDeserializer,yO.AccountNameRequiredError=(0,SO.createCustomErrorClass)("AccountNameRequired"),yO.AccountNotSupported=(0,SO.createCustomErrorClass)("AccountNotSupported"),yO.AmountRequired=(0,SO.createCustomErrorClass)("AmountRequired"),yO.BluetoothRequired=(0,SO.createCustomErrorClass)("BluetoothRequired"),yO.BtcUnmatchedApp=(0,SO.createCustomErrorClass)("BtcUnmatchedApp"),yO.CantOpenDevice=(0,SO.createCustomErrorClass)("CantOpenDevice"),yO.CashAddrNotSupported=(0,SO.createCustomErrorClass)("CashAddrNotSupported"),yO.CurrencyNotSupported=(0,SO.createCustomErrorClass)("CurrencyNotSupported"),yO.DeviceAppVerifyNotSupported=(0,SO.createCustomErrorClass)("DeviceAppVerifyNotSupported"),yO.DeviceGenuineSocketEarlyClose=(0,SO.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),yO.DeviceNotGenuineError=(0,SO.createCustomErrorClass)("DeviceNotGenuine"),yO.DeviceOnDashboardExpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardExpected"),yO.DeviceOnDashboardUnexpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardUnexpected"),yO.DeviceInOSUExpected=(0,SO.createCustomErrorClass)("DeviceInOSUExpected"),yO.DeviceHalted=(0,SO.createCustomErrorClass)("DeviceHalted"),yO.DeviceNameInvalid=(0,SO.createCustomErrorClass)("DeviceNameInvalid"),yO.DeviceSocketFail=(0,SO.createCustomErrorClass)("DeviceSocketFail"),yO.DeviceSocketNoBulkStatus=(0,SO.createCustomErrorClass)("DeviceSocketNoBulkStatus"),yO.DisconnectedDevice=(0,SO.createCustomErrorClass)("DisconnectedDevice"),yO.DisconnectedDeviceDuringOperation=(0,SO.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),yO.EnpointConfigError=(0,SO.createCustomErrorClass)("EnpointConfig"),yO.EthAppPleaseEnableContractData=(0,SO.createCustomErrorClass)("EthAppPleaseEnableContractData"),yO.FeeEstimationFailed=(0,SO.createCustomErrorClass)("FeeEstimationFailed"),yO.HardResetFail=(0,SO.createCustomErrorClass)("HardResetFail"),yO.InvalidXRPTag=(0,SO.createCustomErrorClass)("InvalidXRPTag"),yO.InvalidAddress=(0,SO.createCustomErrorClass)("InvalidAddress"),yO.InvalidAddressBecauseDestinationIsAlsoSource=(0,SO.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),yO.LatestMCUInstalledError=(0,SO.createCustomErrorClass)("LatestMCUInstalledError"),yO.UnknownMCU=(0,SO.createCustomErrorClass)("UnknownMCU"),yO.LedgerAPIError=(0,SO.createCustomErrorClass)("LedgerAPIError"),yO.LedgerAPIErrorWithMessage=(0,SO.createCustomErrorClass)("LedgerAPIErrorWithMessage"),yO.LedgerAPINotAvailable=(0,SO.createCustomErrorClass)("LedgerAPINotAvailable"),yO.ManagerAppAlreadyInstalledError=(0,SO.createCustomErrorClass)("ManagerAppAlreadyInstalled"),yO.ManagerAppRelyOnBTCError=(0,SO.createCustomErrorClass)("ManagerAppRelyOnBTC"),yO.ManagerAppDepInstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepInstallRequired"),yO.ManagerAppDepUninstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepUninstallRequired"),yO.ManagerDeviceLockedError=(0,SO.createCustomErrorClass)("ManagerDeviceLocked"),yO.ManagerFirmwareNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),yO.ManagerNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerNotEnoughSpace"),yO.ManagerUninstallBTCDep=(0,SO.createCustomErrorClass)("ManagerUninstallBTCDep"),yO.NetworkDown=(0,SO.createCustomErrorClass)("NetworkDown"),yO.NoAddressesFound=(0,SO.createCustomErrorClass)("NoAddressesFound"),yO.NotEnoughBalance=(0,SO.createCustomErrorClass)("NotEnoughBalance"),yO.NotEnoughBalanceToDelegate=(0,SO.createCustomErrorClass)("NotEnoughBalanceToDelegate"),yO.NotEnoughBalanceInParentAccount=(0,SO.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),yO.NotEnoughSpendableBalance=(0,SO.createCustomErrorClass)("NotEnoughSpendableBalance"),yO.NotEnoughBalanceBecauseDestinationNotCreated=(0,SO.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),yO.NoAccessToCamera=(0,SO.createCustomErrorClass)("NoAccessToCamera"),yO.NotEnoughGas=(0,SO.createCustomErrorClass)("NotEnoughGas"),yO.NotSupportedLegacyAddress=(0,SO.createCustomErrorClass)("NotSupportedLegacyAddress"),yO.GasLessThanEstimate=(0,SO.createCustomErrorClass)("GasLessThanEstimate"),yO.PasswordsDontMatchError=(0,SO.createCustomErrorClass)("PasswordsDontMatch"),yO.PasswordIncorrectError=(0,SO.createCustomErrorClass)("PasswordIncorrect"),yO.RecommendSubAccountsToEmpty=(0,SO.createCustomErrorClass)("RecommendSubAccountsToEmpty"),yO.RecommendUndelegation=(0,SO.createCustomErrorClass)("RecommendUndelegation"),yO.TimeoutTagged=(0,SO.createCustomErrorClass)("TimeoutTagged"),yO.UnexpectedBootloader=(0,SO.createCustomErrorClass)("UnexpectedBootloader"),yO.MCUNotGenuineToDashboard=(0,SO.createCustomErrorClass)("MCUNotGenuineToDashboard"),yO.RecipientRequired=(0,SO.createCustomErrorClass)("RecipientRequired"),yO.UnavailableTezosOriginatedAccountReceive=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),yO.UnavailableTezosOriginatedAccountSend=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),yO.UpdateYourApp=(0,SO.createCustomErrorClass)("UpdateYourApp"),yO.UserRefusedDeviceNameChange=(0,SO.createCustomErrorClass)("UserRefusedDeviceNameChange"),yO.UserRefusedAddress=(0,SO.createCustomErrorClass)("UserRefusedAddress"),yO.UserRefusedFirmwareUpdate=(0,SO.createCustomErrorClass)("UserRefusedFirmwareUpdate"),yO.UserRefusedAllowManager=(0,SO.createCustomErrorClass)("UserRefusedAllowManager"),yO.UserRefusedOnDevice=(0,SO.createCustomErrorClass)("UserRefusedOnDevice"),yO.TransportOpenUserCancelled=(0,SO.createCustomErrorClass)("TransportOpenUserCancelled"),yO.TransportInterfaceNotAvailable=(0,SO.createCustomErrorClass)("TransportInterfaceNotAvailable"),yO.TransportWebUSBGestureRequired=(0,SO.createCustomErrorClass)("TransportWebUSBGestureRequired"),yO.DeviceShouldStayInApp=(0,SO.createCustomErrorClass)("DeviceShouldStayInApp"),yO.WebsocketConnectionError=(0,SO.createCustomErrorClass)("WebsocketConnectionError"),yO.WebsocketConnectionFailed=(0,SO.createCustomErrorClass)("WebsocketConnectionFailed"),yO.WrongDeviceForAccount=(0,SO.createCustomErrorClass)("WrongDeviceForAccount"),yO.WrongAppForCurrency=(0,SO.createCustomErrorClass)("WrongAppForCurrency"),yO.ETHAddressNonEIP=(0,SO.createCustomErrorClass)("ETHAddressNonEIP"),yO.CantScanQRCode=(0,SO.createCustomErrorClass)("CantScanQRCode"),yO.FeeNotLoaded=(0,SO.createCustomErrorClass)("FeeNotLoaded"),yO.FeeRequired=(0,SO.createCustomErrorClass)("FeeRequired"),yO.FeeTooHigh=(0,SO.createCustomErrorClass)("FeeTooHigh"),yO.SyncError=(0,SO.createCustomErrorClass)("SyncError"),yO.PairingFailed=(0,SO.createCustomErrorClass)("PairingFailed"),yO.GenuineCheckFailed=(0,SO.createCustomErrorClass)("GenuineCheckFailed"),yO.LedgerAPI4xx=(0,SO.createCustomErrorClass)("LedgerAPI4xx"),yO.LedgerAPI5xx=(0,SO.createCustomErrorClass)("LedgerAPI5xx"),yO.FirmwareOrAppUpdateRequired=(0,SO.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),yO.NoDBPathGiven=(0,SO.createCustomErrorClass)("NoDBPathGiven"),yO.DBWrongPassword=(0,SO.createCustomErrorClass)("DBWrongPassword"),yO.DBNotReset=(0,SO.createCustomErrorClass)("DBNotReset"),IO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportError",(function(t){return new IO(t.message,t.id)}));var TO=yO.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function OO(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function AO(t){this.name="TransportStatusError";var e=Object.keys(TO).find((function(e){return TO[e]===t}))||"UNKNOWN_ERROR",r=OO(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}AO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new AO(t.statusCode)})),Object.defineProperty(gO,"__esModule",{value:!0}),gO.getAltStatusMessage=gO.StatusCodes=gO.TransportStatusError=gO.TransportError=void 0;var kO,PO=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[xO.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new xO.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new xO.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=NO(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new xO.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return PO(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new xO.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new xO.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();BO.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",BO.ErrorMessage_NoDeviceFound="No Ledger device found",gO.default=BO;var CO={};Object.defineProperty(CO,"__esModule",{value:!0});var UO=yO;function LO(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var DO={data:Buffer.alloc(0),dataLength:0,sequence:0};CO.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([LO(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var HO={};Object.defineProperty(HO,"__esModule",{value:!0});var jO=Object.assign||function(t){for(var e=1;e>8;return KO.find((function(t){return t.productIdMM===r}))},HO.identifyProductName=function(t){var e=FO[t];return KO.find((function(t){return t.id===e}))};var GO=[],WO={};for(var VO in qO){var $O=qO[VO],zO=$O.bluetoothSpec;if(zO)for(var XO=0;XO0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",oA());case 6:case"end":return t.stop()}}),t,this)}))),function(){return iA.apply(this,arguments)});var uA=HO;function aA(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var hA=[{vendorId:uA.ledgerUSBVendorId}];eA.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(dO,"__esModule",{value:!0});var fA=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,lA.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,dA.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,dA.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new gA.DisconnectedDeviceDuringOperation(e.message);throw e}))}},EA=dO.default=wA,_A=Object.freeze(e({__proto__:null,default:EA},[dO]));t.Btc=pO,t.TransportWebUSB=_A,Object.defineProperty(t,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 36b5dcd8764e6e5ed5b4c72521a1dfc467633213 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 14:41:19 +1100 Subject: [PATCH 11/78] ... --- js/ledger.js | 1 + 1 file changed, 1 insertion(+) diff --git a/js/ledger.js b/js/ledger.js index f1bc9122..bac16a32 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -5,6 +5,7 @@ window.Buffer = buffer.Buffer; !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}const i=2147483648;var o=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=i)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[s]+=i;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new o(n)},o.prototype.toPathArray=function(){return this.path},o.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var s=o,u=n(Object.freeze({__proto__:null,default:{}})),a=u.createHash,h={exports:{}},f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p=!1;function d(){p=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+f[i>>12&63]+f[i>>6&63]+f[63&i]);return o.join("")}function y(t){var e;p||d();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=f[e>>2],i+=f[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=f[e>>10],i+=f[e>>4&63],i+=f[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function m(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var w={}.toString,b=Array.isArray||function(t){return"[object Array]"==w.call(t)};I.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=_();function _(){return I.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function S(t,e){if(_()=_())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_().toString(16)+" bytes");return 0|t}function M(t){return!(null==t||!t._isBuffer)}function x(t,e){if(M(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return it(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ot(t).length;default:if(n)return it(t).length;e=(""+e).toLowerCase(),n=!0}}function R(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return $(this,e,r);case"utf8":case"utf-8":return K(this,e,r);case"ascii":return W(this,e,r);case"latin1":case"binary":return V(this,e,r);case"base64":return F(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function N(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=I.from(e,n)),M(e))return 0===e.length?-1:C(t,e,r,n,i);if("number"==typeof e)return e&=255,I.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):C(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function C(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function F(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function K(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=G)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},I.prototype.compare=function(t,e,r,n,i){if(!M(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return U(this,t,e,r);case"utf8":case"utf-8":return L(this,t,e,r);case"ascii":return D(this,t,e,r);case"latin1":case"binary":return H(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var G=4096;function W(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!M(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Z(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function Q(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function tt(t,e,r,n,i){return i||Q(t,0,r,4),m(t,e,r,n,23,4),r+4}function et(t,e,r,n,i){return i||Q(t,0,r,8),m(t,e,r,n,52,8),r+8}I.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},I.prototype.readUInt8=function(t,e){return e||X(t,1,this.length),this[t]},I.prototype.readUInt16LE=function(t,e){return e||X(t,2,this.length),this[t]|this[t+1]<<8},I.prototype.readUInt16BE=function(t,e){return e||X(t,2,this.length),this[t]<<8|this[t+1]},I.prototype.readUInt32LE=function(t,e){return e||X(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},I.prototype.readUInt32BE=function(t,e){return e||X(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},I.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},I.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},I.prototype.readInt8=function(t,e){return e||X(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},I.prototype.readInt16LE=function(t,e){e||X(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt16BE=function(t,e){e||X(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt32LE=function(t,e){return e||X(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},I.prototype.readInt32BE=function(t,e){return e||X(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},I.prototype.readFloatLE=function(t,e){return e||X(t,4,this.length),v(this,t,!0,23,4)},I.prototype.readFloatBE=function(t,e){return e||X(t,4,this.length),v(this,t,!1,23,4)},I.prototype.readDoubleLE=function(t,e){return e||X(t,8,this.length),v(this,t,!0,52,8)},I.prototype.readDoubleBE=function(t,e){return e||X(t,8,this.length),v(this,t,!1,52,8)},I.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},I.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},I.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Z(this,t,e,!0),e+4},I.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},I.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},I.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},I.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Z(this,t,e,!0),e+4},I.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeFloatLE=function(t,e,r){return tt(this,t,e,!0,r)},I.prototype.writeFloatBE=function(t,e,r){return tt(this,t,e,!1,r)},I.prototype.writeDoubleLE=function(t,e,r){return et(this,t,e,!0,r)},I.prototype.writeDoubleBE=function(t,e,r){return et(this,t,e,!1,r)},I.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!I.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ot(t){return function(t){var e,r,n,i,o,s;p||d();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new l(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(rt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function st(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ut(t){return null!=t&&(!!t._isBuffer||at(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&at(t.slice(0,0))}(t))}function at(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ht=n(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:I,SlowBuffer:function(t){return+t!=t&&(t=0),I.alloc(+t)},isBuffer:ut})); /*! safe-buffer. MIT License. Feross Aboukhadijeh */ !function(t,e){var r=ht,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(h,h.exports);var ft=h.exports.Buffer;var ct=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ft.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ft.from(e)),!ft.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,k=0|s[6],P=8191&k,M=k>>>13,x=0|s[7],R=8191&x,N=x>>>13,B=0|s[8],C=8191&B,U=B>>>13,L=0|s[9],D=8191&L,H=L>>>13,j=0|u[0],q=8191&j,F=j>>>13,K=0|u[1],G=8191&K,W=K>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(c,q))|0)+((8191&(i=(i=Math.imul(c,F))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,F))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,F))+Math.imul(g,q)|0,o=Math.imul(g,F);var vt=(h+(n=n+Math.imul(c,G)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,G)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,F))+Math.imul(m,q)|0,o=Math.imul(m,F),n=n+Math.imul(d,G)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,W)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,F))+Math.imul(E,q)|0,o=Math.imul(E,F),n=n+Math.imul(v,G)|0,i=(i=i+Math.imul(v,W)|0)+Math.imul(m,G)|0,o=o+Math.imul(m,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,F))+Math.imul(I,q)|0,o=Math.imul(I,F),n=n+Math.imul(b,G)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(E,G)|0,o=o+Math.imul(E,W)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,F))+Math.imul(A,q)|0,o=Math.imul(A,F),n=n+Math.imul(S,G)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,G)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(P,q),i=(i=Math.imul(P,F))+Math.imul(M,q)|0,o=Math.imul(M,F),n=n+Math.imul(O,G)|0,i=(i=i+Math.imul(O,W)|0)+Math.imul(A,G)|0,o=o+Math.imul(A,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(R,q),i=(i=Math.imul(R,F))+Math.imul(N,q)|0,o=Math.imul(N,F),n=n+Math.imul(P,G)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,W)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,q),i=(i=Math.imul(C,F))+Math.imul(U,q)|0,o=Math.imul(U,F),n=n+Math.imul(R,G)|0,i=(i=i+Math.imul(R,W)|0)+Math.imul(N,G)|0,o=o+Math.imul(N,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,q),i=(i=Math.imul(D,F))+Math.imul(H,q)|0,o=Math.imul(H,F),n=n+Math.imul(C,G)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,z)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,G),i=(i=Math.imul(D,W))+Math.imul(H,G)|0,o=Math.imul(H,W),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(N,rt)|0,o=o+Math.imul(N,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,st)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ct)|0,o=o+Math.imul(A,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ht)|0)+Math.imul(N,at)|0,o=o+Math.imul(N,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(R,ct)|0,i=(i=i+Math.imul(R,lt)|0)+Math.imul(N,ct)|0,o=o+Math.imul(N,lt)|0;var xt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Rt=(h+(n=n+Math.imul(R,dt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(N,dt)|0))<<13)|0;h=((o=o+Math.imul(N,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Nt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=kt,a[13]=Pt,a[14]=Mt,a[15]=xt,a[16]=Rt,a[17]=Nt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Rt);var Nt={},Bt="6.5.4",Ct={},Ut=Lt;function Lt(t,e){if(!t)throw new Error(e||"Assertion failed")}Lt.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Dt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Dt),function(t){var e=t,r=Rt.exports,n=Ut,i=Dt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ct);var Ht,jt={exports:{}};function qt(t){this.rand=t}if(jt.exports=function(t){return Ht||(Ht=new qt(null)),Ht.generate(t)},jt.exports.Rand=qt,qt.prototype.generate=function(t){return this._rand(t)},qt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Yt=Xt;function Jt(t,e){this.curve=t,this.type=e,this.precomputed=null}Xt.prototype.point=function(){throw new Error("Not implemented")},Xt.prototype.validate=function(){throw new Error("Not implemented")},Xt.prototype._fixedNafMul=function(t,e){zt(t.precomputed);var r=t._getDoubles(),n=Vt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];zt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Xt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=$t(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Jt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},se.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},se.prototype.pointFromX=function(t,e){(t=new re(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},se.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},se.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ae.prototype.isInfinity=function(){return this.inf},ae.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ae.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ae.prototype.getX=function(){return this.x.fromRed()},ae.prototype.getY=function(){return this.y.fromRed()},ae.prototype.mul=function(t){return t=new re(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ae.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ae.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ae.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ae.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ae.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ne(he,ie.BasePoint),se.prototype.jpoint=function(t,e,r){return new he(this,t,e,r)},he.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},he.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},he.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},he.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},he.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},he.prototype.inspect=function(){return this.isInfinity()?"":""},he.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var fe=Rt.exports,ce=Zt.exports,le=Yt,pe=Ct;function de(t){le.call(this,"mont",t),this.a=new fe(t.a,16).toRed(this.red),this.b=new fe(t.b,16).toRed(this.red),this.i4=new fe(4).toRed(this.red).redInvm(),this.two=new fe(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}ce(de,le);var ge=de;function ye(t,e,r){le.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new fe(e,16),this.z=new fe(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}de.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},ce(ye,le.BasePoint),de.prototype.decodePoint=function(t,e){return this.point(pe.toArray(t,e),1)},de.prototype.point=function(t,e){return new ye(this,t,e)},de.prototype.pointFromJSON=function(t){return ye.fromJSON(this,t)},ye.prototype.precompute=function(){},ye.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ye.fromJSON=function(t,e){return new ye(t,e[0],e[1]||t.one)},ye.prototype.inspect=function(){return this.isInfinity()?"":""},ye.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ye.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ye.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ye.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ye.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ye.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ye.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ve=Ct,me=Rt.exports,we=Zt.exports,be=Yt,Ee=ve.assert;function _e(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,be.call(this,"edwards",t),this.a=new me(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new me(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new me(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ee(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}we(_e,be);var Se=_e;function Ie(t,e,r,n,i){be.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new me(e,16),this.y=new me(r,16),this.z=n?new me(n,16):this.curve.one,this.t=i&&new me(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}_e.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},_e.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},_e.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},_e.prototype.pointFromX=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},_e.prototype.pointFromY=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},_e.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},we(Ie,be.BasePoint),_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},_e.prototype.point=function(t,e,r,n){return new Ie(this,t,e,r,n)},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1],e[2])},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ie.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Ie.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ie.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ie.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Ie.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Ie.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ie.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ie.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ie.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ie.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ie.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ie.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ie.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ie.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ie.prototype.toP=Ie.prototype.normalize,Ie.prototype.mixedAdd=Ie.prototype.add,function(t){var e=t;e.base=Yt,e.short=ue,e.mont=ge,e.edwards=Se}(Kt);var Te={},Oe={},Ae={},ke=Ut,Pe=Zt.exports;function Me(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Re(t){return 1===t.length?"0"+t:t}function Ne(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ae.inherits=Pe,Ae.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Me(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ae.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ae.rotr32=function(t,e){return t>>>e|t<<32-e},Ae.rotl32=function(t,e){return t<>>32-e},Ae.sum32=function(t,e){return t+e>>>0},Ae.sum32_3=function(t,e,r){return t+e+r>>>0},Ae.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ae.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ae.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ae.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ae.sum64_lo=function(t,e,r,n){return e+n>>>0},Ae.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ae.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ae.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ae.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ae.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ae.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ae.shr64_hi=function(t,e,r){return t>>>r},Ae.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Be={},Ce=Ae,Ue=Ut;function Le(){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}Be.BlockHash=Le,Le.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},He.g1_256=function(t){return je(t,17)^je(t,19)^t>>>10};var Ge=Ae,We=Be,Ve=He,$e=Ge.rotl32,ze=Ge.sum32,Xe=Ge.sum32_5,Ye=Ve.ft_1,Je=We.BlockHash,Ze=[1518500249,1859775393,2400959708,3395469782];function Qe(){if(!(this instanceof Qe))return new Qe;Je.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ge.inherits(Qe,Je);var tr=Qe;Qe.blockSize=512,Qe.outSize=160,Qe.hmacStrength=80,Qe.padLength=64,Qe.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),bn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var An=On;On.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},On.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=In.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Rn=Rt.exports,Nn=Ct,Bn=Nn.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Bn(t.r&&t.s,"Signature without r or s"),this.r=new Rn(t.r,16),this.s=new Rn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Un=Cn;function Ln(){this.place=0}function Dn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function Hn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Nn.toArray(t,e);var r=new Ln;if(48!==t[r.place++])return!1;var n=Dn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Dn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Dn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Rn(o),this.s=new Rn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=Hn(e),r=Hn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];jn(n,e.length),(n=n.concat(e)).push(2),jn(n,r.length);var i=n.concat(r),o=[48];return jn(o,i.length),o=o.concat(i),Nn.encode(o,t)};var qn=Rt.exports,Fn=An,Kn=Ct,Gn=Te,Wn=jt.exports,Vn=Kn.assert,$n=xn,zn=Un;function Xn(t){if(!(this instanceof Xn))return new Xn(t);"string"==typeof t&&(Vn(Object.prototype.hasOwnProperty.call(Gn,t),"Unknown curve "+t),t=Gn[t]),t instanceof Gn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Yn=Xn;Xn.prototype.keyPair=function(t){return new $n(this,t)},Xn.prototype.keyFromPrivate=function(t,e){return $n.fromPrivate(this,t,e)},Xn.prototype.keyFromPublic=function(t,e){return $n.fromPublic(this,t,e)},Xn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Fn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Wn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new qn(2));;){var i=new qn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Xn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Xn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new qn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Fn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new qn(1)),h=0;;h++){var f=n.k?n.k(h):new qn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new zn({r:p,s:d,recoveryParam:g})}}}}}},Xn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new qn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new zn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Xn.prototype.recoverPubKey=function(t,e,r,n){Vn((3&r)===r,"The recovery param is more than two bits"),e=new zn(e,n);var i=this.n,o=new qn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Xn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new zn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Jn=Ct,Zn=Jn.assert,Qn=Jn.parseBytes,ti=Jn.cachedProperty;function ei(t,e){this.eddsa=t,this._secret=Qn(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=Qn(e.pub)}ei.fromPublic=function(t,e){return e instanceof ei?e:new ei(t,{pub:e})},ei.fromSecret=function(t,e){return e instanceof ei?e:new ei(t,{secret:e})},ei.prototype.secret=function(){return this._secret},ti(ei,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ti(ei,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ti(ei,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ti(ei,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ti(ei,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ti(ei,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ei.prototype.sign=function(t){return Zn(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ei.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ei.prototype.getSecret=function(t){return Zn(this._secret,"KeyPair is public only"),Jn.encode(this.secret(),t)},ei.prototype.getPublic=function(t){return Jn.encode(this.pubBytes(),t)};var ri=ei,ni=Rt.exports,ii=Ct,oi=ii.assert,si=ii.cachedProperty,ui=ii.parseBytes;function ai(t,e){this.eddsa=t,"object"!=typeof e&&(e=ui(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),oi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ni&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}si(ai,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),si(ai,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),si(ai,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),si(ai,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),ai.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},ai.prototype.toHex=function(){return ii.encode(this.toBytes(),"hex").toUpperCase()};var hi=ai,fi=Oe,ci=Te,li=Ct,pi=li.assert,di=li.parseBytes,gi=ri,yi=hi;function vi(t){if(pi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof vi))return new vi(t);t=ci[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=fi.sha512}var mi=vi;vi.prototype.sign=function(t,e){t=di(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},vi.prototype.verify=function(t,e,r){t=di(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},vi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Gi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Oi)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function Hi(t){return 4!==t[0]}function ji(t){return!!Ui(t)&&(t.compare(Oi)>0&&t.compare(Ai)<0)}function qi(t,e){return void 0===t&&void 0!==e?Hi(e):void 0===t||t}function Fi(t){return new Si(t)}function Ki(t){return t.toArrayLike(Buffer,"be",32)}function Gi(t){return Ii.curve.decodePoint(t)}function Wi(t,e){return Buffer.from(t._encode(e))}function Vi(t,e,r){if(!Ui(t))throw new TypeError(Ci);if(!ji(e))throw new TypeError(Ri);if(void 0!==r&&!Ui(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Fi(e),i=Fi(t);let o,s;Ti(t,e,(function(t){const e=Fi(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Pi),0!==o.isZero()&&(s=e.invm(Pi).mul(i.add(n.mul(o))).umod(Pi),0!==s.isZero()))}),ji,r),s.cmp(Mi)>0&&(s=Pi.sub(s));const u=Buffer.allocUnsafe(64);return Ki(o).copy(u,0),Ki(s).copy(u,32),u}var $i={isPoint:Di,isPointCompressed:function(t){return!!Di(t)&&Hi(t)},isPrivate:ji,pointAdd:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Di(e))throw new TypeError(Ni);const n=Gi(t),i=Gi(e),o=n.add(i);return o.isInfinity()?null:Wi(o,qi(r,t))},pointAddScalar:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t);if(0===e.compare(Oi))return Wi(i,n);const o=Fi(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:Wi(u,n)},pointCompress:function(t,e){if(!Di(t))throw new TypeError(Ni);const r=Gi(t);if(r.isInfinity())throw new TypeError(Ni);return Wi(r,qi(e,t))},pointFromScalar:function(t,e){if(!ji(t))throw new TypeError(Ri);const r=Fi(t),n=xi.mul(r);return n.isInfinity()?null:Wi(n,qi(e))},pointMultiply:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t),o=Fi(e),s=i.mul(o);return s.isInfinity()?null:Wi(s,n)},privateAdd:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.add(n).umod(Pi));return ji(i)?i:null},privateSub:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.sub(n).umod(Pi));return ji(i)?i:null},sign:function(t,e){return Vi(t,e)},signWithEntropy:function(t,e,r){return Vi(t,e,r)},verify:function(t,e,r,n){if(!Ui(t))throw new TypeError(Ci);if(!Di(e))throw new TypeError(Ni);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Ai)<0&&r.compare(Ai)<0}(r))throw new TypeError("Expected Signature");const i=Gi(e),o=Fi(r.slice(0,32)),s=Fi(r.slice(32,64));if(n&&s.cmp(Mi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Fi(t),a=s.invm(Pi),h=u.mul(a).umod(Pi),f=o.mul(a).umod(Pi),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Pi).eq(o)}};try{xt.exports=require("./native")}catch(t){xt.exports=$i}var zi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Xi in zi.Null=zi.Nil,zi)zi[Xi].toJSON=function(t){return t}.bind(null,Xi);var Yi=zi,Ji=Yi;function Zi(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Qi(t){return Ji.Nil(t)?"":Zi(t.constructor)}function to(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function eo(t){return Ji.Function(t)?t.toJSON?t.toJSON():Zi(t):Ji.Array(t)?"Array":t&&Ji.Object(t)?"Object":void 0!==t?t:""}function ro(t,e,r){var n=function(t){return Ji.Function(t)?"":Ji.String(t)?JSON.stringify(t):t&&Ji.Object(t)?"":t}(e);return"Expected "+eo(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function no(t,e,r){r=r||Qi(e),this.message=ro(t,e,r),to(this,no),this.__type=t,this.__value=e,this.__valueTypeName=r}function io(t,e,r,n,i){t?(i=i||Qi(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ro('property "'+eo(r)+o+eo(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',to(this,no),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}no.prototype=Object.create(Error.prototype),no.prototype.constructor=no,io.prototype=Object.create(Error.prototype),io.prototype.constructor=no;var oo={TfTypeError:no,TfPropertyTypeError:io,tfCustomError:function(t,e){return new no(t,{},e)},tfSubError:function(t,e,r){return t instanceof io?(e=e+"."+t.__property,t=new io(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof no&&(t=new io(t.__type,e,r,t.__value,t.__valueTypeName)),to(t),t},tfJSON:eo,getValueTypeName:Qi},so=Yi,uo=oo;function ao(t){return Buffer.isBuffer(t)}function ho(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function fo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw uo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var co=fo.bind(null,so.Array),lo=fo.bind(null,ao),po=fo.bind(null,ho),go=fo.bind(null,so.String);var yo=Math.pow(2,53)-1;var vo={ArrayN:co,Buffer:ao,BufferN:lo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:ho,HexN:po,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-yo&&t<=yo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=yo&&Math.floor(t)===t}};for(var mo in vo)vo[mo].toJSON=function(t){return t}.bind(null,mo);var wo=vo,bo=Yi,Eo=oo.tfJSON,_o=oo.TfTypeError,So=oo.TfPropertyTypeError,Io=oo.tfSubError,To=oo.getValueTypeName,Oo={arrayOf:function(t,e){function r(r,n){return!!bo.Array(r)&&(!bo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw Io(t,r)}}))))))}return t=Ao(t),e=e||{},r.toJSON=function(){var r="["+Eo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return bo.Nil(r)||e(r,n,t)}return e=Ao(e),r.toJSON=function(){return"?"+Eo(e)},r},map:function(t,e){function r(r,n){if(!bo.Object(r))return!1;if(bo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw Io(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw Io(t,i)}}return!0}return t=Ao(t),e&&(e=Ao(e)),r.toJSON=e?function(){return"{"+Eo(e)+": "+Eo(t)+"}"}:function(){return"{"+Eo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ao(t[r]);function n(t,r){if(!bo.Object(t))return!1;if(bo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw Io(t,n)}if(r)for(n in t)if(!e[n])throw new So(void 0,n);return!0}return n.toJSON=function(){return Eo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join(" & ")},e},quacksLike:function(t){function e(e){return t===To(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return!bo.Nil(e)&&(!bo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw Io(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Eo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ao(t){if(bo.String(t))return"?"===t[0]?Oo.maybe(t.slice(1)):bo[t]||Oo.quacksLike(t);if(t&&bo.Object(t)){if(bo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Oo.arrayOf(t[0])}return Oo.object(t)}return bo.Function(t)?t:Oo.value(t)}function ko(t,e,r,n){if(bo.Function(t)){if(t(e,r))return!0;throw new _o(n||t,e)}return ko(Ao(t),e,r)}for(var Po in Oo.oneOf=Oo.anyOf,bo)ko[Po]=bo[Po];for(Po in Oo)ko[Po]=Oo[Po];var Mo=wo;for(Po in Mo)ko[Po]=Mo[Po];ko.compile=Ao,ko.TfTypeError=_o,ko.TfPropertyTypeError=So;var xo=ko,Ro=vt;function No(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Bo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return No(Ro.decode(t),e)},decodeRaw:No,encode:function(t,e,r){return"number"==typeof t?Ro.encode(Bo(t,e,r)):Ro.encode(Bo(t.version,t.privateKey,t.compressed))},encodeRaw:Bo};Object.defineProperty(Ot,"__esModule",{value:!0});const Uo=At,Lo=vt,Do=xt.exports,Ho=xo,jo=Co,qo=Ho.BufferN(32),Fo=Ho.compile({wif:Ho.UInt8,bip32:{public:Ho.UInt32,private:Ho.UInt32}}),Ko={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Go=2147483648,Wo=Math.pow(2,31)-1;function Vo(t){return Ho.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function $o(t){return Ho.UInt32(t)&&t<=Wo}class zo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,Ho(Fo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Do.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Uo.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Jo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Lo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return jo.encode(this.network.wif,this.privateKey,!0)}derive(t){Ho(Ho.UInt32,t);const e=t>=Go,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Uo.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Do.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Do.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Jo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Do.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Yo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return Ho($o,t),this.derive(t+Go)}derivePath(t){Ho(Vo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Do.sign(t,this.privateKey);{let e=Do.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Do.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Do.verify(t,this.publicKey,e)}}function Xo(t,e,r){return Yo(t,e,r)}function Yo(t,e,r,n,i,o){if(Ho({privateKey:qo,chainCode:qo},{privateKey:t,chainCode:e}),r=r||Ko,!Do.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new zo(t,void 0,e,r,n,i,o)}function Jo(t,e,r,n,i,o){if(Ho({publicKey:Ho.BufferN(33),chainCode:qo},{publicKey:t,chainCode:e}),r=r||Ko,!Do.isPoint(t))throw new TypeError("Point is not on the curve");return new zo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Lo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Ko;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Yo(r.slice(46,78),u,e,i,s,o)}else{a=Jo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Xo,Ot.fromPublicKey=function(t,e,r){return Jo(t,e,r)},Ot.fromSeed=function(t,e){if(Ho(Ho.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Ko;const r=Uo.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Xo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var Zo=Ot;Tt.fromSeed=Zo.fromSeed,Tt.fromBase58=Zo.fromBase58,Tt.fromPublicKey=Zo.fromPublicKey,Tt.fromPrivateKey=Zo.fromPrivateKey;var Qo={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ts.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ts.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var es={},rs={},ns={},is={};Object.defineProperty(is,"__esModule",{value:!0}),is.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0});const us=xo,as=Math.pow(2,31)-1;function hs(t){return us.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ss.UInt31=function(t){return us.UInt32(t)&&t<=as},ss.BIP32Path=hs,hs.toJSON=()=>"BIP32 derivation path",ss.Signer=function(t){return(us.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ss.Satoshi=function(t){return us.UInt53(t)&&t<=21e14},ss.ECPoint=us.quacksLike("Point"),ss.Network=us.compile({messagePrefix:us.oneOf(us.Buffer,us.String),bip32:{public:us.UInt32,private:us.UInt32},pubKeyHash:us.UInt8,scriptHash:us.UInt8,wif:us.UInt8}),ss.Buffer256bit=us.BufferN(32),ss.Hash160bit=us.BufferN(20),ss.Hash256bit=us.BufferN(32),ss.Number=us.Number,ss.Array=us.Array,ss.Boolean=us.Boolean,ss.String=us.String,ss.Buffer=us.Buffer,ss.Hex=us.Hex,ss.maybe=us.maybe,ss.tuple=us.tuple,ss.UInt8=us.UInt8,ss.UInt32=us.UInt32,ss.Function=us.Function,ss.BufferN=us.BufferN,ss.Null=us.Null,ss.oneOf=us.oneOf;var fs=h.exports.Buffer;var cs={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=fs.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(os,"__esModule",{value:!0});const ls=ss,ps=cs,ds=xo,gs=Buffer.alloc(1,0);function ys(t){let e=0;for(;0===t[e];)++e;return e===t.length?gs:128&(t=t.slice(e))[0]?Buffer.concat([gs,t],1+t.length):t}function vs(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}os.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=ps.decode(t.slice(0,-1)),i=vs(n.r),o=vs(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},os.encode=function(t,e){ds({signature:ls.BufferN(64),hashType:ls.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=ys(t.slice(0,32)),o=ys(t.slice(32,64));return Buffer.concat([ps.encode(i,o),n])};var ms={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ws=ms;function bs(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ws.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ws.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},_s=ms,Ss={};for(var Is in _s){Ss[_s[Is]]=Is}var Ts=Ss;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=is,r=os,n=ss,i=cs,o=xt.exports,s=Es,u=xo;t.OPS=ms;const a=Ts,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(ns);var Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Os.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(rs,"__esModule",{value:!0});const As=ts,ks=ns,Ps=Os,Ms=xo,xs=ks.OPS;rs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ms({network:Ms.maybe(Ms.Object),output:Ms.maybe(Ms.Buffer),data:Ms.maybe(Ms.arrayOf(Ms.Buffer))},t);const r={name:"embed",network:t.network||As.bitcoin};if(Ps.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Ps.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ms.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});const Ns=ts,Bs=ns,Cs=Os,Us=Bs.OPS,Ls=xo,Ds=xt.exports,Hs=Us.OP_RESERVED;function js(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Rs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Bs.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Us.OP_0)}e=Object.assign({validate:!0},e||{}),Ls({network:Ls.maybe(Ls.Object),m:Ls.maybe(Ls.Number),n:Ls.maybe(Ls.Number),output:Ls.maybe(Ls.Buffer),pubkeys:Ls.maybe(Ls.arrayOf(Ds.isPoint)),signatures:Ls.maybe(Ls.arrayOf(r)),input:Ls.maybe(Ls.Buffer)},t);const n={network:t.network||Ns.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Bs.decompile(t),n.m=i[0]-Hs,n.n=i[i.length-2]-Hs,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Bs.compile([].concat(Hs+t.m,t.pubkeys,Hs+n.n,Us.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Bs.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Bs.compile([Us.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Ls.Number(i[0]))throw new TypeError("Output is invalid");if(!Ls.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Us.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ds.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!js(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Us.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!js(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var qs={};Object.defineProperty(qs,"__esModule",{value:!0});const Fs=ts,Ks=ns,Gs=Os,Ws=xo,Vs=Ks.OPS,$s=xt.exports;qs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ws({network:Ws.maybe(Ws.Object),output:Ws.maybe(Ws.Buffer),pubkey:Ws.maybe($s.isPoint),signature:Ws.maybe(Ks.isCanonicalScriptSignature),input:Ws.maybe(Ws.Buffer)},t);const r=Gs.value((()=>Ks.decompile(t.input))),n={name:"p2pk",network:t.network||Fs.bitcoin};if(Gs.prop(n,"output",(()=>{if(t.pubkey)return Ks.compile([t.pubkey,Vs.OP_CHECKSIG])})),Gs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Gs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Gs.prop(n,"input",(()=>{if(t.signature)return Ks.compile([t.signature])})),Gs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==Vs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!$s.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Ks.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var zs={},Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=a;function Js(t){try{return Ys("rmd160").update(t).digest()}catch(e){return Ys("ripemd160").update(t).digest()}}function Zs(t){return Ys("sha256").update(t).digest()}Xs.ripemd160=Js,Xs.sha1=function(t){return Ys("sha1").update(t).digest()},Xs.sha256=Zs,Xs.hash160=function(t){return Js(Zs(t))},Xs.hash256=function(t){return Zs(Zs(t))},Object.defineProperty(zs,"__esModule",{value:!0});const Qs=Xs,tu=ts,eu=ns,ru=Os,nu=xo,iu=eu.OPS,ou=xt.exports,su=vt;zs.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),nu({network:nu.maybe(nu.Object),address:nu.maybe(nu.String),hash:nu.maybe(nu.BufferN(20)),output:nu.maybe(nu.BufferN(25)),pubkey:nu.maybe(ou.isPoint),signature:nu.maybe(eu.isCanonicalScriptSignature),input:nu.maybe(nu.Buffer)},t);const r=ru.value((()=>{const e=su.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=ru.value((()=>eu.decompile(t.input))),i=t.network||tu.bitcoin,o={name:"p2pkh",network:i};if(ru.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),su.encode(t)})),ru.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?Qs.hash160(t.pubkey||o.pubkey):void 0)),ru.prop(o,"output",(()=>{if(o.hash)return eu.compile([iu.OP_DUP,iu.OP_HASH160,o.hash,iu.OP_EQUALVERIFY,iu.OP_CHECKSIG])})),ru.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),ru.prop(o,"signature",(()=>{if(t.input)return n()[0]})),ru.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return eu.compile([t.signature,t.pubkey])})),ru.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==iu.OP_DUP||t.output[1]!==iu.OP_HASH160||20!==t.output[2]||t.output[23]!==iu.OP_EQUALVERIFY||t.output[24]!==iu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=Qs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!eu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ou.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=Qs.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var uu={};Object.defineProperty(uu,"__esModule",{value:!0});const au=Xs,hu=ts,fu=ns,cu=Os,lu=xo,pu=fu.OPS,du=vt;uu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),lu({network:lu.maybe(lu.Object),address:lu.maybe(lu.String),hash:lu.maybe(lu.BufferN(20)),output:lu.maybe(lu.BufferN(23)),redeem:lu.maybe({network:lu.maybe(lu.Object),output:lu.maybe(lu.Buffer),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))}),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||hu.bitcoin);const n={network:r},i=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=cu.value((()=>fu.decompile(t.input))),s=cu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:fu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(cu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),du.encode(t)})),cu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?au.hash160(n.redeem.output):void 0)),cu.prop(n,"output",(()=>{if(n.hash)return fu.compile([pu.OP_HASH160,n.hash,pu.OP_EQUAL])})),cu.prop(n,"redeem",(()=>{if(t.input)return s()})),cu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return fu.compile([].concat(fu.decompile(t.redeem.input),t.redeem.output))})),cu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),cu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==pu.OP_HASH160||20!==t.output[1]||t.output[22]!==pu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=fu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=au.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=fu.decompile(t.input);if(!fu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var gu={},yu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vu={},mu=0;mu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Eu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=bu(e)^n>>5}for(e=bu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Eu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Su(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Eu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=bu(n)^s,i+=yu.charAt(s)}for(o=0;o<6;++o)n=bu(n);for(n^=1,o=0;o<6;++o){i+=yu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(gu,"__esModule",{value:!0});const Tu=Xs,Ou=ts,Au=ns,ku=Os,Pu=xo,Mu=Au.OPS,xu=xt.exports,Ru=Iu,Nu=Buffer.alloc(0);gu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Pu({address:Pu.maybe(Pu.String),hash:Pu.maybe(Pu.BufferN(20)),input:Pu.maybe(Pu.BufferN(0)),network:Pu.maybe(Pu.Object),output:Pu.maybe(Pu.BufferN(22)),pubkey:Pu.maybe(xu.isPoint),signature:Pu.maybe(Au.isCanonicalScriptSignature),witness:Pu.maybe(Pu.arrayOf(Pu.Buffer))},t);const r=ku.value((()=>{const e=Ru.decode(t.address),r=e.words.shift(),n=Ru.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Ou.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Ru.toWords(i.hash);return t.unshift(0),Ru.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Tu.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Au.compile([Mu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Nu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Mu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Tu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Au.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Tu.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0});const Cu=Xs,Uu=ts,Lu=ns,Du=Os,Hu=xo,ju=Lu.OPS,qu=xt.exports,Fu=Iu,Ku=Buffer.alloc(0);function Gu(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!qu.isPoint(t))}Bu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Hu({network:Hu.maybe(Hu.Object),address:Hu.maybe(Hu.String),hash:Hu.maybe(Hu.BufferN(32)),output:Hu.maybe(Hu.BufferN(34)),redeem:Hu.maybe({input:Hu.maybe(Hu.Buffer),network:Hu.maybe(Hu.Object),output:Hu.maybe(Hu.Buffer),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))}),input:Hu.maybe(Hu.BufferN(0)),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))},t);const r=Du.value((()=>{const e=Fu.decode(t.address),r=e.words.shift(),n=Fu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Du.value((()=>Lu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Uu.bitcoin);const o={network:i};if(Du.prop(o,"address",(()=>{if(!o.hash)return;const t=Fu.toWords(o.hash);return t.unshift(0),Fu.encode(i.bech32,t)})),Du.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Du.prop(o,"output",(()=>{if(o.hash)return Lu.compile([ju.OP_0,o.hash])})),Du.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ku,witness:t.witness.slice(0,-1)}})),Du.prop(o,"input",(()=>{if(o.witness)return Ku})),Du.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Lu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Ku,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Du.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==ju.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Lu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Lu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Gu)||t.redeem.output&&(Lu.decompile(t.redeem.output)||[]).some(Gu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Gu)||(Lu.decompile(e)||[]).some(Gu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(es,"__esModule",{value:!0});const Wu=rs;es.embed=Wu.p2data;const Vu=Rs;es.p2ms=Vu.p2ms;const $u=qs;es.p2pk=$u.p2pk;const zu=zs;es.p2pkh=zu.p2pkh;const Xu=uu;es.p2sh=Xu.p2sh;const Yu=gu;es.p2wpkh=Yu.p2wpkh;const Ju=Bu;es.p2wsh=Ju.p2wsh,Object.defineProperty(Qo,"__esModule",{value:!0});const Zu=ts,Qu=es,ta=ns,ea=ss,ra=Iu,na=vt,ia=xo;function oa(t){const e=na.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function sa(t){const e=ra.decode(t),r=ra.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}Qo.fromBase58Check=oa,Qo.fromBech32=sa,Qo.toBase58Check=function(t,e){ia(ea.tuple(ea.Hash160bit,ea.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),na.encode(r)},Qo.toBech32=function(t,e,r){const n=ra.toWords(t);return n.unshift(e),ra.encode(r,n)},Qo.fromOutputScript=function(t,e){e=e||Zu.bitcoin;try{return Qu.p2pkh({output:t,network:e}).address}catch(t){}try{return Qu.p2sh({output:t,network:e}).address}catch(t){}try{return Qu.p2wpkh({output:t,network:e}).address}catch(t){}try{return Qu.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ta.toASM(t)+" has no matching Address")},Qo.toOutputScript=function(t,e){let r,n;e=e||Zu.bitcoin;try{r=oa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return Qu.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return Qu.p2sh({hash:r.hash}).output}else{try{n=sa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return Qu.p2wpkh({hash:n.data}).output;if(32===n.data.length)return Qu.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ua={},aa=u.randomBytes;Object.defineProperty(ua,"__esModule",{value:!0});const ha=ts,fa=ss,ca=xt.exports,la=aa,pa=xo,da=Co,ga=pa.maybe(pa.compile({compressed:fa.maybe(fa.Boolean),network:fa.maybe(fa.Network)}));class ya{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ha.bitcoin,void 0!==e&&(this.__Q=ca.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=ca.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return da.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return ca.sign(t,this.__D);{let e=ca.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=ca.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return ca.verify(t,this.publicKey,e)}}function va(t,e){if(pa(fa.Buffer256bit,t),!ca.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return pa(ga,e),new ya(t,void 0,e)}ua.fromPrivateKey=va,ua.fromPublicKey=function(t,e){return pa(ca.isPoint,t),pa(ga,e),new ya(void 0,t,e)},ua.fromWIF=function(t,e){const r=da.decode(t),n=r.version;if(fa.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ha.bitcoin,n!==e.wif)throw new Error("Invalid network version");return va(r.privateKey,{compressed:r.compressed,network:e})},ua.makeRandom=function(t){pa(ga,t),void 0===t&&(t={});const e=t.rng||la;let r;do{r=e(32),pa(fa.Buffer256bit,r)}while(!ca.isPrivate(r));return va(r,t)};var ma={},wa={},ba=h.exports.Buffer;function Ea(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function _a(t){return Ea(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Sa={encode:function t(e,r,n){if(Ea(e),r||(r=ba.allocUnsafe(_a(e))),!ba.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!ba.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ea(o),o},encodingLength:_a};Object.defineProperty(wa,"__esModule",{value:!0});const Ia=ss,Ta=xo,Oa=Sa;function Aa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Aa(n+r,9007199254740991),n+r}function Pa(t,e,r){return Aa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}wa.readUInt64LE=ka,wa.writeUInt64LE=Pa,wa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};wa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ta(Ia.tuple(Ia.Buffer,Ia.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Oa.decode(this.buffer,this.offset);return this.offset+=Oa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+La.encodingLength(this.ins.length)+La.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Da(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Da(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return La.encodingLength(e)+t.reduce(((t,e)=>t+Da(e)),0)}(e.witness)),0):0)}clone(){const t=new Wa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return Fa;const n=Na.compile(Na.decompile(e).filter((t=>t!==Ba.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Wa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Wa.SIGHASH_SINGLE){if(t>=this.outs.length)return Fa;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Wa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=Ha})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ra.hash256(o)}hashForWitnessV0(t,e,r,n){Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=qa,u=qa,a=qa;if(n&Wa.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ra.hash256(o)),n&Wa.SIGHASH_ANYONECANPAY||(31&n)===Wa.SIGHASH_SINGLE||(31&n)===Wa.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ra.hash256(o)),(31&n)!==Wa.SIGHASH_SINGLE&&(31&n)!==Wa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Da(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ra.hash256(o)}else if((31&n)===Wa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Wa.DEFAULT_SEQUENCE=4294967295,Wa.SIGHASH_ALL=1,Wa.SIGHASH_NONE=2,Wa.SIGHASH_SINGLE=3,Wa.SIGHASH_ANYONECANPAY=128,Wa.ADVANCED_TRANSACTION_MARKER=0,Wa.ADVANCED_TRANSACTION_FLAG=1,Ma.Transaction=Wa;Object.defineProperty(ma,"__esModule",{value:!0});const Va=wa,$a=Xs,za=Ma,Xa=ss,Ya=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=za.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Ja([{getHash:Xa.Function}],t),0===t.length)throw Qa;if(e&&!rh(t))throw th;const r=t.map((t=>t.getHash(e))),n=Ya(r,$a.hash256);return e?$a.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!rh(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+Za.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return $a.hash256(this.toBuffer(!0))}getId(){return Va.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new Va.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(Za.encode(this.transactions.length,e,r.offset),r.offset+=Za.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=Va.reverseBuffer(this.getHash()),e=eh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw Qa;const t=eh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw Qa;if(!this.hasWitnessCommit())throw th;const t=eh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function rh(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ma.Block=eh;var nh={},ih={},oh={},sh={},uh={},ah={},hh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(hh);var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const ch=hh;fh.decode=function(t){if(t.key[0]!==ch.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},fh.encode=function(t){const e=Buffer.from([ch.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},fh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",fh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},fh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=hh;lh.encode=function(t){return{key:Buffer.from([ph.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=hh;dh.decode=function(t){if(t.key[0]!==gh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},dh.encode=function(t){return{key:Buffer.from([gh.InputTypes.FINAL_SCRIPTSIG]),value:t}},dh.expected="Buffer",dh.check=function(t){return Buffer.isBuffer(t)},dh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var yh={};Object.defineProperty(yh,"__esModule",{value:!0});const vh=hh;yh.decode=function(t){if(t.key[0]!==vh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},yh.encode=function(t){return{key:Buffer.from([vh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},yh.expected="Buffer",yh.check=function(t){return Buffer.isBuffer(t)},yh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=hh;mh.decode=function(t){if(t.key[0]!==wh.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([wh.InputTypes.NON_WITNESS_UTXO]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=hh;bh.decode=function(t){if(t.key[0]!==Eh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},bh.encode=function(t){const e=Buffer.from([Eh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},bh.expected="{ pubkey: Buffer; signature: Buffer; }",bh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},bh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=hh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},_h.encode=function(t){return{key:Buffer.from([Sh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},_h.expected="string",_h.check=function(t){return"string"==typeof t},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=hh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ih.encode=function(t){const e=Buffer.from([Th.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ih.expected="number",Ih.check=function(t){return"number"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Oh={},Ah={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Ph(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Mh(t){return Ph(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Ph(e),r||(r=Buffer.allocUnsafe(Mh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Ph(i),i}},kh.encodingLength=Mh,Object.defineProperty(Ah,"__esModule",{value:!0});const xh=kh;function Rh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Nh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ah.range=t=>[...Array(t).keys()],Ah.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Dh={};Object.defineProperty(Dh,"__esModule",{value:!0}),Dh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var Hh={};Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(ah,"__esModule",{value:!0});const qh=hh,Fh=dh,Kh=yh,Gh=mh,Wh=bh,Vh=_h,$h=Ih,zh=Oh,Xh=Lh,Yh=Dh,Jh=Hh,Zh=jh,Qh={unsignedTx:lh,globalXpub:fh,checkPubkey:Yh.makeChecker([])};ah.globals=Qh;const tf={nonWitnessUtxo:Gh,partialSig:Wh,sighashType:$h,finalScriptSig:Fh,finalScriptWitness:Kh,porCommitment:Vh,witnessUtxo:zh,bip32Derivation:Xh.makeConverter(qh.InputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.InputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.InputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.InputTypes.PARTIAL_SIG,qh.InputTypes.BIP32_DERIVATION])};ah.inputs=tf;const ef={bip32Derivation:Xh.makeConverter(qh.OutputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.OutputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.OutputTypes.BIP32_DERIVATION])};ah.outputs=ef,Object.defineProperty(uh,"__esModule",{value:!0});const rf=ah,nf=Ah,of=kh,sf=hh;function uf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function af(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case sf.GlobalTypes.UNSIGNED_TX:if(uf("global",t.key,sf.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case sf.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(rf.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of nf.range(s)){const e={};for(const n of r[t])switch(rf.inputs.checkPubkey(n),n.key[0]){case sf.InputTypes.NON_WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=rf.inputs.nonWitnessUtxo.decode(n);break;case sf.InputTypes.WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=rf.inputs.witnessUtxo.decode(n);break;case sf.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(rf.inputs.partialSig.decode(n));break;case sf.InputTypes.SIGHASH_TYPE:if(uf("input",n.key,sf.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=rf.inputs.sighashType.decode(n);break;case sf.InputTypes.REDEEM_SCRIPT:if(uf("input",n.key,sf.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=rf.inputs.redeemScript.decode(n);break;case sf.InputTypes.WITNESS_SCRIPT:if(uf("input",n.key,sf.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=rf.inputs.witnessScript.decode(n);break;case sf.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.inputs.bip32Derivation.decode(n));break;case sf.InputTypes.FINAL_SCRIPTSIG:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=rf.inputs.finalScriptSig.decode(n);break;case sf.InputTypes.FINAL_SCRIPTWITNESS:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=rf.inputs.finalScriptWitness.decode(n);break;case sf.InputTypes.POR_COMMITMENT:uf("input",n.key,sf.InputTypes.POR_COMMITMENT),e.porCommitment=rf.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of nf.range(u)){const e={};for(const r of n[t])switch(rf.outputs.checkPubkey(r),r.key[0]){case sf.OutputTypes.REDEEM_SCRIPT:if(uf("output",r.key,sf.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=rf.outputs.redeemScript.decode(r);break;case sf.OutputTypes.WITNESS_SCRIPT:if(uf("output",r.key,sf.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=rf.outputs.witnessScript.decode(r);break;case sf.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}uh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=of.decode(t,r);r+=of.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===sf.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of nf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of nf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return af(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},uh.checkKeyBuffer=uf,uh.psbtFromKeyVals=af;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});const ff=ah,cf=Ah;hf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=df({globalMap:t,inputs:e,outputs:r}),s=cf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(cf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const lf=(t,e)=>t.key.compare(e.key);function pf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(lf)}function df({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:pf(t,ff.globals),inputKeyVals:e.map((t=>pf(t,ff.inputs))),outputKeyVals:r.map((t=>pf(t,ff.outputs)))}}hf.psbtToKeyVals=df,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(uh),e(hf)}(sh),Object.defineProperty(oh,"__esModule",{value:!0});const gf=sh;function yf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function vf(t){return t.globalMap.unsignedTx}function mf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}oh.combine=function(t){const e=t[0],r=gf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=vf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=mf(r.globalKeyVals),s=r.inputKeyVals.map(mf),u=r.outputKeyVals.map(mf);for(const t of n){const e=vf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=gf.psbtToKeyVals(t);mf(n.globalKeyVals).forEach(yf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return gf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var wf={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ah;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(wf),Object.defineProperty(ih,"__esModule",{value:!0});const bf=oh,Ef=sh,_f=hh,Sf=wf;ih.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ef.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ef.psbtToBuffer(this)}updateGlobal(t){return Sf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.updateInput(e,r),this}updateOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Sf.checkHasKey(t,this.globalMap.unknownKeyVals,Sf.getEnumLength(_f.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Sf.checkForInput(this.inputs,t);Sf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=bf.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(nh,"__esModule",{value:!0});const If=ih,Tf=kh,Of=wf,Af=Qo,kf=wa,Pf=Xs,Mf=ua,xf=es,Rf=ns,Nf=Ma,Bf={network:ts.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new If.Psbt(new Lf)){this.data=e,this.opts=Object.assign({},Bf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=If.Psbt.fromBuffer(t,Uf),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{Zf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Af.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Xf(t),this.opts.maximumFeeRate=t}setVersion(t){Xf(t),Yf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Xf(t),Yf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Xf(e),Yf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Yf(this.data.inputs,"addInput"),t.witnessScript&&gc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);Zf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&hc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Yf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Af.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(jf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return fc(this.data.inputs,r,e,!0),r}getFeeRate(){return rc("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return rc("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Of.checkForInput(this.data.inputs,0),mc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=nc){const r=Of.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=cc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Wf(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Rf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Of.checkForInput(this.data.inputs,t),r=dc(lc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Rf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||pc(r)||(n=r,Rf.isCanonicalScriptSignature(n)))return;var n;if(!Rf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=uc(t),r=e[e.length-1];if(pc(r))return;if(!Rf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+vc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=lc(r,e,n),{meaningfulScript:o}=dc(i,r,"input",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Of.checkForInput(this.data.inputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=dc(i,r,"output",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Of.checkForOutput(this.data.outputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Of.checkForInput(this.data.inputs,0);return mc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Rf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?oc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Jf(e.pubkey,h,"verify");const f=Mf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of mc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return sc(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=sc(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Rf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Rf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Df(this.__CACHE),this.data.toBuffer()}toHex(){return Df(this.__CACHE),this.data.toHex()}toBase64(){return Df(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&gc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&hc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}nh.Psbt=Cf;const Uf=t=>new Lf(t);class Lf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Nf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Df(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Hf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Mf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function jf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function qf(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Ff=qf(xf.p2ms),Kf=qf(xf.p2pk),Gf=qf(xf.p2pkh),Wf=qf(xf.p2wpkh),Vf=qf(xf.p2wsh),$f=qf(xf.p2sh);function zf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Xf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Yf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Rf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Rf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Rf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Rf.signature.decode(t.signature),i=[];n&Nf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Nf.Transaction.SIGHASH_ALL:break;case Nf.Transaction.SIGHASH_SINGLE:case Nf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Jf(t,e,r){if(!yc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function Zf(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function Qf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const tc=Qf(xf.p2sh,"Redeem script"),ec=Qf(xf.p2wsh,"Witness script");function rc(t,e,r,n){if(!r.every(jf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),fc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function nc(t,e,r,n,i,o){const s=vc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Hf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return Hf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=ac(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function ic(t,e,r,n,i){const o=Of.checkForInput(t,e),{hash:s,sighashType:u,script:a}=oc(e,o,n,!1,i);return Jf(r,a,"sign"),{hash:s,sighashType:u}}function oc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Nf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Nf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Nf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Nf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Nf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=cc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=dc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Wf(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function sc(t,e,r){const n=Of.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function uc(t){let e=0;function r(){const r=Tf.decode(t,e);return e+=Tf.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=uc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=cc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function cc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||hc(t,e,r),n[r]}function lc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return cc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function pc(t){return 33===t.length&&Rf.isCanonicalPubKey(t)}function dc(t,e,r,n,i){const o=$f(t),s=o&&n&&Vf(n),u=Vf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,tc(e,t,n,r),ec(e,n,i,r),gc(a)):u?(a=i,ec(e,t,i,r),gc(a)):o?(a=n,tc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function gc(t){if(Wf(t)||$f(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function yc(t,e){const r=Pf.hash160(t),n=Rf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function vc(t){return Wf(t)?"witnesspubkeyhash":Gf(t)?"pubkeyhash":Ff(t)?"multisig":Kf(t)?"pubkey":"nonstandard"}function mc(t){return[...Array(t).keys()]}var wc={},bc={},Ec={},_c={};Object.defineProperty(_c,"__esModule",{value:!0});const Sc=ns,Ic=ns;function Tc(t){return t===Ic.OPS.OP_0||Sc.isCanonicalScriptSignature(t)}function Oc(t,e){const r=Sc.decompile(t);return!(r.length<2)&&(r[0]===Ic.OPS.OP_0&&(e?r.slice(1).every(Tc):r.slice(1).every(Sc.isCanonicalScriptSignature)))}_c.check=Oc,Oc.toJSON=()=>"multisig input";var Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const kc=ns,Pc=ns,Mc=ss,xc=Pc.OPS.OP_RESERVED;function Rc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Pc.OPS.OP_CHECKMULTISIG)return!1;if(!Mc.Number(r[0]))return!1;if(!Mc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Ac.check=Rc,Rc.toJSON=()=>"multi-sig output",Object.defineProperty(Ec,"__esModule",{value:!0});const Nc=_c;Ec.input=Nc;const Bc=Ac;Ec.output=Bc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Uc=ns,Lc=Uc.OPS;function Dc(t){const e=Uc.compile(t);return e.length>1&&e[0]===Lc.OP_RETURN}Cc.check=Dc,Dc.toJSON=()=>"null data output";const Hc={check:Dc};Cc.output=Hc;var jc={},qc={};Object.defineProperty(qc,"__esModule",{value:!0});const Fc=ns;function Kc(t){const e=Fc.decompile(t);return 1===e.length&&Fc.isCanonicalScriptSignature(e[0])}qc.check=Kc,Kc.toJSON=()=>"pubKey input";var Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});const Wc=ns,Vc=ns;function $c(t){const e=Wc.decompile(t);return 2===e.length&&Wc.isCanonicalPubKey(e[0])&&e[1]===Vc.OPS.OP_CHECKSIG}Gc.check=$c,$c.toJSON=()=>"pubKey output",Object.defineProperty(jc,"__esModule",{value:!0});const zc=qc;jc.input=zc;const Xc=Gc;jc.output=Xc;var Yc={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});const Zc=ns;function Qc(t){const e=Zc.decompile(t);return 2===e.length&&Zc.isCanonicalScriptSignature(e[0])&&Zc.isCanonicalPubKey(e[1])}Jc.check=Qc,Qc.toJSON=()=>"pubKeyHash input";var tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=ns,rl=ns;function nl(t){const e=el.compile(t);return 25===e.length&&e[0]===rl.OPS.OP_DUP&&e[1]===rl.OPS.OP_HASH160&&20===e[2]&&e[23]===rl.OPS.OP_EQUALVERIFY&&e[24]===rl.OPS.OP_CHECKSIG}tl.check=nl,nl.toJSON=()=>"pubKeyHash output",Object.defineProperty(Yc,"__esModule",{value:!0});const il=Jc;Yc.input=il;const ol=tl;Yc.output=ol;var sl={},ul={},al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=ns,fl=ns;function cl(t){const e=hl.compile(t);return 22===e.length&&e[0]===fl.OPS.OP_0&&20===e[1]}al.check=cl,cl.toJSON=()=>"Witness pubKeyHash output";var ll={};Object.defineProperty(ll,"__esModule",{value:!0});const pl=ns,dl=ns;function gl(t){const e=pl.compile(t);return 34===e.length&&e[0]===dl.OPS.OP_0&&32===e[1]}ll.check=gl,gl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(ul,"__esModule",{value:!0});const yl=ns,vl=Ec,ml=jc,wl=Yc,bl=al,El=ll;function _l(t,e){const r=yl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=yl.decompile(yl.compile(r.slice(0,-1))),o=yl.decompile(n);return!!o&&(!!yl.isPushOnly(i)&&(1===r.length?El.check(o)||bl.check(o):!(!wl.input.check(i)||!wl.output.check(o))||(!(!vl.input.check(i,e)||!vl.output.check(o))||!(!ml.input.check(i)||!ml.output.check(o)))))}ul.check=_l,_l.toJSON=()=>"scriptHash input";var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Il=ns,Tl=ns;function Ol(t){const e=Il.compile(t);return 23===e.length&&e[0]===Tl.OPS.OP_HASH160&&20===e[1]&&e[22]===Tl.OPS.OP_EQUAL}Sl.check=Ol,Ol.toJSON=()=>"scriptHash output",Object.defineProperty(sl,"__esModule",{value:!0});const Al=ul;sl.input=Al;const kl=Sl;sl.output=kl;var Pl={},Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const xl=ns,Rl=ns,Nl=ss,Bl=xo,Cl=Buffer.from("aa21a9ed","hex");function Ul(t){const e=xl.compile(t);return e.length>37&&e[0]===Rl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Ml.check=Ul,Ul.toJSON=()=>"Witness commitment output",Ml.encode=function(t){Bl(Nl.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Rl.OPS.OP_RETURN,e])},Ml.decode=function(t){return Bl(Ul,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Pl,"__esModule",{value:!0});const Ll=Ml;Pl.output=Ll;var Dl={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const jl=ns;function ql(t){const e=jl.decompile(t);return 2===e.length&&jl.isCanonicalScriptSignature(e[0])&&function(t){return jl.isCanonicalPubKey(t)&&33===t.length}(e[1])}Hl.check=ql,ql.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Dl,"__esModule",{value:!0});const Fl=Hl;Dl.input=Fl;const Kl=al;Dl.output=Kl;var Gl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Vl=ns,$l=xo,zl=Ec,Xl=jc,Yl=Yc;function Jl(t,e){if($l($l.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=Vl.decompile(r);if(!n||0===n.length)return!1;const i=Vl.compile(t.slice(0,-1));return!(!Yl.input.check(i)||!Yl.output.check(n))||(!(!zl.input.check(i,e)||!zl.output.check(n))||!(!Xl.input.check(i)||!Xl.output.check(n)))}Wl.check=Jl,Jl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Gl,"__esModule",{value:!0});const Zl=Wl;Gl.input=Zl;const Ql=ll;Gl.output=Ql,Object.defineProperty(bc,"__esModule",{value:!0});const tp=ns,ep=Ec,rp=Cc,np=jc,ip=Yc,op=sl,sp=Pl,up=Dl,ap=Gl,hp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};bc.types=hp,bc.output=function(t){if(up.output.check(t))return hp.P2WPKH;if(ap.output.check(t))return hp.P2WSH;if(ip.output.check(t))return hp.P2PKH;if(op.output.check(t))return hp.P2SH;const e=tp.decompile(t);if(!e)throw new TypeError("Invalid script");return ep.output.check(e)?hp.P2MS:np.output.check(e)?hp.P2PK:sp.output.check(e)?hp.WITNESS_COMMITMENT:rp.output.check(e)?hp.NULLDATA:hp.NONSTANDARD},bc.input=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return ip.input.check(r)?hp.P2PKH:op.input.check(r,e)?hp.P2SH:ep.input.check(r,e)?hp.P2MS:np.input.check(r)?hp.P2PK:hp.NONSTANDARD},bc.witness=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return up.input.check(r)?hp.P2WPKH:ap.input.check(r,e)?hp.P2WSH:hp.NONSTANDARD},Object.defineProperty(wc,"__esModule",{value:!0});const fp=Qo,cp=wa,lp=bc,pp=Xs,dp=ua,gp=ts,yp=es,vp=ns,mp=ns,wp=Ma,bp=ss,Ep=xo,_p=lp.types,Sp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Ip(t,e,r){try{Ep(t,e)}catch(t){throw new Error(r)}}class Tp{constructor(t=gp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new wp.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Tp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==_p.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=dp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=vp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ep(Ep.maybe(Ep.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ep(bp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ep(bp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=cp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof wp.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=fp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=vp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Sp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Ip(Ep.Number,e.vin,"sign must include vin parameter as Number (input index)"),Ip(bp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Ip(Ep.maybe(Ep.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires witnessScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||wp.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Pp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ep(bp.Satoshi,a),l.value=a}if(!Pp(l)){const t=function(t,e,r,n){if(r&&n){const i=yp.p2wsh({redeem:{output:n}}),o=yp.p2wsh({output:r}),s=yp.p2sh({redeem:{output:r}}),u=yp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ap(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===_p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:_p.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:_p.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=yp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=yp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ap(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+vp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===_p.P2WPKH&&(o=yp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:_p.P2SH,prevOutScript:n.output,hasWitness:i.type===_p.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=yp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=yp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ap(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===_p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:_p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===_p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===_p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ap(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+vp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===_p.P2WPKH&&(n=yp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===_p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=yp.p2pkh({pubkey:e}).output;return{prevOutType:_p.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:_p.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Pp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(wp.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Op(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ap(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||lp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===_p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Mp(t)&wp.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===wp.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Mp(t)&wp.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Mp(r);return n===wp.Transaction.SIGHASH_NONE||n===wp.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Op(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=lp.input(t,!0),i=lp.witness(e,!0);n===_p.NONSTANDARD&&(n=void 0),i===_p.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case _p.P2WPKH:{const{output:t,pubkey:r,signature:n}=yp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:_p.P2WPKH,pubkeys:[r],signatures:[n]}}case _p.P2PKH:{const{output:e,pubkey:r,signature:n}=yp.p2pkh({input:t});return{prevOutScript:e,prevOutType:_p.P2PKH,pubkeys:[r],signatures:[n]}}case _p.P2PK:{const{signature:e}=yp.p2pk({input:t});return{prevOutType:_p.P2PK,pubkeys:[void 0],signatures:[e]}}case _p.P2MS:{const{m:e,pubkeys:r,signatures:i}=yp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:_p.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===_p.P2SH){const{output:r,redeem:n}=yp.p2sh({input:t,witness:e}),i=lp.output(n.output),o=Op(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:_p.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===_p.P2WSH){const{output:r,redeem:n}=yp.p2wsh({input:t,witness:e}),i=lp.output(n.output);let o;return o=i===_p.P2WPKH?Op(n.input,n.witness,i):Op(vp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:_p.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:_p.NONSTANDARD,prevOutScript:t}}function Ap(t,e){Ep(bp.Buffer,t);const r=lp.output(t);switch(r){case _p.P2PKH:{if(!e)return{type:r};const n=yp.p2pkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2WPKH:{if(!e)return{type:r};const n=yp.p2wpkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2PK:return{type:r,pubkeys:[yp.p2pk({output:t}).pubkey],signatures:[void 0]};case _p.P2MS:{const e=yp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case _p.P2PKH:if(0===n.length)break;if(0===i.length)break;return yp.p2pkh({pubkey:n[0],signature:i[0]});case _p.P2WPKH:if(0===n.length)break;if(0===i.length)break;return yp.p2wpkh({pubkey:n[0],signature:i[0]});case _p.P2PK:if(0===n.length)break;if(0===i.length)break;return yp.p2pk({signature:i[0]});case _p.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||mp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return yp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case _p.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return yp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case _p.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return yp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Pp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Mp(t){return t.readUInt8(t.length-1)}wc.TransactionBuilder=Tp,Object.defineProperty(It,"__esModule",{value:!0});const xp=Tt;It.bip32=xp;const Rp=Qo;It.address=Rp;const Np=Xs;var Bp=It.crypto=Np;const Cp=ua;It.ECPair=Cp;const Up=ts;It.networks=Up;const Lp=es;It.payments=Lp;const Dp=ns;It.script=Dp;var Hp=ma;It.Block=Hp.Block;var jp=nh;It.Psbt=jp.Psbt;var qp=ns;It.opcodes=qp.OPS;var Fp=Ma;It.Transaction=Fp.Transaction;var Kp=wc;It.TransactionBuilder=Kp.TransactionBuilder;var Gp={exports:{}};var Wp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var Vp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Wp,n=Vp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Gp,Gp.exports);const $p=["includePrerelease","loose","rtl"];var zp=t=>t?"object"!=typeof t?{loose:!0}:$p.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Xp=/^[0-9]+$/,Yp=(t,e)=>{const r=Xp.test(t),n=Xp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tYp(e,t)};const Zp=Vp,{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:td}=Wp,{re:ed,t:rd}=Gp.exports,nd=zp,{compareIdentifiers:id}=Jp;class od{constructor(t,e){if(e=nd(e),t instanceof od){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);Zp("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?ed[rd.LOOSE]:ed[rd.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>td||this.major<0)throw new TypeError("Invalid major version");if(this.minor>td||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>td||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var sd=od;const{MAX_LENGTH:ud}=Wp,{re:ad,t:hd}=Gp.exports,fd=sd,cd=zp;var ld=(t,e)=>{if(e=cd(e),t instanceof fd)return t;if("string"!=typeof t)return null;if(t.length>ud)return null;if(!(e.loose?ad[hd.LOOSE]:ad[hd.FULL]).test(t))return null;try{return new fd(t,e)}catch(t){return null}};const pd=ld;var dd=(t,e)=>{const r=pd(t,e);return r?r.version:null};const gd=ld;var yd=(t,e)=>{const r=gd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const vd=sd;var md=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new vd(t,r).inc(e,n).version}catch(t){return null}};const wd=sd;var bd=(t,e,r)=>new wd(t,r).compare(new wd(e,r));const Ed=bd;var _d=(t,e,r)=>0===Ed(t,e,r);const Sd=ld,Id=_d;var Td=(t,e)=>{if(Id(t,e))return null;{const r=Sd(t),n=Sd(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Od=sd;var Ad=(t,e)=>new Od(t,e).major;const kd=sd;var Pd=(t,e)=>new kd(t,e).minor;const Md=sd;var xd=(t,e)=>new Md(t,e).patch;const Rd=ld;var Nd=(t,e)=>{const r=Rd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Bd=bd;var Cd=(t,e,r)=>Bd(e,t,r);const Ud=bd;var Ld=(t,e)=>Ud(t,e,!0);const Dd=sd;var Hd=(t,e,r)=>{const n=new Dd(t,r),i=new Dd(e,r);return n.compare(i)||n.compareBuild(i)};const jd=Hd;var qd=(t,e)=>t.sort(((t,r)=>jd(t,r,e)));const Fd=Hd;var Kd=(t,e)=>t.sort(((t,r)=>Fd(r,t,e)));const Gd=bd;var Wd=(t,e,r)=>Gd(t,e,r)>0;const Vd=bd;var $d=(t,e,r)=>Vd(t,e,r)<0;const zd=bd;var Xd=(t,e,r)=>0!==zd(t,e,r);const Yd=bd;var Jd=(t,e,r)=>Yd(t,e,r)>=0;const Zd=bd;var Qd=(t,e,r)=>Zd(t,e,r)<=0;const tg=_d,eg=Xd,rg=Wd,ng=Jd,ig=$d,og=Qd;var sg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return tg(t,r,n);case"!=":return eg(t,r,n);case">":return rg(t,r,n);case">=":return ng(t,r,n);case"<":return ig(t,r,n);case"<=":return og(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const ug=sd,ag=ld,{re:hg,t:fg}=Gp.exports;var cg=(t,e)=>{if(t instanceof ug)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=hg[fg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),hg[fg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;hg[fg.COERCERTL].lastIndex=-1}else r=t.match(hg[fg.COERCE]);return null===r?null:ag(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},lg=pg;function pg(t){var e=this;if(e instanceof pg||(e=new pg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},pg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},pg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},pg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},pg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new pg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},pg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Mg=(t,e,r)=>{const n=t[Ag].get(e);if(n){const e=n.value;if(xg(t,e)){if(Ng(t,n),!t[_g])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Og].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Sg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Sg]&&r>t[Sg]},Rg=t=>{if(t[bg]>t[wg])for(let e=t[Og].tail;t[bg]>t[wg]&&null!==e;){const r=e.prev;Ng(t,e),e=r}},Ng=(t,e)=>{if(e){const r=e.value;t[Ig]&&t[Ig](r.key,r.value),t[bg]-=r.length,t[Ag].delete(r.key),t[Og].removeNode(e)}};class Bg{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Ng(t,r),t[_g]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Ug=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[wg]=t.max||1/0;const e=t.length||Pg;if(this[Eg]="function"!=typeof e?Pg:e,this[_g]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Sg]=t.maxAge||0,this[Ig]=t.dispose,this[Tg]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[wg]=t||1/0,Rg(this)}get max(){return this[wg]}set allowStale(t){this[_g]=!!t}get allowStale(){return this[_g]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Sg]=t,Rg(this)}get maxAge(){return this[Sg]}set lengthCalculator(t){"function"!=typeof t&&(t=Pg),t!==this[Eg]&&(this[Eg]=t,this[bg]=0,this[Og].forEach((t=>{t.length=this[Eg](t.value,t.key),this[bg]+=t.length}))),Rg(this)}get lengthCalculator(){return this[Eg]}get length(){return this[bg]}get itemCount(){return this[Og].length}rforEach(t,e){e=e||this;for(let r=this[Og].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Og].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Og].toArray().map((t=>t.key))}values(){return this[Og].toArray().map((t=>t.value))}reset(){this[Ig]&&this[Og]&&this[Og].length&&this[Og].forEach((t=>this[Ig](t.key,t.value))),this[Ag]=new Map,this[Og]=new mg,this[bg]=0}dump(){return this[Og].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Og]}set(t,e,r){if((r=r||this[Sg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Eg](e,t);if(this[Ag].has(t)){if(i>this[wg])return Ng(this,this[Ag].get(t)),!1;const o=this[Ag].get(t).value;return this[Ig]&&(this[Tg]||this[Ig](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[bg]+=i-o.length,o.length=i,this.get(t),Rg(this),!0}const o=new Bg(t,e,i,n,r);return o.length>this[wg]?(this[Ig]&&this[Ig](t,e),!1):(this[bg]+=o.length,this[Og].unshift(o),this[Ag].set(t,this[Og].head),Rg(this),!0)}has(t){if(!this[Ag].has(t))return!1;const e=this[Ag].get(t).value;return!xg(this,e)}get(t){return Mg(this,t,!0)}peek(t){return Mg(this,t,!1)}pop(){const t=this[Og].tail;return t?(Ng(this,t),t.value):null}del(t){Ng(this,this[Ag].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ag].forEach(((t,e)=>Mg(this,e,!1)))}};class Lg{constructor(t,e){if(e=jg(e),t instanceof Lg)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Lg(t.raw,e);if(t instanceof qg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Xg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Yg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=Hg.get(e);if(r)return r;const n=this.options.loose,i=n?Gg[Wg.HYPHENRANGELOOSE]:Gg[Wg.HYPHENRANGE];t=t.replace(i,ay(this.options.includePrerelease)),Fg("hyphen replace",t),t=t.replace(Gg[Wg.COMPARATORTRIM],Vg),Fg("comparator trim",t,Gg[Wg.COMPARATORTRIM]),t=(t=(t=t.replace(Gg[Wg.TILDETRIM],$g)).replace(Gg[Wg.CARETTRIM],zg)).split(/\s+/).join(" ");const o=n?Gg[Wg.COMPARATORLOOSE]:Gg[Wg.COMPARATOR],s=t.split(" ").map((t=>Zg(t,this.options))).join(" ").split(/\s+/).map((t=>uy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new qg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Xg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return Hg.set(e,a),a}intersects(t,e){if(!(t instanceof Lg))throw new TypeError("a Range is required");return this.set.some((r=>Jg(r,e)&&t.set.some((t=>Jg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Kg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Yg=t=>""===t.value,Jg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},Zg=(t,e)=>(Fg("comp",t,e),t=ry(t,e),Fg("caret",t),t=ty(t,e),Fg("tildes",t),t=iy(t,e),Fg("xrange",t),t=sy(t,e),Fg("stars",t),t),Qg=t=>!t||"x"===t.toLowerCase()||"*"===t,ty=(t,e)=>t.trim().split(/\s+/).map((t=>ey(t,e))).join(" "),ey=(t,e)=>{const r=e.loose?Gg[Wg.TILDELOOSE]:Gg[Wg.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Fg("tilde",t,e,r,n,i,o),Qg(r)?s="":Qg(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Qg(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Fg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Fg("tilde return",s),s}))},ry=(t,e)=>t.trim().split(/\s+/).map((t=>ny(t,e))).join(" "),ny=(t,e)=>{Fg("caret",t,e);const r=e.loose?Gg[Wg.CARETLOOSE]:Gg[Wg.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Fg("caret",t,e,r,i,o,s),Qg(r)?u="":Qg(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Qg(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Fg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Fg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Fg("caret return",u),u}))},iy=(t,e)=>(Fg("replaceXRanges",t,e),t.split(/\s+/).map((t=>oy(t,e))).join(" ")),oy=(t,e)=>{t=t.trim();const r=e.loose?Gg[Wg.XRANGELOOSE]:Gg[Wg.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Fg("xRange",t,r,n,i,o,s,u);const a=Qg(i),h=a||Qg(o),f=h||Qg(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Fg("xRange return",r),r}))},sy=(t,e)=>(Fg("replaceStars",t,e),t.trim().replace(Gg[Wg.STAR],"")),uy=(t,e)=>(Fg("replaceGTE0",t,e),t.trim().replace(Gg[e.includePrerelease?Wg.GTE0PRE:Wg.GTE0],"")),ay=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=Qg(n)?"":Qg(i)?`>=${n}.0.0${t?"-0":""}`:Qg(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Qg(h)?"":Qg(f)?`<${+h+1}.0.0-0`:Qg(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),hy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},fy=Symbol("SemVer ANY");class cy{static get ANY(){return fy}constructor(t,e){if(e=py(e),t instanceof cy){if(t.loose===!!e.loose)return t;t=t.value}vy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===fy?this.value="":this.value=this.operator+this.semver.version,vy("comp",this)}parse(t){const e=this.options.loose?dy[gy.COMPARATORLOOSE]:dy[gy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new my(r[2],this.options.loose):this.semver=fy}toString(){return this.value}test(t){if(vy("Comparator.test",t,this.options.loose),this.semver===fy||t===fy)return!0;if("string"==typeof t)try{t=new my(t,this.options)}catch(t){return!1}return yy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof cy))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new wy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new wy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=yy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=yy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var ly=cy;const py=zp,{re:dy,t:gy}=Gp.exports,yy=sg,vy=Vp,my=sd,wy=Dg,by=Dg;var Ey=(t,e,r)=>{try{e=new by(e,r)}catch(t){return!1}return e.test(t)};const _y=Dg;var Sy=(t,e)=>new _y(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Iy=sd,Ty=Dg;var Oy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ty(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Iy(n,r)))})),n};const Ay=sd,ky=Dg;var Py=(t,e,r)=>{let n=null,i=null,o=null;try{o=new ky(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Ay(n,r)))})),n};const My=sd,xy=Dg,Ry=Wd;var Ny=(t,e)=>{t=new xy(t,e);let r=new My("0.0.0");if(t.test(r))return r;if(r=new My("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new My(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Ry(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Ry(r,i)||(r=i)}return r&&t.test(r)?r:null};const By=Dg;var Cy=(t,e)=>{try{return new By(t,e).range||"*"}catch(t){return null}};const Uy=sd,Ly=ly,{ANY:Dy}=Ly,Hy=Dg,jy=Ey,qy=Wd,Fy=$d,Ky=Qd,Gy=Jd;var Wy=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Uy(t,n),e=new Hy(e,n),r){case">":i=qy,o=Ky,s=Fy,u=">",a=">=";break;case"<":i=Fy,o=Gy,s=qy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jy(t,e,n))return!1;for(let r=0;r{t.semver===Dy&&(t=new Ly(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const Vy=Wy;var $y=(t,e,r)=>Vy(t,e,">",r);const zy=Wy;var Xy=(t,e,r)=>zy(t,e,"<",r);const Yy=Dg;var Jy=(t,e,r)=>(t=new Yy(t,r),e=new Yy(e,r),t.intersects(e));const Zy=Ey,Qy=bd;const tv=Dg,ev=ly,{ANY:rv}=ev,nv=Ey,iv=bd,ov=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===rv){if(1===e.length&&e[0].semver===rv)return!0;t=r.includePrerelease?[new ev(">=0.0.0-0")]:[new ev(">=0.0.0")]}if(1===e.length&&e[0].semver===rv){if(r.includePrerelease)return!0;e=[new ev(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=sv(i,e,r):"<"===e.operator||"<="===e.operator?o=uv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=iv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!nv(t,String(i),r))return null;if(o&&!nv(t,String(o),r))return null;for(const n of e)if(!nv(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=sv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!nv(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=uv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!nv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},sv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},uv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var av=(t,e,r={})=>{if(t===e)return!0;t=new tv(t,r),e=new tv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=ov(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const hv=Gp.exports;var fv={re:hv.re,src:hv.src,tokens:hv.t,SEMVER_SPEC_VERSION:Wp.SEMVER_SPEC_VERSION,SemVer:sd,compareIdentifiers:Jp.compareIdentifiers,rcompareIdentifiers:Jp.rcompareIdentifiers,parse:ld,valid:dd,clean:yd,inc:md,diff:Td,major:Ad,minor:Pd,patch:xd,prerelease:Nd,compare:bd,rcompare:Cd,compareLoose:Ld,compareBuild:Hd,sort:qd,rsort:Kd,gt:Wd,lt:$d,eq:_d,neq:Xd,gte:Jd,lte:Qd,cmp:sg,coerce:cg,Comparator:ly,Range:Dg,satisfies:Ey,toComparators:Sy,maxSatisfying:Oy,minSatisfying:Py,minVersion:Ny,validRange:Cy,outside:Wy,gtr:$y,ltr:Xy,intersects:Jy,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Qy(t,e,r)));for(const t of s){Zy(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Tv(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ov(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Av(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}yv.prototype=Object.create(null),vv.EventEmitter=vv,vv.usingDomains=!1,vv.prototype.domain=void 0,vv.prototype._events=void 0,vv.prototype._maxListeners=void 0,vv.defaultMaxListeners=10,vv.init=function(){this.domain=null,vv.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new yv,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},vv.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},vv.prototype.getMaxListeners=function(){return mv(this)},vv.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:wv(r,f,this);break;case 2:bv(r,f,this,arguments[1]);break;case 3:Ev(r,f,this,arguments[1],arguments[2]);break;case 4:_v(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new yv,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var kv=Object.freeze({__proto__:null,default:vv,EventEmitter:vv});function Pv(){throw new Error("setTimeout has not been defined")}function Mv(){throw new Error("clearTimeout has not been defined")}var xv=Pv,Rv=Mv;function Nv(t){if(xv===setTimeout)return setTimeout(t,0);if((xv===Pv||!xv)&&setTimeout)return xv=setTimeout,setTimeout(t,0);try{return xv(t,0)}catch(e){try{return xv.call(null,t,0)}catch(e){return xv.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xv=setTimeout),"function"==typeof global.clearTimeout&&(Rv=clearTimeout);var Bv,Cv=[],Uv=!1,Lv=-1;function Dv(){Uv&&Bv&&(Uv=!1,Bv.length?Cv=Bv.concat(Cv):Lv=-1,Cv.length&&Hv())}function Hv(){if(!Uv){var t=Nv(Dv);Uv=!0;for(var e=Cv.length;e;){for(Bv=Cv,Cv=[];++Lv1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),nm(e)?r.showHidden=e:e&&_m(r,e),hm(r.showHidden)&&(r.showHidden=!1),hm(r.depth)&&(r.depth=2),hm(r.colors)&&(r.colors=!1),hm(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Jv),Qv(r,t,r.depth)}function Jv(t,e){var r=Yv.styles[e];return r?"["+Yv.colors[r][0]+"m"+t+"["+Yv.colors[r][1]+"m":t}function Zv(t,e){return t}function Qv(t,e,r){if(t.customInspect&&e&&dm(e.inspect)&&e.inspect!==Yv&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return um(n)||(n=Qv(t,n,r)),n}var i=function(t,e){if(hm(e))return t.stylize("undefined","undefined");if(um(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(sm(e))return t.stylize(""+e,"number");if(nm(e))return t.stylize(""+e,"boolean");if(im(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),pm(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tm(e);if(0===o.length){if(dm(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(fm(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(lm(e))return t.stylize(Date.prototype.toString.call(e),"date");if(pm(e))return tm(e)}var a,h="",f=!1,c=["{","}"];(rm(e)&&(f=!0,c=["[","]"]),dm(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return fm(e)&&(h=" "+RegExp.prototype.toString.call(e)),lm(e)&&(h=" "+Date.prototype.toUTCString.call(e)),pm(e)&&(h=" "+tm(e)),0!==o.length||f&&0!=e.length?r<0?fm(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function tm(t){return"["+Error.prototype.toString.call(t)+"]"}function em(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Sm(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=im(r)?Qv(t,a.value,null):Qv(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),hm(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function rm(t){return Array.isArray(t)}function nm(t){return"boolean"==typeof t}function im(t){return null===t}function om(t){return null==t}function sm(t){return"number"==typeof t}function um(t){return"string"==typeof t}function am(t){return"symbol"==typeof t}function hm(t){return void 0===t}function fm(t){return cm(t)&&"[object RegExp]"===vm(t)}function cm(t){return"object"==typeof t&&null!==t}function lm(t){return cm(t)&&"[object Date]"===vm(t)}function pm(t){return cm(t)&&("[object Error]"===vm(t)||t instanceof Error)}function dm(t){return"function"==typeof t}function gm(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function ym(t){return Buffer.isBuffer(t)}function vm(t){return Object.prototype.toString.call(t)}function mm(t){return t<10?"0"+t.toString(10):t.toString(10)}Yv.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]},Yv.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var wm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bm(){var t=new Date,e=[mm(t.getHours()),mm(t.getMinutes()),mm(t.getSeconds())].join(":");return[t.getDate(),wm[t.getMonth()],e].join(" ")}function Em(){console.log("%s - %s",bm(),Wv.apply(null,arguments))}function _m(t,e){if(!e||!cm(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Sm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Im={inherits:Kv,_extend:_m,log:Em,isBuffer:ym,isPrimitive:gm,isFunction:dm,isError:pm,isDate:lm,isObject:cm,isRegExp:fm,isUndefined:hm,isSymbol:am,isString:um,isNumber:sm,isNullOrUndefined:om,isNull:im,isBoolean:nm,isArray:rm,inspect:Yv,deprecate:Vv,format:Wv,debuglog:Xv},Tm=Object.freeze({__proto__:null,format:Wv,deprecate:Vv,debuglog:Xv,inspect:Yv,isArray:rm,isBoolean:nm,isNull:im,isNullOrUndefined:om,isNumber:sm,isString:um,isSymbol:am,isUndefined:hm,isRegExp:fm,isObject:cm,isDate:lm,isError:pm,isFunction:dm,isPrimitive:gm,isBuffer:ym,log:Em,inherits:Kv,_extend:_m,default:Im});function Om(){this.head=null,this.tail=null,this.length=0}Om.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Om.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Om.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Om.prototype.clear=function(){this.head=this.tail=null,this.length=0},Om.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Om.prototype.concat=function(t){if(0===this.length)return I.alloc(0);if(1===this.length)return this.head.data;for(var e=I.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Am=I.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function km(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Am(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Mm;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xm;break;default:return void(this.write=Pm)}this.charBuffer=new I(6),this.charReceived=0,this.charLength=0}function Pm(t){return t.toString(this.encoding)}function Mm(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xm(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}km.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},km.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},km.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Bm.ReadableState=Nm;var Rm=Xv("stream");function Nm(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof aw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Om,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new km(t.encoding),this.encoding=t.encoding)}function Bm(t){if(!(this instanceof Bm))return new Bm(t);this._readableState=new Nm(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),vv.call(this)}function Cm(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Dm(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Dm(t))),function(t,e){e.readingMore||(e.readingMore=!0,jv(jm,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Um?t=Um:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Dm(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Rm("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?jv(Hm,t):Hm(t))}function Hm(t){Rm("emit readable"),t.emit("readable"),Km(t)}function jm(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Wm(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,jv(Vm,e,t))}function Vm(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function $m(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Rm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Wm(this):Dm(this),null;if(0===(t=Lm(t,e))&&e.ended)return 0===e.length&&Wm(this),null;var n,i=e.needReadable;return Rm("need readable",i),(0===e.length||e.length-t0?Gm(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Wm(this)),null!==n&&this.emit("data",n),n},Bm.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Bm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Rm("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Rm("onunpipe"),t===r&&h()}function s(){Rm("onend"),t.end()}n.endEmitted?jv(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Rm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Km(t))}}(r);t.on("drain",u);var a=!1;function h(){Rm("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Rm("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==$m(n.pipes,t))&&!a&&(Rm("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Rm("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Rm("onfinish"),t.removeListener("close",p),g()}function g(){Rm("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Rm("pipe resume"),r.resume()),t},Bm.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Jm.prototype._write=function(t,e,r){r(new Error("not implemented"))},Jm.prototype._writev=null,Jm.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,nw(t,e),r&&(e.finished?jv(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Kv(aw,Bm);for(var ow=Object.keys(Jm.prototype),sw=0;sw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Sw.alloc(0);for(var e=Sw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ow(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Sw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Tw,value:function(t,e){return Iw(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Bw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Bw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Cw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Cw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Bw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Bw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Bw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Bw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Bw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Bw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Bw("ERR_STREAM_WRITE_AFTER_END","write after end"),Bw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Bw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Bw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Rw.codes=Nw;var Uw=Rw.codes.ERR_INVALID_OPT_VALUE;var Lw,Dw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Uw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Hw=ww.deprecate,jw=ub;function qw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}ub.WritableState=sb;var Fw={deprecate:Hw},Kw=mw,Gw=ht.Buffer,Ww=r.Uint8Array||function(){};var Vw,$w=xw,zw=Dw.getHighWaterMark,Xw=Rw.codes,Yw=Xw.ERR_INVALID_ARG_TYPE,Jw=Xw.ERR_METHOD_NOT_IMPLEMENTED,Zw=Xw.ERR_MULTIPLE_CALLBACK,Qw=Xw.ERR_STREAM_CANNOT_PIPE,tb=Xw.ERR_STREAM_DESTROYED,eb=Xw.ERR_STREAM_NULL_VALUES,rb=Xw.ERR_STREAM_WRITE_AFTER_END,nb=Xw.ERR_UNKNOWN_ENCODING,ib=$w.errorOrDestroy;function ob(){}function sb(t,e,r){Lw=Lw||gb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Lw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=zw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Zw;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(pb,t,e),t._writableState.errorEmitted=!0,ib(t,n)):(i(n),t._writableState.errorEmitted=!0,ib(t,n),pb(t,e))}(t,r,n,e,i);else{var o=cb(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||fb(t,r),n?process.nextTick(hb,t,r,o,i):hb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new qw(this)}function ub(t){var e=this instanceof(Lw=Lw||gb);if(!e&&!Vw.call(ub,this))return new ub(t);this._writableState=new sb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Kw.call(this)}function ab(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new tb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),pb(t,e)}function fb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,ab(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new qw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(ab(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function cb(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function lb(t,e){t._final((function(r){e.pendingcb--,r&&ib(t,r),e.prefinished=!0,t.emit("prefinish"),pb(t,e)}))}function pb(t,e){var r=cb(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(lb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}Zt.exports(ub,Kw),sb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(sb.prototype,"buffer",{get:Fw.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Vw=Function.prototype[Symbol.hasInstance],Object.defineProperty(ub,Symbol.hasInstance,{value:function(t){return!!Vw.call(this,t)||this===ub&&(t&&t._writableState instanceof sb)}})):Vw=function(t){return t instanceof this},ub.prototype.pipe=function(){ib(this,new Qw)},ub.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Gw.isBuffer(n)||n instanceof Ww);return s&&!Gw.isBuffer(t)&&(t=function(t){return Gw.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ob),i.ending?function(t,e){var r=new rb;ib(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new eb:"string"==typeof r||e.objectMode||(i=new Yw("chunk",["string","Buffer"],r)),!i||(ib(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Gw.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new nb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(ub.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(ub.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),ub.prototype._write=function(t,e,r){r(new Jw("_write()"))},ub.prototype._writev=null,ub.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,pb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(ub.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(ub.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),ub.prototype.destroy=$w.destroy,ub.prototype._undestroy=$w.undestroy,ub.prototype._destroy=function(t,e){e(t)};var db=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},gb=Eb,yb=aE,vb=jw;Zt.exports(Eb,yb);for(var mb=db(vb.prototype),wb=0;wb>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Pb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Mb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function xb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Rb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Nb(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Bb(t){return t.toString(this.encoding)}function Cb(t){return t&&t.length?this.write(t):""}Ib.StringDecoder=Ab,Ab.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Ab.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Ub=Rw.codes.ERR_STREAM_PREMATURE_CLOSE;function Lb(){}var Db,Hb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===cE.prototype||(e=function(t){return cE.from(t)}(e)),n)s.endEmitted?OE(t,new TE):xE(t,s,e,!0);else if(s.ended)OE(t,new SE);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?xE(t,s,e,!1):UE(t,s)):xE(t,s,e,!1)}else n||(s.reading=!1,UE(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=RE?t=RE:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function BE(t){var e=t._readableState;pE("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(pE("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(CE,t))}function CE(t){var e=t._readableState;pE("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,qE(t)}function UE(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(LE,t,e))}function LE(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function HE(t){pE("readable nexttick read 0"),t.read(0)}function jE(t,e){pE("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),qE(t),e.flowing&&!e.reading&&t.read(0)}function qE(t){var e=t._readableState;for(pE("flow",e.flowing);e.flowing&&null!==t.read(););}function FE(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function KE(t){var e=t._readableState;pE("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(GE,e,t))}function GE(t,e){if(pE("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function WE(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return pE("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?KE(this):BE(this),null;if(0===(t=NE(t,e))&&e.ended)return 0===e.length&&KE(this),null;var n,i=e.needReadable;return pE("need readable",i),(0===e.length||e.length-t0?FE(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&KE(this)),null!==n&&this.emit("data",n),n},PE.prototype._read=function(t){OE(this,new IE("_read()"))},PE.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,pE("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){pE("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,pE("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){pE("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;pE("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&hE(t,"data")&&(e.flowing=!0,qE(t))}}(r);t.on("drain",u);var a=!1;function h(e){pE("ondata");var i=t.write(e);pE("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==WE(n.pipes,t))&&!a&&(pE("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){pE("onerror",e),p(),t.removeListener("error",f),0===hE(t,"error")&&OE(t,e)}function c(){t.removeListener("finish",l),p()}function l(){pE("onfinish"),t.removeListener("close",c),p()}function p(){pE("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(pE("pipe resume"),r.resume()),t},PE.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,pE("on readable",n.length,n.reading),n.length?BE(this):n.reading||process.nextTick(HE,this))),r},PE.prototype.addListener=PE.prototype.on,PE.prototype.removeListener=function(t,e){var r=fE.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(DE,this),r},PE.prototype.removeAllListeners=function(t){var e=fE.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(DE,this),e},PE.prototype.resume=function(){var t=this._readableState;return t.flowing||(pE("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(jE,t,e))}(this,t)),t.paused=!1,this},PE.prototype.pause=function(){return pE("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(pE("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},PE.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(pE("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(pE("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(l_),s||(o.forEach(l_),i(n))}))}));return e.reduce(p_)};!function(t,e){var r=yw;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=aE).Stream=r||e,e.Readable=e,e.Writable=jw,e.Duplex=gb,e.Transform=VE,e.PassThrough=i_,e.finished=Hb,e.pipeline=g_)}(gv,gv.exports);var y_=h.exports.Buffer,v_=gv.exports.Transform;function m_(t){v_.call(this),this._block=y_.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,Zt.exports)(m_,v_),m_.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},m_.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},m_.prototype.update=function(t,e){if(function(t,e){if(!y_.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");y_.isBuffer(t)||(t=y_.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},m_.prototype._update=function(){throw new Error("_update is not implemented")},m_.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},m_.prototype._digest=function(){throw new Error("_digest is not implemented")};var w_=m_,b_=ht.Buffer,E_=Zt.exports,__=w_,S_=new Array(16),I_=[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],T_=[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],O_=[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],A_=[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],k_=[0,1518500249,1859775393,2400959708,2840853838],P_=[1352829926,1548603684,1836072691,2053994217,0];function M_(){__.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function x_(t,e){return t<>>32-e}function R_(t,e,r,n,i,o,s,u){return x_(t+(e^r^n)+o+s|0,u)+i|0}function N_(t,e,r,n,i,o,s,u){return x_(t+(e&r|~e&n)+o+s|0,u)+i|0}function B_(t,e,r,n,i,o,s,u){return x_(t+((e|~r)^n)+o+s|0,u)+i|0}function C_(t,e,r,n,i,o,s,u){return x_(t+(e&n|r&~n)+o+s|0,u)+i|0}function U_(t,e,r,n,i,o,s,u){return x_(t+(e^(r|~n))+o+s|0,u)+i|0}E_(M_,__),M_.prototype._update=function(){for(var t=S_,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=R_(r,n,i,o,s,t[I_[l]],k_[0],O_[l]),d=U_(u,a,h,f,c,t[T_[l]],P_[0],A_[l])):l<32?(p=N_(r,n,i,o,s,t[I_[l]],k_[1],O_[l]),d=C_(u,a,h,f,c,t[T_[l]],P_[1],A_[l])):l<48?(p=B_(r,n,i,o,s,t[I_[l]],k_[2],O_[l]),d=B_(u,a,h,f,c,t[T_[l]],P_[2],A_[l])):l<64?(p=C_(r,n,i,o,s,t[I_[l]],k_[3],O_[l]),d=N_(u,a,h,f,c,t[T_[l]],P_[3],A_[l])):(p=U_(r,n,i,o,s,t[I_[l]],k_[4],O_[l]),d=R_(u,a,h,f,c,t[T_[l]],P_[4],A_[l])),r=s,s=o,o=x_(i,10),i=n,n=p,u=c,c=f,f=x_(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},M_.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=b_.alloc?b_.alloc(20):new b_(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var L_=M_,D_={exports:{}},H_=h.exports.Buffer;function j_(t,e){this._block=H_.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}j_.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=H_.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},j_.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var q_=j_,F_=Zt.exports,K_=q_,G_=h.exports.Buffer,W_=[1518500249,1859775393,-1894007588,-899497514],V_=new Array(80);function $_(){this.init(),this._w=V_,K_.call(this,64,56)}function z_(t){return t<<30|t>>>2}function X_(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}F_($_,K_),$_.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},$_.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+X_(f,i,o,s)+u+r[h]+W_[f];u=s,s=o,o=z_(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},$_.prototype._hash=function(){var t=G_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var Y_=$_,J_=Zt.exports,Z_=q_,Q_=h.exports.Buffer,tS=[1518500249,1859775393,-1894007588,-899497514],eS=new Array(80);function rS(){this.init(),this._w=eS,Z_.call(this,64,56)}function nS(t){return t<<5|t>>>27}function iS(t){return t<<30|t>>>2}function oS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}J_(rS,Z_),rS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},rS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=nS(n)+oS(f,i,o,s)+u+r[h]+tS[f]|0;u=s,s=o,o=iS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},rS.prototype._hash=function(){var t=Q_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var sS=rS,uS=Zt.exports,aS=q_,hS=h.exports.Buffer,fS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cS=new Array(64);function lS(){this.init(),this._w=cS,aS.call(this,64,56)}function pS(t,e,r){return r^t&(e^r)}function dS(t,e,r){return t&e|r&(t|e)}function gS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function yS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function vS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function mS(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}uS(lS,aS),lS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},lS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=mS(e[f-2])+e[f-7]+vS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+yS(s)+pS(s,u,a)+fS[c]+e[c]|0,p=gS(r)+dS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},lS.prototype._hash=function(){var t=hS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var wS=lS,bS=Zt.exports,ES=wS,_S=q_,SS=h.exports.Buffer,IS=new Array(64);function TS(){this.init(),this._w=IS,_S.call(this,64,56)}bS(TS,ES),TS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},TS.prototype._hash=function(){var t=SS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var OS=TS,AS=Zt.exports,kS=q_,PS=h.exports.Buffer,MS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xS=new Array(160);function RS(){this.init(),this._w=xS,kS.call(this,128,112)}function NS(t,e,r){return r^t&(e^r)}function BS(t,e,r){return t&e|r&(t|e)}function CS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function US(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function LS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function DS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function HS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function jS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function qS(t,e){return t>>>0>>0?1:0}AS(RS,kS),RS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},RS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=LS(w,b),_=DS(b,w),S=HS(w=e[m-4],b=e[m-4+1]),I=jS(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],k=e[m-32+1],P=_+O|0,M=E+T+qS(P,_)|0;M=(M=M+S+qS(P=P+I|0,I)|0)+A+qS(P=P+k|0,k)|0,e[m]=M,e[m+1]=P}for(var x=0;x<160;x+=2){M=e[x],P=e[x+1];var R=BS(r,n,i),N=BS(f,c,l),B=CS(r,f),C=CS(f,r),U=US(s,d),L=US(d,s),D=MS[x],H=MS[x+1],j=NS(s,u,a),q=NS(d,g,y),F=v+L|0,K=h+U+qS(F,v)|0;K=(K=(K=K+j+qS(F=F+q|0,q)|0)+D+qS(F=F+H|0,H)|0)+M+qS(F=F+P|0,P)|0;var G=C+N|0,W=B+R+qS(G,C)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+K+qS(d=p+F|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=K+W+qS(f=F+G|0,F)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+qS(this._al,f)|0,this._bh=this._bh+n+qS(this._bl,c)|0,this._ch=this._ch+i+qS(this._cl,l)|0,this._dh=this._dh+o+qS(this._dl,p)|0,this._eh=this._eh+s+qS(this._el,d)|0,this._fh=this._fh+u+qS(this._fl,g)|0,this._gh=this._gh+a+qS(this._gl,y)|0,this._hh=this._hh+h+qS(this._hl,v)|0},RS.prototype._hash=function(){var t=PS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var FS=RS,KS=Zt.exports,GS=FS,WS=q_,VS=h.exports.Buffer,$S=new Array(160);function zS(){this.init(),this._w=$S,WS.call(this,128,112)}KS(zS,GS),zS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},zS.prototype._hash=function(){var t=VS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var XS=zS,YS=D_.exports=function(t){t=t.toLowerCase();var e=YS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};YS.sha=Y_,YS.sha1=sS,YS.sha224=OS,YS.sha256=wS,YS.sha384=XS,YS.sha512=FS;var JS=D_.exports;function ZS(t){return(new L_).update(JS("sha256").update(t).digest()).digest()}var QS,tI=(QS=function(t,e){return QS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},QS(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}QS(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),eI=function(t,e){this.psbt=t,this.masterFp=e},rI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(eI),nI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(rI),iI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new cv,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Bp.sha256(Buffer.from("TapTweak","utf-8"));return Bp.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(xt.exports.pointAddScalar(e,r)).slice(1)},e}(rI),oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=this.createRedeemScript(t),n=ZS(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=ZS(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(rI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(rI),uI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},aI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return lI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new cI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new cI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function LI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,UI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,UI(t.script.length),t.script])}))),r}function DI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,UI(t.script.length),t.script,t.sequence])}));var a=LI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),UI(t.inputs.length),s,a])}var HI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new pI(e,dI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return HI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I;return jI(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new _I,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new iI(e,r):t.additionals.includes("bech32")?new sI(e,r):t.segwit?new oI(e,r):new nI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new cv).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new cv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new cv;BI(h,f),BI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new cv).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}NI(t,r)}}(r),I=function(t){var e,r,n=new cv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new cv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nT(t,e,r){return tT(this,void 0,void 0,(function(){var n,i,o,s;return eT(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function iT(t,e,r,n){return void 0===n&&(n=[]),tT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R=this;return eT(this,(function(N){switch(N.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return tT(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return eT(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>pv?pv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=rT(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,nT(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return nT(t,e)},[4,nT(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(o.length)]),e)];case 1:N.sent(),N.label=2;case 2:N.trys.push([2,8,9,10]),d=rT(o),g=d.next(),N.label=3;case 3:return g.done?[3,7]:(y=g.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?y.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([y.prevout,m,v?Buffer.from([0]):UI(y.script.length)]),[4,nT(t,O)]);case 4:return N.sent(),[4,f?p(Buffer.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:N.sent(),N.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=N.sent(),k={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,nT(t,UI(s.length))];case 11:N.sent(),N.label=12;case 12:N.trys.push([12,17,18,19]),b=rT(s),E=b.next(),N.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),UI(_.script.length),_.script]),[4,nT(t,O)]);case 14:N.sent(),N.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=N.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([UI(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return A=N.sent(),QI(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var oT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},sT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aT(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function hT(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),oT(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return sT(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(r.inputs.length)]),[4,aT(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=uT(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),UI(p.script.length)]),[4,aT(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>pv?pv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=uT(y),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,aT(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function fT(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=JS("sha256").update(JS("sha256").update(DI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function cT(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=wt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var lT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},pT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:pv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var yT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ST={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function IT(t,e){return bT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C,U,L,D,H,j,q,F,K,G,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return ET(this,(function(ht){switch(ht.label){case 0:if(r=wT(wT({},ST),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,mT(t)];case 2:return v=ht.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||fv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),A=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),P=[],M=[],x=[],R=[],N=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},U=T&&!y?fT:iT,L=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=_T(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:j=ht.sent(),VI("hw","got trustedInput="+j),(q=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:dv,0),P.push({trustedInput:!0,value:Buffer.from(j,"hex"),sequence:q}),ht.label=8;case 8:F=$[0].outputs,K=$[1],F&&K<=F.length-1&&M.push(F[K]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return G=ht.sent(),ut={error:G},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:dv,0),{script:O,prevout:A,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),ZS(R[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[P[it]]:P,T?X.inputs=[wT(wT({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,hT(t,!T&&N,X,Y,T,!!l&&!b,c,y)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,dT(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,gT(t,L,c)];case 30:ht.sent(),ht.label=31;case 31:return N&&(d(),w(1,0)),[4,cT(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,N&&(N=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},xT={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function RT(t,e){return kT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C;return PT(this,(function(U){switch(U.label){case 0:r=AT(AT({},xT),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?fT:iT,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),E=MT(n),_=E.next(),U.label=2;case 2:return _.done?[3,6]:(P=_.value,v?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=U.sent(),(A=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:dv,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:A}),U.label=4;case 4:I=P[0].outputs,T=P[1],I&&T<=I.length-1&&d.push(I[T]),U.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=U.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:dv,0),m.inputs.push({script:f,prevout:c,sequence:A});return a?[4,hT(t,!0,m,p,!0)]:[3,12];case 10:return U.sent(),[4,gT(t,b)];case 11:U.sent(),U.label=12;case 12:k=0,U.label=13;case 13:return k=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[k].script,x=Object.assign({},m),R=a?[p[k]]:p,a?x.inputs=[AT(AT({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,hT(t,!a&&y,x,R,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,gT(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,cT(t,i[k],s,u)];case 17:N=U.sent(),g.push(a?N.toString("hex"):N.slice(0,N.length-1).toString("hex")),m.inputs[k].script=f,y&&(y=!1),U.label=18;case 18:return k++,[3,13];case 19:return[2,g]}}))}))}var NT=function(){return NT=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,u()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),IT(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),RT(this.transport,t)},t}();function LT(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var DT=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function HT(t){return JS("sha256").update(t).digest()}var jT,qT=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new hI(t.map((function(t){return fI(t)}))),this.values=e,this.valuesTree=new hI(e.map((function(t){return fI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([UI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),FT=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),KT=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},GT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},zT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(jT||(jT={}));var YT,JT,ZT=function(){},QT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=jT.YIELD,n.results=e,n}return VT(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(ZT),tO=function(t){function e(e,r){var n=t.call(this)||this;return n.code=jT.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=UI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,zT([],$T(a.slice(-f)),!1)),Buffer.concat(zT([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],$T(a.slice(0,h)),!1))},e}(ZT),rO=function(t){function e(e){var r=t.call(this)||this;return r.code=jT.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(YT||(YT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(JT||(JT={}));var aO=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return oO(this,void 0,void 0,(function(){var n,i,o;return sO(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,JT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return oO(this,void 0,void 0,(function(){return sO(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(YT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),mt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return oO(this,void 0,void 0,(function(){var o,s;return sO(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new iO((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(YT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return oO(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S;return sO(this,(function(I){switch(I.label){case 0:if(i=new WT(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new iO(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=uO(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=uO(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new hI(i.inputMapCommitments.map((function(t){return fI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new hI(i.outputMapCommitments.map((function(t){return fI(t)}))).getRoot(),[4,this.makeRequest(YT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),UI(i.getGlobalInputCount()),c,UI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=uO(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return oO(this,void 0,void 0,(function(){return sO(this,(function(t){return[2,this.makeRequest(YT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var hO=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},fO=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof FI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||lO(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(Buffer.from([3,0,0,128]))||y.equals(Buffer.from([4,0,0,128])),m=y.equals(Buffer.from([1,0,0,0]))||y.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(c=g.slice(a,4+a),a+=4);var w=CI(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new UT(this.transport)},t.prototype.new=function(){return new FI(new aO(this.transport))},t}();function lO(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var pO=Object.freeze({__proto__:null,default:cO}),dO={},gO={},yO={},vO={};Object.defineProperty(vO,"__esModule",{value:!0});var mO="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wO={},bO={};vO.addCustomErrorDeserializer=function(t,e){bO[t]=e};var EO=vO.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,wO[t]=e,e};function _O(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":mO(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=_O(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}vO.deserializeError=function t(e){if("object"===(void 0===e?"undefined":mO(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=bO[i];if(o)n=o(e);else{var s="Error"===i?Error:wO[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=EO(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},vO.serializeError=function(t){return t?"object"===(void 0===t?"undefined":mO(t))?_O(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(yO,"__esModule",{value:!0}),yO.StatusCodes=yO.DBNotReset=yO.DBWrongPassword=yO.NoDBPathGiven=yO.FirmwareOrAppUpdateRequired=yO.LedgerAPI5xx=yO.LedgerAPI4xx=yO.GenuineCheckFailed=yO.PairingFailed=yO.SyncError=yO.FeeTooHigh=yO.FeeRequired=yO.FeeNotLoaded=yO.CantScanQRCode=yO.ETHAddressNonEIP=yO.WrongAppForCurrency=yO.WrongDeviceForAccount=yO.WebsocketConnectionFailed=yO.WebsocketConnectionError=yO.DeviceShouldStayInApp=yO.TransportWebUSBGestureRequired=yO.TransportInterfaceNotAvailable=yO.TransportOpenUserCancelled=yO.UserRefusedOnDevice=yO.UserRefusedAllowManager=yO.UserRefusedFirmwareUpdate=yO.UserRefusedAddress=yO.UserRefusedDeviceNameChange=yO.UpdateYourApp=yO.UnavailableTezosOriginatedAccountSend=yO.UnavailableTezosOriginatedAccountReceive=yO.RecipientRequired=yO.MCUNotGenuineToDashboard=yO.UnexpectedBootloader=yO.TimeoutTagged=yO.RecommendUndelegation=yO.RecommendSubAccountsToEmpty=yO.PasswordIncorrectError=yO.PasswordsDontMatchError=yO.GasLessThanEstimate=yO.NotSupportedLegacyAddress=yO.NotEnoughGas=yO.NoAccessToCamera=yO.NotEnoughBalanceBecauseDestinationNotCreated=yO.NotEnoughSpendableBalance=yO.NotEnoughBalanceInParentAccount=yO.NotEnoughBalanceToDelegate=yO.NotEnoughBalance=yO.NoAddressesFound=yO.NetworkDown=yO.ManagerUninstallBTCDep=yO.ManagerNotEnoughSpaceError=yO.ManagerFirmwareNotEnoughSpaceError=yO.ManagerDeviceLockedError=yO.ManagerAppDepUninstallRequired=yO.ManagerAppDepInstallRequired=yO.ManagerAppRelyOnBTCError=yO.ManagerAppAlreadyInstalledError=yO.LedgerAPINotAvailable=yO.LedgerAPIErrorWithMessage=yO.LedgerAPIError=yO.UnknownMCU=yO.LatestMCUInstalledError=yO.InvalidAddressBecauseDestinationIsAlsoSource=yO.InvalidAddress=yO.InvalidXRPTag=yO.HardResetFail=yO.FeeEstimationFailed=yO.EthAppPleaseEnableContractData=yO.EnpointConfigError=yO.DisconnectedDeviceDuringOperation=yO.DisconnectedDevice=yO.DeviceSocketNoBulkStatus=yO.DeviceSocketFail=yO.DeviceNameInvalid=yO.DeviceHalted=yO.DeviceInOSUExpected=yO.DeviceOnDashboardUnexpected=yO.DeviceOnDashboardExpected=yO.DeviceNotGenuineError=yO.DeviceGenuineSocketEarlyClose=yO.DeviceAppVerifyNotSupported=yO.CurrencyNotSupported=yO.CashAddrNotSupported=yO.CantOpenDevice=yO.BtcUnmatchedApp=yO.BluetoothRequired=yO.AmountRequired=yO.AccountNotSupported=yO.AccountNameRequiredError=yO.addCustomErrorDeserializer=yO.createCustomErrorClass=yO.deserializeError=yO.serializeError=void 0,yO.TransportError=IO,yO.getAltStatusMessage=OO,yO.TransportStatusError=AO;var SO=vO;function IO(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}yO.serializeError=SO.serializeError,yO.deserializeError=SO.deserializeError,yO.createCustomErrorClass=SO.createCustomErrorClass,yO.addCustomErrorDeserializer=SO.addCustomErrorDeserializer,yO.AccountNameRequiredError=(0,SO.createCustomErrorClass)("AccountNameRequired"),yO.AccountNotSupported=(0,SO.createCustomErrorClass)("AccountNotSupported"),yO.AmountRequired=(0,SO.createCustomErrorClass)("AmountRequired"),yO.BluetoothRequired=(0,SO.createCustomErrorClass)("BluetoothRequired"),yO.BtcUnmatchedApp=(0,SO.createCustomErrorClass)("BtcUnmatchedApp"),yO.CantOpenDevice=(0,SO.createCustomErrorClass)("CantOpenDevice"),yO.CashAddrNotSupported=(0,SO.createCustomErrorClass)("CashAddrNotSupported"),yO.CurrencyNotSupported=(0,SO.createCustomErrorClass)("CurrencyNotSupported"),yO.DeviceAppVerifyNotSupported=(0,SO.createCustomErrorClass)("DeviceAppVerifyNotSupported"),yO.DeviceGenuineSocketEarlyClose=(0,SO.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),yO.DeviceNotGenuineError=(0,SO.createCustomErrorClass)("DeviceNotGenuine"),yO.DeviceOnDashboardExpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardExpected"),yO.DeviceOnDashboardUnexpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardUnexpected"),yO.DeviceInOSUExpected=(0,SO.createCustomErrorClass)("DeviceInOSUExpected"),yO.DeviceHalted=(0,SO.createCustomErrorClass)("DeviceHalted"),yO.DeviceNameInvalid=(0,SO.createCustomErrorClass)("DeviceNameInvalid"),yO.DeviceSocketFail=(0,SO.createCustomErrorClass)("DeviceSocketFail"),yO.DeviceSocketNoBulkStatus=(0,SO.createCustomErrorClass)("DeviceSocketNoBulkStatus"),yO.DisconnectedDevice=(0,SO.createCustomErrorClass)("DisconnectedDevice"),yO.DisconnectedDeviceDuringOperation=(0,SO.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),yO.EnpointConfigError=(0,SO.createCustomErrorClass)("EnpointConfig"),yO.EthAppPleaseEnableContractData=(0,SO.createCustomErrorClass)("EthAppPleaseEnableContractData"),yO.FeeEstimationFailed=(0,SO.createCustomErrorClass)("FeeEstimationFailed"),yO.HardResetFail=(0,SO.createCustomErrorClass)("HardResetFail"),yO.InvalidXRPTag=(0,SO.createCustomErrorClass)("InvalidXRPTag"),yO.InvalidAddress=(0,SO.createCustomErrorClass)("InvalidAddress"),yO.InvalidAddressBecauseDestinationIsAlsoSource=(0,SO.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),yO.LatestMCUInstalledError=(0,SO.createCustomErrorClass)("LatestMCUInstalledError"),yO.UnknownMCU=(0,SO.createCustomErrorClass)("UnknownMCU"),yO.LedgerAPIError=(0,SO.createCustomErrorClass)("LedgerAPIError"),yO.LedgerAPIErrorWithMessage=(0,SO.createCustomErrorClass)("LedgerAPIErrorWithMessage"),yO.LedgerAPINotAvailable=(0,SO.createCustomErrorClass)("LedgerAPINotAvailable"),yO.ManagerAppAlreadyInstalledError=(0,SO.createCustomErrorClass)("ManagerAppAlreadyInstalled"),yO.ManagerAppRelyOnBTCError=(0,SO.createCustomErrorClass)("ManagerAppRelyOnBTC"),yO.ManagerAppDepInstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepInstallRequired"),yO.ManagerAppDepUninstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepUninstallRequired"),yO.ManagerDeviceLockedError=(0,SO.createCustomErrorClass)("ManagerDeviceLocked"),yO.ManagerFirmwareNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),yO.ManagerNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerNotEnoughSpace"),yO.ManagerUninstallBTCDep=(0,SO.createCustomErrorClass)("ManagerUninstallBTCDep"),yO.NetworkDown=(0,SO.createCustomErrorClass)("NetworkDown"),yO.NoAddressesFound=(0,SO.createCustomErrorClass)("NoAddressesFound"),yO.NotEnoughBalance=(0,SO.createCustomErrorClass)("NotEnoughBalance"),yO.NotEnoughBalanceToDelegate=(0,SO.createCustomErrorClass)("NotEnoughBalanceToDelegate"),yO.NotEnoughBalanceInParentAccount=(0,SO.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),yO.NotEnoughSpendableBalance=(0,SO.createCustomErrorClass)("NotEnoughSpendableBalance"),yO.NotEnoughBalanceBecauseDestinationNotCreated=(0,SO.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),yO.NoAccessToCamera=(0,SO.createCustomErrorClass)("NoAccessToCamera"),yO.NotEnoughGas=(0,SO.createCustomErrorClass)("NotEnoughGas"),yO.NotSupportedLegacyAddress=(0,SO.createCustomErrorClass)("NotSupportedLegacyAddress"),yO.GasLessThanEstimate=(0,SO.createCustomErrorClass)("GasLessThanEstimate"),yO.PasswordsDontMatchError=(0,SO.createCustomErrorClass)("PasswordsDontMatch"),yO.PasswordIncorrectError=(0,SO.createCustomErrorClass)("PasswordIncorrect"),yO.RecommendSubAccountsToEmpty=(0,SO.createCustomErrorClass)("RecommendSubAccountsToEmpty"),yO.RecommendUndelegation=(0,SO.createCustomErrorClass)("RecommendUndelegation"),yO.TimeoutTagged=(0,SO.createCustomErrorClass)("TimeoutTagged"),yO.UnexpectedBootloader=(0,SO.createCustomErrorClass)("UnexpectedBootloader"),yO.MCUNotGenuineToDashboard=(0,SO.createCustomErrorClass)("MCUNotGenuineToDashboard"),yO.RecipientRequired=(0,SO.createCustomErrorClass)("RecipientRequired"),yO.UnavailableTezosOriginatedAccountReceive=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),yO.UnavailableTezosOriginatedAccountSend=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),yO.UpdateYourApp=(0,SO.createCustomErrorClass)("UpdateYourApp"),yO.UserRefusedDeviceNameChange=(0,SO.createCustomErrorClass)("UserRefusedDeviceNameChange"),yO.UserRefusedAddress=(0,SO.createCustomErrorClass)("UserRefusedAddress"),yO.UserRefusedFirmwareUpdate=(0,SO.createCustomErrorClass)("UserRefusedFirmwareUpdate"),yO.UserRefusedAllowManager=(0,SO.createCustomErrorClass)("UserRefusedAllowManager"),yO.UserRefusedOnDevice=(0,SO.createCustomErrorClass)("UserRefusedOnDevice"),yO.TransportOpenUserCancelled=(0,SO.createCustomErrorClass)("TransportOpenUserCancelled"),yO.TransportInterfaceNotAvailable=(0,SO.createCustomErrorClass)("TransportInterfaceNotAvailable"),yO.TransportWebUSBGestureRequired=(0,SO.createCustomErrorClass)("TransportWebUSBGestureRequired"),yO.DeviceShouldStayInApp=(0,SO.createCustomErrorClass)("DeviceShouldStayInApp"),yO.WebsocketConnectionError=(0,SO.createCustomErrorClass)("WebsocketConnectionError"),yO.WebsocketConnectionFailed=(0,SO.createCustomErrorClass)("WebsocketConnectionFailed"),yO.WrongDeviceForAccount=(0,SO.createCustomErrorClass)("WrongDeviceForAccount"),yO.WrongAppForCurrency=(0,SO.createCustomErrorClass)("WrongAppForCurrency"),yO.ETHAddressNonEIP=(0,SO.createCustomErrorClass)("ETHAddressNonEIP"),yO.CantScanQRCode=(0,SO.createCustomErrorClass)("CantScanQRCode"),yO.FeeNotLoaded=(0,SO.createCustomErrorClass)("FeeNotLoaded"),yO.FeeRequired=(0,SO.createCustomErrorClass)("FeeRequired"),yO.FeeTooHigh=(0,SO.createCustomErrorClass)("FeeTooHigh"),yO.SyncError=(0,SO.createCustomErrorClass)("SyncError"),yO.PairingFailed=(0,SO.createCustomErrorClass)("PairingFailed"),yO.GenuineCheckFailed=(0,SO.createCustomErrorClass)("GenuineCheckFailed"),yO.LedgerAPI4xx=(0,SO.createCustomErrorClass)("LedgerAPI4xx"),yO.LedgerAPI5xx=(0,SO.createCustomErrorClass)("LedgerAPI5xx"),yO.FirmwareOrAppUpdateRequired=(0,SO.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),yO.NoDBPathGiven=(0,SO.createCustomErrorClass)("NoDBPathGiven"),yO.DBWrongPassword=(0,SO.createCustomErrorClass)("DBWrongPassword"),yO.DBNotReset=(0,SO.createCustomErrorClass)("DBNotReset"),IO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportError",(function(t){return new IO(t.message,t.id)}));var TO=yO.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function OO(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function AO(t){this.name="TransportStatusError";var e=Object.keys(TO).find((function(e){return TO[e]===t}))||"UNKNOWN_ERROR",r=OO(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}AO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new AO(t.statusCode)})),Object.defineProperty(gO,"__esModule",{value:!0}),gO.getAltStatusMessage=gO.StatusCodes=gO.TransportStatusError=gO.TransportError=void 0;var kO,PO=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[xO.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new xO.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new xO.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=NO(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new xO.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return PO(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new xO.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new xO.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();BO.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",BO.ErrorMessage_NoDeviceFound="No Ledger device found",gO.default=BO;var CO={};Object.defineProperty(CO,"__esModule",{value:!0});var UO=yO;function LO(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var DO={data:Buffer.alloc(0),dataLength:0,sequence:0};CO.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([LO(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var HO={};Object.defineProperty(HO,"__esModule",{value:!0});var jO=Object.assign||function(t){for(var e=1;e>8;return KO.find((function(t){return t.productIdMM===r}))},HO.identifyProductName=function(t){var e=FO[t];return KO.find((function(t){return t.id===e}))};var GO=[],WO={};for(var VO in qO){var $O=qO[VO],zO=$O.bluetoothSpec;if(zO)for(var XO=0;XO0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",oA());case 6:case"end":return t.stop()}}),t,this)}))),function(){return iA.apply(this,arguments)});var uA=HO;function aA(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var hA=[{vendorId:uA.ledgerUSBVendorId}];eA.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(dO,"__esModule",{value:!0});var fA=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,lA.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,dA.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,dA.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new gA.DisconnectedDeviceDuringOperation(e.message);throw e}))}},EA=dO.default=wA,_A=Object.freeze(e({__proto__:null,default:EA},[dO]));t.Btc=pO,t.TransportWebUSB=_A,Object.defineProperty(t,"__esModule",{value:!0})})); +//# sourceMappingURL=build.js.map window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 9659f602cc17d271f7f4ff5701e5ef1f58660bb3 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 14:46:53 +1100 Subject: [PATCH 12/78] ... --- js/ledger.js | 30904 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 30901 insertions(+), 3 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index bac16a32..a12e852e 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,9 +2,30907 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}const i=2147483648;var o=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=i)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[s]+=i;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new o(n)},o.prototype.toPathArray=function(){return this.path},o.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var s=o,u=n(Object.freeze({__proto__:null,default:{}})),a=u.createHash,h={exports:{}},f=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p=!1;function d(){p=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+f[i>>12&63]+f[i>>6&63]+f[63&i]);return o.join("")}function y(t){var e;p||d();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=f[e>>2],i+=f[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=f[e>>10],i+=f[e>>4&63],i+=f[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function m(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var w={}.toString,b=Array.isArray||function(t){return"[object Array]"==w.call(t)};I.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=_();function _(){return I.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function S(t,e){if(_()=_())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_().toString(16)+" bytes");return 0|t}function M(t){return!(null==t||!t._isBuffer)}function x(t,e){if(M(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return it(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ot(t).length;default:if(n)return it(t).length;e=(""+e).toLowerCase(),n=!0}}function R(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return $(this,e,r);case"utf8":case"utf-8":return K(this,e,r);case"ascii":return W(this,e,r);case"latin1":case"binary":return V(this,e,r);case"base64":return F(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function N(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=I.from(e,n)),M(e))return 0===e.length?-1:C(t,e,r,n,i);if("number"==typeof e)return e&=255,I.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):C(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function C(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function F(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function K(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=G)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},I.prototype.compare=function(t,e,r,n,i){if(!M(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return U(this,t,e,r);case"utf8":case"utf-8":return L(this,t,e,r);case"ascii":return D(this,t,e,r);case"latin1":case"binary":return H(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},I.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var G=4096;function W(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function Y(t,e,r,n,i,o){if(!M(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function J(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Z(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function Q(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function tt(t,e,r,n,i){return i||Q(t,0,r,4),m(t,e,r,n,23,4),r+4}function et(t,e,r,n,i){return i||Q(t,0,r,8),m(t,e,r,n,52,8),r+8}I.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},I.prototype.readUInt8=function(t,e){return e||X(t,1,this.length),this[t]},I.prototype.readUInt16LE=function(t,e){return e||X(t,2,this.length),this[t]|this[t+1]<<8},I.prototype.readUInt16BE=function(t,e){return e||X(t,2,this.length),this[t]<<8|this[t+1]},I.prototype.readUInt32LE=function(t,e){return e||X(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},I.prototype.readUInt32BE=function(t,e){return e||X(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},I.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},I.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||X(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},I.prototype.readInt8=function(t,e){return e||X(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},I.prototype.readInt16LE=function(t,e){e||X(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt16BE=function(t,e){e||X(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},I.prototype.readInt32LE=function(t,e){return e||X(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},I.prototype.readInt32BE=function(t,e){return e||X(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},I.prototype.readFloatLE=function(t,e){return e||X(t,4,this.length),v(this,t,!0,23,4)},I.prototype.readFloatBE=function(t,e){return e||X(t,4,this.length),v(this,t,!1,23,4)},I.prototype.readDoubleLE=function(t,e){return e||X(t,8,this.length),v(this,t,!0,52,8)},I.prototype.readDoubleBE=function(t,e){return e||X(t,8,this.length),v(this,t,!1,52,8)},I.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||Y(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},I.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,255,0),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},I.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,65535,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Z(this,t,e,!0),e+4},I.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,4294967295,0),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},I.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);Y(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},I.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,1,127,-128),I.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},I.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):J(this,t,e,!0),e+2},I.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,2,32767,-32768),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):J(this,t,e,!1),e+2},I.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),I.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Z(this,t,e,!0),e+4},I.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||Y(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),I.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Z(this,t,e,!1),e+4},I.prototype.writeFloatLE=function(t,e,r){return tt(this,t,e,!0,r)},I.prototype.writeFloatBE=function(t,e,r){return tt(this,t,e,!1,r)},I.prototype.writeDoubleLE=function(t,e,r){return et(this,t,e,!0,r)},I.prototype.writeDoubleBE=function(t,e,r){return et(this,t,e,!1,r)},I.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!I.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ot(t){return function(t){var e,r,n,i,o,s;p||d();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new l(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(rt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function st(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ut(t){return null!=t&&(!!t._isBuffer||at(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&at(t.slice(0,0))}(t))}function at(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ht=n(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:I,SlowBuffer:function(t){return+t!=t&&(t=0),I.alloc(+t)},isBuffer:ut})); -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -!function(t,e){var r=ht,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(h,h.exports);var ft=h.exports.Buffer;var ct=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ft.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ft.from(e)),!ft.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,k=0|s[6],P=8191&k,M=k>>>13,x=0|s[7],R=8191&x,N=x>>>13,B=0|s[8],C=8191&B,U=B>>>13,L=0|s[9],D=8191&L,H=L>>>13,j=0|u[0],q=8191&j,F=j>>>13,K=0|u[1],G=8191&K,W=K>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(c,q))|0)+((8191&(i=(i=Math.imul(c,F))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,F))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,F))+Math.imul(g,q)|0,o=Math.imul(g,F);var vt=(h+(n=n+Math.imul(c,G)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,G)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,F))+Math.imul(m,q)|0,o=Math.imul(m,F),n=n+Math.imul(d,G)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,W)|0;var mt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,F))+Math.imul(E,q)|0,o=Math.imul(E,F),n=n+Math.imul(v,G)|0,i=(i=i+Math.imul(v,W)|0)+Math.imul(m,G)|0,o=o+Math.imul(m,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,F))+Math.imul(I,q)|0,o=Math.imul(I,F),n=n+Math.imul(b,G)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(E,G)|0,o=o+Math.imul(E,W)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,F))+Math.imul(A,q)|0,o=Math.imul(A,F),n=n+Math.imul(S,G)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,G)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(P,q),i=(i=Math.imul(P,F))+Math.imul(M,q)|0,o=Math.imul(M,F),n=n+Math.imul(O,G)|0,i=(i=i+Math.imul(O,W)|0)+Math.imul(A,G)|0,o=o+Math.imul(A,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(R,q),i=(i=Math.imul(R,F))+Math.imul(N,q)|0,o=Math.imul(N,F),n=n+Math.imul(P,G)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,W)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(C,q),i=(i=Math.imul(C,F))+Math.imul(U,q)|0,o=Math.imul(U,F),n=n+Math.imul(R,G)|0,i=(i=i+Math.imul(R,W)|0)+Math.imul(N,G)|0,o=o+Math.imul(N,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(M,$)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,q),i=(i=Math.imul(D,F))+Math.imul(H,q)|0,o=Math.imul(H,F),n=n+Math.imul(C,G)|0,i=(i=i+Math.imul(C,W)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,z)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(M,Y)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,G),i=(i=Math.imul(D,W))+Math.imul(H,G)|0,o=Math.imul(H,W),n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ct)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ct)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(M,rt)|0,o=o+Math.imul(M,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ct)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(N,rt)|0,o=o+Math.imul(N,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(M,ot)|0,o=o+Math.imul(M,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var kt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(R,ot)|0,i=(i=i+Math.imul(R,st)|0)+Math.imul(N,ot)|0,o=o+Math.imul(N,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(M,at)|0,o=o+Math.imul(M,ht)|0,n=n+Math.imul(O,ct)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ct)|0,o=o+Math.imul(A,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(C,ot)|0,i=(i=i+Math.imul(C,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ht)|0)+Math.imul(N,at)|0,o=o+Math.imul(N,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(M,ct)|0,o=o+Math.imul(M,lt)|0;var Mt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(R,ct)|0,i=(i=i+Math.imul(R,lt)|0)+Math.imul(N,ct)|0,o=o+Math.imul(N,lt)|0;var xt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(M,dt)|0))<<13)|0;h=((o=o+Math.imul(M,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(C,ct)|0,i=(i=i+Math.imul(C,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Rt=(h+(n=n+Math.imul(R,dt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(N,dt)|0))<<13)|0;h=((o=o+Math.imul(N,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var Nt=(h+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=kt,a[13]=Pt,a[14]=Mt,a[15]=xt,a[16]=Rt,a[17]=Nt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Rt);var Nt={},Bt="6.5.4",Ct={},Ut=Lt;function Lt(t,e){if(!t)throw new Error(e||"Assertion failed")}Lt.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Dt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Dt),function(t){var e=t,r=Rt.exports,n=Ut,i=Dt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ct);var Ht,jt={exports:{}};function qt(t){this.rand=t}if(jt.exports=function(t){return Ht||(Ht=new qt(null)),Ht.generate(t)},jt.exports.Rand=qt,qt.prototype.generate=function(t){return this._rand(t)},qt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Yt=Xt;function Jt(t,e){this.curve=t,this.type=e,this.precomputed=null}Xt.prototype.point=function(){throw new Error("Not implemented")},Xt.prototype.validate=function(){throw new Error("Not implemented")},Xt.prototype._fixedNafMul=function(t,e){zt(t.precomputed);var r=t._getDoubles(),n=Vt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];zt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Xt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=$t(r[p],r[d]);for(c=Math.max(v[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Jt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},se.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},se.prototype.pointFromX=function(t,e){(t=new re(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},se.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},se.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ae.prototype.isInfinity=function(){return this.inf},ae.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ae.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ae.prototype.getX=function(){return this.x.fromRed()},ae.prototype.getY=function(){return this.y.fromRed()},ae.prototype.mul=function(t){return t=new re(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ae.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ae.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ae.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ae.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ae.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},ne(he,ie.BasePoint),se.prototype.jpoint=function(t,e,r){return new he(this,t,e,r)},he.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},he.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},he.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},he.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},he.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},he.prototype.inspect=function(){return this.isInfinity()?"":""},he.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var fe=Rt.exports,ce=Zt.exports,le=Yt,pe=Ct;function de(t){le.call(this,"mont",t),this.a=new fe(t.a,16).toRed(this.red),this.b=new fe(t.b,16).toRed(this.red),this.i4=new fe(4).toRed(this.red).redInvm(),this.two=new fe(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}ce(de,le);var ge=de;function ye(t,e,r){le.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new fe(e,16),this.z=new fe(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}de.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},ce(ye,le.BasePoint),de.prototype.decodePoint=function(t,e){return this.point(pe.toArray(t,e),1)},de.prototype.point=function(t,e){return new ye(this,t,e)},de.prototype.pointFromJSON=function(t){return ye.fromJSON(this,t)},ye.prototype.precompute=function(){},ye.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ye.fromJSON=function(t,e){return new ye(t,e[0],e[1]||t.one)},ye.prototype.inspect=function(){return this.isInfinity()?"":""},ye.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ye.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ye.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ye.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ye.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ye.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ye.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ye.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var ve=Ct,me=Rt.exports,we=Zt.exports,be=Yt,Ee=ve.assert;function _e(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,be.call(this,"edwards",t),this.a=new me(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new me(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new me(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Ee(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}we(_e,be);var Se=_e;function Ie(t,e,r,n,i){be.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new me(e,16),this.y=new me(r,16),this.z=n?new me(n,16):this.curve.one,this.t=i&&new me(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}_e.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},_e.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},_e.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},_e.prototype.pointFromX=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},_e.prototype.pointFromY=function(t,e){(t=new me(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},_e.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},we(Ie,be.BasePoint),_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},_e.prototype.point=function(t,e,r,n){return new Ie(this,t,e,r,n)},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1],e[2])},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ie.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Ie.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ie.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ie.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Ie.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Ie.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ie.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ie.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ie.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ie.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ie.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ie.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ie.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ie.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ie.prototype.toP=Ie.prototype.normalize,Ie.prototype.mixedAdd=Ie.prototype.add,function(t){var e=t;e.base=Yt,e.short=ue,e.mont=ge,e.edwards=Se}(Kt);var Te={},Oe={},Ae={},ke=Ut,Pe=Zt.exports;function Me(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Re(t){return 1===t.length?"0"+t:t}function Ne(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ae.inherits=Pe,Ae.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Me(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ae.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ae.rotr32=function(t,e){return t>>>e|t<<32-e},Ae.rotl32=function(t,e){return t<>>32-e},Ae.sum32=function(t,e){return t+e>>>0},Ae.sum32_3=function(t,e,r){return t+e+r>>>0},Ae.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ae.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ae.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ae.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ae.sum64_lo=function(t,e,r,n){return e+n>>>0},Ae.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ae.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ae.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Ae.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ae.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ae.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ae.shr64_hi=function(t,e,r){return t>>>r},Ae.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Be={},Ce=Ae,Ue=Ut;function Le(){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}Be.BlockHash=Le,Le.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},He.g1_256=function(t){return je(t,17)^je(t,19)^t>>>10};var Ge=Ae,We=Be,Ve=He,$e=Ge.rotl32,ze=Ge.sum32,Xe=Ge.sum32_5,Ye=Ve.ft_1,Je=We.BlockHash,Ze=[1518500249,1859775393,2400959708,3395469782];function Qe(){if(!(this instanceof Qe))return new Qe;Je.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ge.inherits(Qe,Je);var tr=Qe;Qe.blockSize=512,Qe.outSize=160,Qe.hmacStrength=80,Qe.padLength=64,Qe.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),bn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var An=On;On.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},On.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=In.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Rn=Rt.exports,Nn=Ct,Bn=Nn.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Bn(t.r&&t.s,"Signature without r or s"),this.r=new Rn(t.r,16),this.s=new Rn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Un=Cn;function Ln(){this.place=0}function Dn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function Hn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Nn.toArray(t,e);var r=new Ln;if(48!==t[r.place++])return!1;var n=Dn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Dn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Dn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Rn(o),this.s=new Rn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=Hn(e),r=Hn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];jn(n,e.length),(n=n.concat(e)).push(2),jn(n,r.length);var i=n.concat(r),o=[48];return jn(o,i.length),o=o.concat(i),Nn.encode(o,t)};var qn=Rt.exports,Fn=An,Kn=Ct,Gn=Te,Wn=jt.exports,Vn=Kn.assert,$n=xn,zn=Un;function Xn(t){if(!(this instanceof Xn))return new Xn(t);"string"==typeof t&&(Vn(Object.prototype.hasOwnProperty.call(Gn,t),"Unknown curve "+t),t=Gn[t]),t instanceof Gn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Yn=Xn;Xn.prototype.keyPair=function(t){return new $n(this,t)},Xn.prototype.keyFromPrivate=function(t,e){return $n.fromPrivate(this,t,e)},Xn.prototype.keyFromPublic=function(t,e){return $n.fromPublic(this,t,e)},Xn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Fn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Wn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new qn(2));;){var i=new qn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Xn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Xn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new qn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Fn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new qn(1)),h=0;;h++){var f=n.k?n.k(h):new qn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new zn({r:p,s:d,recoveryParam:g})}}}}}},Xn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new qn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new zn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Xn.prototype.recoverPubKey=function(t,e,r,n){Vn((3&r)===r,"The recovery param is more than two bits"),e=new zn(e,n);var i=this.n,o=new qn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Xn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new zn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Jn=Ct,Zn=Jn.assert,Qn=Jn.parseBytes,ti=Jn.cachedProperty;function ei(t,e){this.eddsa=t,this._secret=Qn(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=Qn(e.pub)}ei.fromPublic=function(t,e){return e instanceof ei?e:new ei(t,{pub:e})},ei.fromSecret=function(t,e){return e instanceof ei?e:new ei(t,{secret:e})},ei.prototype.secret=function(){return this._secret},ti(ei,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ti(ei,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ti(ei,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ti(ei,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ti(ei,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ti(ei,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ei.prototype.sign=function(t){return Zn(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ei.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ei.prototype.getSecret=function(t){return Zn(this._secret,"KeyPair is public only"),Jn.encode(this.secret(),t)},ei.prototype.getPublic=function(t){return Jn.encode(this.pubBytes(),t)};var ri=ei,ni=Rt.exports,ii=Ct,oi=ii.assert,si=ii.cachedProperty,ui=ii.parseBytes;function ai(t,e){this.eddsa=t,"object"!=typeof e&&(e=ui(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),oi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof ni&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}si(ai,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),si(ai,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),si(ai,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),si(ai,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),ai.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},ai.prototype.toHex=function(){return ii.encode(this.toBytes(),"hex").toUpperCase()};var hi=ai,fi=Oe,ci=Te,li=Ct,pi=li.assert,di=li.parseBytes,gi=ri,yi=hi;function vi(t){if(pi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof vi))return new vi(t);t=ci[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=fi.sha512}var mi=vi;vi.prototype.sign=function(t,e){t=di(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},vi.prototype.verify=function(t,e,r){t=di(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},vi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Gi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Oi)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function Hi(t){return 4!==t[0]}function ji(t){return!!Ui(t)&&(t.compare(Oi)>0&&t.compare(Ai)<0)}function qi(t,e){return void 0===t&&void 0!==e?Hi(e):void 0===t||t}function Fi(t){return new Si(t)}function Ki(t){return t.toArrayLike(Buffer,"be",32)}function Gi(t){return Ii.curve.decodePoint(t)}function Wi(t,e){return Buffer.from(t._encode(e))}function Vi(t,e,r){if(!Ui(t))throw new TypeError(Ci);if(!ji(e))throw new TypeError(Ri);if(void 0!==r&&!Ui(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Fi(e),i=Fi(t);let o,s;Ti(t,e,(function(t){const e=Fi(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Pi),0!==o.isZero()&&(s=e.invm(Pi).mul(i.add(n.mul(o))).umod(Pi),0!==s.isZero()))}),ji,r),s.cmp(Mi)>0&&(s=Pi.sub(s));const u=Buffer.allocUnsafe(64);return Ki(o).copy(u,0),Ki(s).copy(u,32),u}var $i={isPoint:Di,isPointCompressed:function(t){return!!Di(t)&&Hi(t)},isPrivate:ji,pointAdd:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Di(e))throw new TypeError(Ni);const n=Gi(t),i=Gi(e),o=n.add(i);return o.isInfinity()?null:Wi(o,qi(r,t))},pointAddScalar:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t);if(0===e.compare(Oi))return Wi(i,n);const o=Fi(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:Wi(u,n)},pointCompress:function(t,e){if(!Di(t))throw new TypeError(Ni);const r=Gi(t);if(r.isInfinity())throw new TypeError(Ni);return Wi(r,qi(e,t))},pointFromScalar:function(t,e){if(!ji(t))throw new TypeError(Ri);const r=Fi(t),n=xi.mul(r);return n.isInfinity()?null:Wi(n,qi(e))},pointMultiply:function(t,e,r){if(!Di(t))throw new TypeError(Ni);if(!Li(e))throw new TypeError(Bi);const n=qi(r,t),i=Gi(t),o=Fi(e),s=i.mul(o);return s.isInfinity()?null:Wi(s,n)},privateAdd:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.add(n).umod(Pi));return ji(i)?i:null},privateSub:function(t,e){if(!ji(t))throw new TypeError(Ri);if(!Li(e))throw new TypeError(Bi);const r=Fi(t),n=Fi(e),i=Ki(r.sub(n).umod(Pi));return ji(i)?i:null},sign:function(t,e){return Vi(t,e)},signWithEntropy:function(t,e,r){return Vi(t,e,r)},verify:function(t,e,r,n){if(!Ui(t))throw new TypeError(Ci);if(!Di(e))throw new TypeError(Ni);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Ai)<0&&r.compare(Ai)<0}(r))throw new TypeError("Expected Signature");const i=Gi(e),o=Fi(r.slice(0,32)),s=Fi(r.slice(32,64));if(n&&s.cmp(Mi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Fi(t),a=s.invm(Pi),h=u.mul(a).umod(Pi),f=o.mul(a).umod(Pi),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Pi).eq(o)}};try{xt.exports=require("./native")}catch(t){xt.exports=$i}var zi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Xi in zi.Null=zi.Nil,zi)zi[Xi].toJSON=function(t){return t}.bind(null,Xi);var Yi=zi,Ji=Yi;function Zi(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function Qi(t){return Ji.Nil(t)?"":Zi(t.constructor)}function to(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function eo(t){return Ji.Function(t)?t.toJSON?t.toJSON():Zi(t):Ji.Array(t)?"Array":t&&Ji.Object(t)?"Object":void 0!==t?t:""}function ro(t,e,r){var n=function(t){return Ji.Function(t)?"":Ji.String(t)?JSON.stringify(t):t&&Ji.Object(t)?"":t}(e);return"Expected "+eo(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function no(t,e,r){r=r||Qi(e),this.message=ro(t,e,r),to(this,no),this.__type=t,this.__value=e,this.__valueTypeName=r}function io(t,e,r,n,i){t?(i=i||Qi(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),ro('property "'+eo(r)+o+eo(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',to(this,no),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}no.prototype=Object.create(Error.prototype),no.prototype.constructor=no,io.prototype=Object.create(Error.prototype),io.prototype.constructor=no;var oo={TfTypeError:no,TfPropertyTypeError:io,tfCustomError:function(t,e){return new no(t,{},e)},tfSubError:function(t,e,r){return t instanceof io?(e=e+"."+t.__property,t=new io(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof no&&(t=new io(t.__type,e,r,t.__value,t.__valueTypeName)),to(t),t},tfJSON:eo,getValueTypeName:Qi},so=Yi,uo=oo;function ao(t){return Buffer.isBuffer(t)}function ho(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function fo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw uo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var co=fo.bind(null,so.Array),lo=fo.bind(null,ao),po=fo.bind(null,ho),go=fo.bind(null,so.String);var yo=Math.pow(2,53)-1;var vo={ArrayN:co,Buffer:ao,BufferN:lo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:ho,HexN:po,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-yo&&t<=yo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=yo&&Math.floor(t)===t}};for(var mo in vo)vo[mo].toJSON=function(t){return t}.bind(null,mo);var wo=vo,bo=Yi,Eo=oo.tfJSON,_o=oo.TfTypeError,So=oo.TfPropertyTypeError,Io=oo.tfSubError,To=oo.getValueTypeName,Oo={arrayOf:function(t,e){function r(r,n){return!!bo.Array(r)&&(!bo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw Io(t,r)}}))))))}return t=Ao(t),e=e||{},r.toJSON=function(){var r="["+Eo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return bo.Nil(r)||e(r,n,t)}return e=Ao(e),r.toJSON=function(){return"?"+Eo(e)},r},map:function(t,e){function r(r,n){if(!bo.Object(r))return!1;if(bo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw Io(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw Io(t,i)}}return!0}return t=Ao(t),e&&(e=Ao(e)),r.toJSON=e?function(){return"{"+Eo(e)+": "+Eo(t)+"}"}:function(){return"{"+Eo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Ao(t[r]);function n(t,r){if(!bo.Object(t))return!1;if(bo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw Io(t,n)}if(r)for(n in t)if(!e[n])throw new So(void 0,n);return!0}return n.toJSON=function(){return Eo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Eo).join(" & ")},e},quacksLike:function(t){function e(e){return t===To(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Ao);function e(e,r){return!bo.Nil(e)&&(!bo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw Io(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Eo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Ao(t){if(bo.String(t))return"?"===t[0]?Oo.maybe(t.slice(1)):bo[t]||Oo.quacksLike(t);if(t&&bo.Object(t)){if(bo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Oo.arrayOf(t[0])}return Oo.object(t)}return bo.Function(t)?t:Oo.value(t)}function ko(t,e,r,n){if(bo.Function(t)){if(t(e,r))return!0;throw new _o(n||t,e)}return ko(Ao(t),e,r)}for(var Po in Oo.oneOf=Oo.anyOf,bo)ko[Po]=bo[Po];for(Po in Oo)ko[Po]=Oo[Po];var Mo=wo;for(Po in Mo)ko[Po]=Mo[Po];ko.compile=Ao,ko.TfTypeError=_o,ko.TfPropertyTypeError=So;var xo=ko,Ro=vt;function No(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Bo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return No(Ro.decode(t),e)},decodeRaw:No,encode:function(t,e,r){return"number"==typeof t?Ro.encode(Bo(t,e,r)):Ro.encode(Bo(t.version,t.privateKey,t.compressed))},encodeRaw:Bo};Object.defineProperty(Ot,"__esModule",{value:!0});const Uo=At,Lo=vt,Do=xt.exports,Ho=xo,jo=Co,qo=Ho.BufferN(32),Fo=Ho.compile({wif:Ho.UInt8,bip32:{public:Ho.UInt32,private:Ho.UInt32}}),Ko={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Go=2147483648,Wo=Math.pow(2,31)-1;function Vo(t){return Ho.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function $o(t){return Ho.UInt32(t)&&t<=Wo}class zo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,Ho(Fo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Do.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Uo.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Jo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Lo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return jo.encode(this.network.wif,this.privateKey,!0)}derive(t){Ho(Ho.UInt32,t);const e=t>=Go,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Uo.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Do.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Do.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Jo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Do.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Yo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return Ho($o,t),this.derive(t+Go)}derivePath(t){Ho(Vo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Do.sign(t,this.privateKey);{let e=Do.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Do.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Do.verify(t,this.publicKey,e)}}function Xo(t,e,r){return Yo(t,e,r)}function Yo(t,e,r,n,i,o){if(Ho({privateKey:qo,chainCode:qo},{privateKey:t,chainCode:e}),r=r||Ko,!Do.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new zo(t,void 0,e,r,n,i,o)}function Jo(t,e,r,n,i,o){if(Ho({publicKey:Ho.BufferN(33),chainCode:qo},{publicKey:t,chainCode:e}),r=r||Ko,!Do.isPoint(t))throw new TypeError("Point is not on the curve");return new zo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Lo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Ko;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Yo(r.slice(46,78),u,e,i,s,o)}else{a=Jo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Xo,Ot.fromPublicKey=function(t,e,r){return Jo(t,e,r)},Ot.fromSeed=function(t,e){if(Ho(Ho.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Ko;const r=Uo.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Xo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var Zo=Ot;Tt.fromSeed=Zo.fromSeed,Tt.fromBase58=Zo.fromBase58,Tt.fromPublicKey=Zo.fromPublicKey,Tt.fromPrivateKey=Zo.fromPrivateKey;var Qo={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ts.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ts.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var es={},rs={},ns={},is={};Object.defineProperty(is,"__esModule",{value:!0}),is.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0});const us=xo,as=Math.pow(2,31)-1;function hs(t){return us.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ss.UInt31=function(t){return us.UInt32(t)&&t<=as},ss.BIP32Path=hs,hs.toJSON=()=>"BIP32 derivation path",ss.Signer=function(t){return(us.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ss.Satoshi=function(t){return us.UInt53(t)&&t<=21e14},ss.ECPoint=us.quacksLike("Point"),ss.Network=us.compile({messagePrefix:us.oneOf(us.Buffer,us.String),bip32:{public:us.UInt32,private:us.UInt32},pubKeyHash:us.UInt8,scriptHash:us.UInt8,wif:us.UInt8}),ss.Buffer256bit=us.BufferN(32),ss.Hash160bit=us.BufferN(20),ss.Hash256bit=us.BufferN(32),ss.Number=us.Number,ss.Array=us.Array,ss.Boolean=us.Boolean,ss.String=us.String,ss.Buffer=us.Buffer,ss.Hex=us.Hex,ss.maybe=us.maybe,ss.tuple=us.tuple,ss.UInt8=us.UInt8,ss.UInt32=us.UInt32,ss.Function=us.Function,ss.BufferN=us.BufferN,ss.Null=us.Null,ss.oneOf=us.oneOf;var fs=h.exports.Buffer;var cs={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=fs.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(os,"__esModule",{value:!0});const ls=ss,ps=cs,ds=xo,gs=Buffer.alloc(1,0);function ys(t){let e=0;for(;0===t[e];)++e;return e===t.length?gs:128&(t=t.slice(e))[0]?Buffer.concat([gs,t],1+t.length):t}function vs(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}os.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=ps.decode(t.slice(0,-1)),i=vs(n.r),o=vs(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},os.encode=function(t,e){ds({signature:ls.BufferN(64),hashType:ls.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=ys(t.slice(0,32)),o=ys(t.slice(32,64));return Buffer.concat([ps.encode(i,o),n])};var ms={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},ws=ms;function bs(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===ws.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==ws.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},_s=ms,Ss={};for(var Is in _s){Ss[_s[Is]]=Is}var Ts=Ss;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=is,r=os,n=ss,i=cs,o=xt.exports,s=Es,u=xo;t.OPS=ms;const a=Ts,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(ns);var Os={};Object.defineProperty(Os,"__esModule",{value:!0}),Os.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Os.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(rs,"__esModule",{value:!0});const As=ts,ks=ns,Ps=Os,Ms=xo,xs=ks.OPS;rs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ms({network:Ms.maybe(Ms.Object),output:Ms.maybe(Ms.Buffer),data:Ms.maybe(Ms.arrayOf(Ms.Buffer))},t);const r={name:"embed",network:t.network||As.bitcoin};if(Ps.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Ps.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ms.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0});const Ns=ts,Bs=ns,Cs=Os,Us=Bs.OPS,Ls=xo,Ds=xt.exports,Hs=Us.OP_RESERVED;function js(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Rs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Bs.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Us.OP_0)}e=Object.assign({validate:!0},e||{}),Ls({network:Ls.maybe(Ls.Object),m:Ls.maybe(Ls.Number),n:Ls.maybe(Ls.Number),output:Ls.maybe(Ls.Buffer),pubkeys:Ls.maybe(Ls.arrayOf(Ds.isPoint)),signatures:Ls.maybe(Ls.arrayOf(r)),input:Ls.maybe(Ls.Buffer)},t);const n={network:t.network||Ns.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Bs.decompile(t),n.m=i[0]-Hs,n.n=i[i.length-2]-Hs,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Bs.compile([].concat(Hs+t.m,t.pubkeys,Hs+n.n,Us.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Bs.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Bs.compile([Us.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Ls.Number(i[0]))throw new TypeError("Output is invalid");if(!Ls.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Us.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ds.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!js(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Us.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!js(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var qs={};Object.defineProperty(qs,"__esModule",{value:!0});const Fs=ts,Ks=ns,Gs=Os,Ws=xo,Vs=Ks.OPS,$s=xt.exports;qs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ws({network:Ws.maybe(Ws.Object),output:Ws.maybe(Ws.Buffer),pubkey:Ws.maybe($s.isPoint),signature:Ws.maybe(Ks.isCanonicalScriptSignature),input:Ws.maybe(Ws.Buffer)},t);const r=Gs.value((()=>Ks.decompile(t.input))),n={name:"p2pk",network:t.network||Fs.bitcoin};if(Gs.prop(n,"output",(()=>{if(t.pubkey)return Ks.compile([t.pubkey,Vs.OP_CHECKSIG])})),Gs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Gs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Gs.prop(n,"input",(()=>{if(t.signature)return Ks.compile([t.signature])})),Gs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==Vs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!$s.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Ks.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var zs={},Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=a;function Js(t){try{return Ys("rmd160").update(t).digest()}catch(e){return Ys("ripemd160").update(t).digest()}}function Zs(t){return Ys("sha256").update(t).digest()}Xs.ripemd160=Js,Xs.sha1=function(t){return Ys("sha1").update(t).digest()},Xs.sha256=Zs,Xs.hash160=function(t){return Js(Zs(t))},Xs.hash256=function(t){return Zs(Zs(t))},Object.defineProperty(zs,"__esModule",{value:!0});const Qs=Xs,tu=ts,eu=ns,ru=Os,nu=xo,iu=eu.OPS,ou=xt.exports,su=vt;zs.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),nu({network:nu.maybe(nu.Object),address:nu.maybe(nu.String),hash:nu.maybe(nu.BufferN(20)),output:nu.maybe(nu.BufferN(25)),pubkey:nu.maybe(ou.isPoint),signature:nu.maybe(eu.isCanonicalScriptSignature),input:nu.maybe(nu.Buffer)},t);const r=ru.value((()=>{const e=su.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=ru.value((()=>eu.decompile(t.input))),i=t.network||tu.bitcoin,o={name:"p2pkh",network:i};if(ru.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),su.encode(t)})),ru.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?Qs.hash160(t.pubkey||o.pubkey):void 0)),ru.prop(o,"output",(()=>{if(o.hash)return eu.compile([iu.OP_DUP,iu.OP_HASH160,o.hash,iu.OP_EQUALVERIFY,iu.OP_CHECKSIG])})),ru.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),ru.prop(o,"signature",(()=>{if(t.input)return n()[0]})),ru.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return eu.compile([t.signature,t.pubkey])})),ru.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==iu.OP_DUP||t.output[1]!==iu.OP_HASH160||20!==t.output[2]||t.output[23]!==iu.OP_EQUALVERIFY||t.output[24]!==iu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=Qs.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!eu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!ou.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=Qs.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var uu={};Object.defineProperty(uu,"__esModule",{value:!0});const au=Xs,hu=ts,fu=ns,cu=Os,lu=xo,pu=fu.OPS,du=vt;uu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),lu({network:lu.maybe(lu.Object),address:lu.maybe(lu.String),hash:lu.maybe(lu.BufferN(20)),output:lu.maybe(lu.BufferN(23)),redeem:lu.maybe({network:lu.maybe(lu.Object),output:lu.maybe(lu.Buffer),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))}),input:lu.maybe(lu.Buffer),witness:lu.maybe(lu.arrayOf(lu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||hu.bitcoin);const n={network:r},i=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=cu.value((()=>fu.decompile(t.input))),s=cu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:fu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(cu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),du.encode(t)})),cu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?au.hash160(n.redeem.output):void 0)),cu.prop(n,"output",(()=>{if(n.hash)return fu.compile([pu.OP_HASH160,n.hash,pu.OP_EQUAL])})),cu.prop(n,"redeem",(()=>{if(t.input)return s()})),cu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return fu.compile([].concat(fu.decompile(t.redeem.input),t.redeem.output))})),cu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),cu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==pu.OP_HASH160||20!==t.output[1]||t.output[22]!==pu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=fu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=au.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=fu.decompile(t.input);if(!fu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var gu={},yu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",vu={},mu=0;mu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Eu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=bu(e)^n>>5}for(e=bu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Eu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Su(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Eu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=bu(n)^s,i+=yu.charAt(s)}for(o=0;o<6;++o)n=bu(n);for(n^=1,o=0;o<6;++o){i+=yu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Su(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Su(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(gu,"__esModule",{value:!0});const Tu=Xs,Ou=ts,Au=ns,ku=Os,Pu=xo,Mu=Au.OPS,xu=xt.exports,Ru=Iu,Nu=Buffer.alloc(0);gu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Pu({address:Pu.maybe(Pu.String),hash:Pu.maybe(Pu.BufferN(20)),input:Pu.maybe(Pu.BufferN(0)),network:Pu.maybe(Pu.Object),output:Pu.maybe(Pu.BufferN(22)),pubkey:Pu.maybe(xu.isPoint),signature:Pu.maybe(Au.isCanonicalScriptSignature),witness:Pu.maybe(Pu.arrayOf(Pu.Buffer))},t);const r=ku.value((()=>{const e=Ru.decode(t.address),r=e.words.shift(),n=Ru.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Ou.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Ru.toWords(i.hash);return t.unshift(0),Ru.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Tu.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Au.compile([Mu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Nu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Mu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Tu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Au.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Tu.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0});const Cu=Xs,Uu=ts,Lu=ns,Du=Os,Hu=xo,ju=Lu.OPS,qu=xt.exports,Fu=Iu,Ku=Buffer.alloc(0);function Gu(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!qu.isPoint(t))}Bu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Hu({network:Hu.maybe(Hu.Object),address:Hu.maybe(Hu.String),hash:Hu.maybe(Hu.BufferN(32)),output:Hu.maybe(Hu.BufferN(34)),redeem:Hu.maybe({input:Hu.maybe(Hu.Buffer),network:Hu.maybe(Hu.Object),output:Hu.maybe(Hu.Buffer),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))}),input:Hu.maybe(Hu.BufferN(0)),witness:Hu.maybe(Hu.arrayOf(Hu.Buffer))},t);const r=Du.value((()=>{const e=Fu.decode(t.address),r=e.words.shift(),n=Fu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Du.value((()=>Lu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Uu.bitcoin);const o={network:i};if(Du.prop(o,"address",(()=>{if(!o.hash)return;const t=Fu.toWords(o.hash);return t.unshift(0),Fu.encode(i.bech32,t)})),Du.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Du.prop(o,"output",(()=>{if(o.hash)return Lu.compile([ju.OP_0,o.hash])})),Du.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ku,witness:t.witness.slice(0,-1)}})),Du.prop(o,"input",(()=>{if(o.witness)return Ku})),Du.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Lu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Ku,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Du.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==ju.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Lu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Lu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Gu)||t.redeem.output&&(Lu.decompile(t.redeem.output)||[]).some(Gu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Gu)||(Lu.decompile(e)||[]).some(Gu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(es,"__esModule",{value:!0});const Wu=rs;es.embed=Wu.p2data;const Vu=Rs;es.p2ms=Vu.p2ms;const $u=qs;es.p2pk=$u.p2pk;const zu=zs;es.p2pkh=zu.p2pkh;const Xu=uu;es.p2sh=Xu.p2sh;const Yu=gu;es.p2wpkh=Yu.p2wpkh;const Ju=Bu;es.p2wsh=Ju.p2wsh,Object.defineProperty(Qo,"__esModule",{value:!0});const Zu=ts,Qu=es,ta=ns,ea=ss,ra=Iu,na=vt,ia=xo;function oa(t){const e=na.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function sa(t){const e=ra.decode(t),r=ra.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}Qo.fromBase58Check=oa,Qo.fromBech32=sa,Qo.toBase58Check=function(t,e){ia(ea.tuple(ea.Hash160bit,ea.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),na.encode(r)},Qo.toBech32=function(t,e,r){const n=ra.toWords(t);return n.unshift(e),ra.encode(r,n)},Qo.fromOutputScript=function(t,e){e=e||Zu.bitcoin;try{return Qu.p2pkh({output:t,network:e}).address}catch(t){}try{return Qu.p2sh({output:t,network:e}).address}catch(t){}try{return Qu.p2wpkh({output:t,network:e}).address}catch(t){}try{return Qu.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ta.toASM(t)+" has no matching Address")},Qo.toOutputScript=function(t,e){let r,n;e=e||Zu.bitcoin;try{r=oa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return Qu.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return Qu.p2sh({hash:r.hash}).output}else{try{n=sa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return Qu.p2wpkh({hash:n.data}).output;if(32===n.data.length)return Qu.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ua={},aa=u.randomBytes;Object.defineProperty(ua,"__esModule",{value:!0});const ha=ts,fa=ss,ca=xt.exports,la=aa,pa=xo,da=Co,ga=pa.maybe(pa.compile({compressed:fa.maybe(fa.Boolean),network:fa.maybe(fa.Network)}));class ya{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ha.bitcoin,void 0!==e&&(this.__Q=ca.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=ca.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return da.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return ca.sign(t,this.__D);{let e=ca.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=ca.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return ca.verify(t,this.publicKey,e)}}function va(t,e){if(pa(fa.Buffer256bit,t),!ca.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return pa(ga,e),new ya(t,void 0,e)}ua.fromPrivateKey=va,ua.fromPublicKey=function(t,e){return pa(ca.isPoint,t),pa(ga,e),new ya(void 0,t,e)},ua.fromWIF=function(t,e){const r=da.decode(t),n=r.version;if(fa.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ha.bitcoin,n!==e.wif)throw new Error("Invalid network version");return va(r.privateKey,{compressed:r.compressed,network:e})},ua.makeRandom=function(t){pa(ga,t),void 0===t&&(t={});const e=t.rng||la;let r;do{r=e(32),pa(fa.Buffer256bit,r)}while(!ca.isPrivate(r));return va(r,t)};var ma={},wa={},ba=h.exports.Buffer;function Ea(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function _a(t){return Ea(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Sa={encode:function t(e,r,n){if(Ea(e),r||(r=ba.allocUnsafe(_a(e))),!ba.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!ba.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ea(o),o},encodingLength:_a};Object.defineProperty(wa,"__esModule",{value:!0});const Ia=ss,Ta=xo,Oa=Sa;function Aa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Aa(n+r,9007199254740991),n+r}function Pa(t,e,r){return Aa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}wa.readUInt64LE=ka,wa.writeUInt64LE=Pa,wa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};wa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ta(Ia.tuple(Ia.Buffer,Ia.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Oa.decode(this.buffer,this.offset);return this.offset+=Oa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+La.encodingLength(this.ins.length)+La.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Da(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Da(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return La.encodingLength(e)+t.reduce(((t,e)=>t+Da(e)),0)}(e.witness)),0):0)}clone(){const t=new Wa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return Fa;const n=Na.compile(Na.decompile(e).filter((t=>t!==Ba.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Wa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Wa.SIGHASH_SINGLE){if(t>=this.outs.length)return Fa;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Wa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=Ha})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ra.hash256(o)}hashForWitnessV0(t,e,r,n){Ua(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=qa,u=qa,a=qa;if(n&Wa.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ra.hash256(o)),n&Wa.SIGHASH_ANYONECANPAY||(31&n)===Wa.SIGHASH_SINGLE||(31&n)===Wa.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ra.hash256(o)),(31&n)!==Wa.SIGHASH_SINGLE&&(31&n)!==Wa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Da(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ra.hash256(o)}else if((31&n)===Wa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Wa.DEFAULT_SEQUENCE=4294967295,Wa.SIGHASH_ALL=1,Wa.SIGHASH_NONE=2,Wa.SIGHASH_SINGLE=3,Wa.SIGHASH_ANYONECANPAY=128,Wa.ADVANCED_TRANSACTION_MARKER=0,Wa.ADVANCED_TRANSACTION_FLAG=1,Ma.Transaction=Wa;Object.defineProperty(ma,"__esModule",{value:!0});const Va=wa,$a=Xs,za=Ma,Xa=ss,Ya=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=za.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Ja([{getHash:Xa.Function}],t),0===t.length)throw Qa;if(e&&!rh(t))throw th;const r=t.map((t=>t.getHash(e))),n=Ya(r,$a.hash256);return e?$a.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!rh(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+Za.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return $a.hash256(this.toBuffer(!0))}getId(){return Va.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new Va.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(Za.encode(this.transactions.length,e,r.offset),r.offset+=Za.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=Va.reverseBuffer(this.getHash()),e=eh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw Qa;const t=eh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw Qa;if(!this.hasWitnessCommit())throw th;const t=eh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function rh(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ma.Block=eh;var nh={},ih={},oh={},sh={},uh={},ah={},hh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(hh);var fh={};Object.defineProperty(fh,"__esModule",{value:!0});const ch=hh;fh.decode=function(t){if(t.key[0]!==ch.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},fh.encode=function(t){const e=Buffer.from([ch.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},fh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",fh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},fh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=hh;lh.encode=function(t){return{key:Buffer.from([ph.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=hh;dh.decode=function(t){if(t.key[0]!==gh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},dh.encode=function(t){return{key:Buffer.from([gh.InputTypes.FINAL_SCRIPTSIG]),value:t}},dh.expected="Buffer",dh.check=function(t){return Buffer.isBuffer(t)},dh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var yh={};Object.defineProperty(yh,"__esModule",{value:!0});const vh=hh;yh.decode=function(t){if(t.key[0]!==vh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},yh.encode=function(t){return{key:Buffer.from([vh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},yh.expected="Buffer",yh.check=function(t){return Buffer.isBuffer(t)},yh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=hh;mh.decode=function(t){if(t.key[0]!==wh.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([wh.InputTypes.NON_WITNESS_UTXO]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=hh;bh.decode=function(t){if(t.key[0]!==Eh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},bh.encode=function(t){const e=Buffer.from([Eh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},bh.expected="{ pubkey: Buffer; signature: Buffer; }",bh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},bh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=hh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},_h.encode=function(t){return{key:Buffer.from([Sh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},_h.expected="string",_h.check=function(t){return"string"==typeof t},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=hh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Ih.encode=function(t){const e=Buffer.from([Th.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Ih.expected="number",Ih.check=function(t){return"number"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Oh={},Ah={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Ph(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Mh(t){return Ph(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Ph(e),r||(r=Buffer.allocUnsafe(Mh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Ph(i),i}},kh.encodingLength=Mh,Object.defineProperty(Ah,"__esModule",{value:!0});const xh=kh;function Rh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Nh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ah.range=t=>[...Array(t).keys()],Ah.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Dh={};Object.defineProperty(Dh,"__esModule",{value:!0}),Dh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var Hh={};Object.defineProperty(Hh,"__esModule",{value:!0}),Hh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(ah,"__esModule",{value:!0});const qh=hh,Fh=dh,Kh=yh,Gh=mh,Wh=bh,Vh=_h,$h=Ih,zh=Oh,Xh=Lh,Yh=Dh,Jh=Hh,Zh=jh,Qh={unsignedTx:lh,globalXpub:fh,checkPubkey:Yh.makeChecker([])};ah.globals=Qh;const tf={nonWitnessUtxo:Gh,partialSig:Wh,sighashType:$h,finalScriptSig:Fh,finalScriptWitness:Kh,porCommitment:Vh,witnessUtxo:zh,bip32Derivation:Xh.makeConverter(qh.InputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.InputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.InputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.InputTypes.PARTIAL_SIG,qh.InputTypes.BIP32_DERIVATION])};ah.inputs=tf;const ef={bip32Derivation:Xh.makeConverter(qh.OutputTypes.BIP32_DERIVATION),redeemScript:Jh.makeConverter(qh.OutputTypes.REDEEM_SCRIPT),witnessScript:Zh.makeConverter(qh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Yh.makeChecker([qh.OutputTypes.BIP32_DERIVATION])};ah.outputs=ef,Object.defineProperty(uh,"__esModule",{value:!0});const rf=ah,nf=Ah,of=kh,sf=hh;function uf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function af(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case sf.GlobalTypes.UNSIGNED_TX:if(uf("global",t.key,sf.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case sf.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(rf.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of nf.range(s)){const e={};for(const n of r[t])switch(rf.inputs.checkPubkey(n),n.key[0]){case sf.InputTypes.NON_WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=rf.inputs.nonWitnessUtxo.decode(n);break;case sf.InputTypes.WITNESS_UTXO:if(uf("input",n.key,sf.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=rf.inputs.witnessUtxo.decode(n);break;case sf.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(rf.inputs.partialSig.decode(n));break;case sf.InputTypes.SIGHASH_TYPE:if(uf("input",n.key,sf.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=rf.inputs.sighashType.decode(n);break;case sf.InputTypes.REDEEM_SCRIPT:if(uf("input",n.key,sf.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=rf.inputs.redeemScript.decode(n);break;case sf.InputTypes.WITNESS_SCRIPT:if(uf("input",n.key,sf.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=rf.inputs.witnessScript.decode(n);break;case sf.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.inputs.bip32Derivation.decode(n));break;case sf.InputTypes.FINAL_SCRIPTSIG:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=rf.inputs.finalScriptSig.decode(n);break;case sf.InputTypes.FINAL_SCRIPTWITNESS:uf("input",n.key,sf.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=rf.inputs.finalScriptWitness.decode(n);break;case sf.InputTypes.POR_COMMITMENT:uf("input",n.key,sf.InputTypes.POR_COMMITMENT),e.porCommitment=rf.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of nf.range(u)){const e={};for(const r of n[t])switch(rf.outputs.checkPubkey(r),r.key[0]){case sf.OutputTypes.REDEEM_SCRIPT:if(uf("output",r.key,sf.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=rf.outputs.redeemScript.decode(r);break;case sf.OutputTypes.WITNESS_SCRIPT:if(uf("output",r.key,sf.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=rf.outputs.witnessScript.decode(r);break;case sf.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(rf.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}uh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=of.decode(t,r);r+=of.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===sf.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of nf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of nf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return af(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},uh.checkKeyBuffer=uf,uh.psbtFromKeyVals=af;var hf={};Object.defineProperty(hf,"__esModule",{value:!0});const ff=ah,cf=Ah;hf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=df({globalMap:t,inputs:e,outputs:r}),s=cf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(cf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const lf=(t,e)=>t.key.compare(e.key);function pf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(lf)}function df({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:pf(t,ff.globals),inputKeyVals:e.map((t=>pf(t,ff.inputs))),outputKeyVals:r.map((t=>pf(t,ff.outputs)))}}hf.psbtToKeyVals=df,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(uh),e(hf)}(sh),Object.defineProperty(oh,"__esModule",{value:!0});const gf=sh;function yf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function vf(t){return t.globalMap.unsignedTx}function mf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}oh.combine=function(t){const e=t[0],r=gf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=vf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=mf(r.globalKeyVals),s=r.inputKeyVals.map(mf),u=r.outputKeyVals.map(mf);for(const t of n){const e=vf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=gf.psbtToKeyVals(t);mf(n.globalKeyVals).forEach(yf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(mf).forEach(((t,e)=>t.forEach(yf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return gf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var wf={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ah;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(wf),Object.defineProperty(ih,"__esModule",{value:!0});const bf=oh,Ef=sh,_f=hh,Sf=wf;ih.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Ef.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Ef.psbtToBuffer(this)}updateGlobal(t){return Sf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.updateInput(e,r),this}updateOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Sf.checkHasKey(t,this.globalMap.unknownKeyVals,Sf.getEnumLength(_f.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Sf.checkForInput(this.inputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Sf.checkForOutput(this.outputs,t);return Sf.checkHasKey(e,r.unknownKeyVals,Sf.getEnumLength(_f.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Sf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Sf.checkForInput(this.inputs,t);Sf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=bf.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(nh,"__esModule",{value:!0});const If=ih,Tf=kh,Of=wf,Af=Qo,kf=wa,Pf=Xs,Mf=ua,xf=es,Rf=ns,Nf=Ma,Bf={network:ts.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new If.Psbt(new Lf)){this.data=e,this.opts=Object.assign({},Bf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=If.Psbt.fromBuffer(t,Uf),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{Zf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Af.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Xf(t),this.opts.maximumFeeRate=t}setVersion(t){Xf(t),Yf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Xf(t),Yf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Xf(e),Yf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Yf(this.data.inputs,"addInput"),t.witnessScript&&gc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);Zf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&hc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Yf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Af.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(jf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return fc(this.data.inputs,r,e,!0),r}getFeeRate(){return rc("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return rc("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Of.checkForInput(this.data.inputs,0),mc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=nc){const r=Of.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=cc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Wf(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Rf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Of.checkForInput(this.data.inputs,t),r=dc(lc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Rf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||pc(r)||(n=r,Rf.isCanonicalScriptSignature(n)))return;var n;if(!Rf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=uc(t),r=e[e.length-1];if(pc(r))return;if(!Rf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+vc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=lc(r,e,n),{meaningfulScript:o}=dc(i,r,"input",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Of.checkForInput(this.data.inputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=dc(i,r,"output",e.redeemScript,e.witnessScript);return yc(t,o)}(e,Of.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Of.checkForOutput(this.data.outputs,t),n=zf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Of.checkForInput(this.data.inputs,0);return mc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Rf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?oc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Jf(e.pubkey,h,"verify");const f=Mf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of mc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return sc(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=sc(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Nf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of mc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Nf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Nf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Rf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Nf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=ic(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Rf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Df(this.__CACHE),this.data.toBuffer()}toHex(){return Df(this.__CACHE),this.data.toHex()}toBase64(){return Df(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&gc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&hc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}nh.Psbt=Cf;const Uf=t=>new Lf(t);class Lf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Nf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Df(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Hf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Mf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function jf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function qf(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Ff=qf(xf.p2ms),Kf=qf(xf.p2pk),Gf=qf(xf.p2pkh),Wf=qf(xf.p2wpkh),Vf=qf(xf.p2wsh),$f=qf(xf.p2sh);function zf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Xf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Yf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Rf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Rf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Rf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Rf.signature.decode(t.signature),i=[];n&Nf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Nf.Transaction.SIGHASH_ALL:break;case Nf.Transaction.SIGHASH_SINGLE:case Nf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Jf(t,e,r){if(!yc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function Zf(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function Qf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const tc=Qf(xf.p2sh,"Redeem script"),ec=Qf(xf.p2wsh,"Witness script");function rc(t,e,r,n){if(!r.every(jf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),fc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function nc(t,e,r,n,i,o){const s=vc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Hf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return Hf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=ac(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function ic(t,e,r,n,i){const o=Of.checkForInput(t,e),{hash:s,sighashType:u,script:a}=oc(e,o,n,!1,i);return Jf(r,a,"sign"),{hash:s,sighashType:u}}function oc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Nf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Nf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Nf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Nf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Nf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=cc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=dc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Wf(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function sc(t,e,r){const n=Of.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function uc(t){let e=0;function r(){const r=Tf.decode(t,e);return e+=Tf.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=uc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=cc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function cc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||hc(t,e,r),n[r]}function lc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return cc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function pc(t){return 33===t.length&&Rf.isCanonicalPubKey(t)}function dc(t,e,r,n,i){const o=$f(t),s=o&&n&&Vf(n),u=Vf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,tc(e,t,n,r),ec(e,n,i,r),gc(a)):u?(a=i,ec(e,t,i,r),gc(a)):o?(a=n,tc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function gc(t){if(Wf(t)||$f(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function yc(t,e){const r=Pf.hash160(t),n=Rf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function vc(t){return Wf(t)?"witnesspubkeyhash":Gf(t)?"pubkeyhash":Ff(t)?"multisig":Kf(t)?"pubkey":"nonstandard"}function mc(t){return[...Array(t).keys()]}var wc={},bc={},Ec={},_c={};Object.defineProperty(_c,"__esModule",{value:!0});const Sc=ns,Ic=ns;function Tc(t){return t===Ic.OPS.OP_0||Sc.isCanonicalScriptSignature(t)}function Oc(t,e){const r=Sc.decompile(t);return!(r.length<2)&&(r[0]===Ic.OPS.OP_0&&(e?r.slice(1).every(Tc):r.slice(1).every(Sc.isCanonicalScriptSignature)))}_c.check=Oc,Oc.toJSON=()=>"multisig input";var Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const kc=ns,Pc=ns,Mc=ss,xc=Pc.OPS.OP_RESERVED;function Rc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Pc.OPS.OP_CHECKMULTISIG)return!1;if(!Mc.Number(r[0]))return!1;if(!Mc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Ac.check=Rc,Rc.toJSON=()=>"multi-sig output",Object.defineProperty(Ec,"__esModule",{value:!0});const Nc=_c;Ec.input=Nc;const Bc=Ac;Ec.output=Bc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Uc=ns,Lc=Uc.OPS;function Dc(t){const e=Uc.compile(t);return e.length>1&&e[0]===Lc.OP_RETURN}Cc.check=Dc,Dc.toJSON=()=>"null data output";const Hc={check:Dc};Cc.output=Hc;var jc={},qc={};Object.defineProperty(qc,"__esModule",{value:!0});const Fc=ns;function Kc(t){const e=Fc.decompile(t);return 1===e.length&&Fc.isCanonicalScriptSignature(e[0])}qc.check=Kc,Kc.toJSON=()=>"pubKey input";var Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});const Wc=ns,Vc=ns;function $c(t){const e=Wc.decompile(t);return 2===e.length&&Wc.isCanonicalPubKey(e[0])&&e[1]===Vc.OPS.OP_CHECKSIG}Gc.check=$c,$c.toJSON=()=>"pubKey output",Object.defineProperty(jc,"__esModule",{value:!0});const zc=qc;jc.input=zc;const Xc=Gc;jc.output=Xc;var Yc={},Jc={};Object.defineProperty(Jc,"__esModule",{value:!0});const Zc=ns;function Qc(t){const e=Zc.decompile(t);return 2===e.length&&Zc.isCanonicalScriptSignature(e[0])&&Zc.isCanonicalPubKey(e[1])}Jc.check=Qc,Qc.toJSON=()=>"pubKeyHash input";var tl={};Object.defineProperty(tl,"__esModule",{value:!0});const el=ns,rl=ns;function nl(t){const e=el.compile(t);return 25===e.length&&e[0]===rl.OPS.OP_DUP&&e[1]===rl.OPS.OP_HASH160&&20===e[2]&&e[23]===rl.OPS.OP_EQUALVERIFY&&e[24]===rl.OPS.OP_CHECKSIG}tl.check=nl,nl.toJSON=()=>"pubKeyHash output",Object.defineProperty(Yc,"__esModule",{value:!0});const il=Jc;Yc.input=il;const ol=tl;Yc.output=ol;var sl={},ul={},al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=ns,fl=ns;function cl(t){const e=hl.compile(t);return 22===e.length&&e[0]===fl.OPS.OP_0&&20===e[1]}al.check=cl,cl.toJSON=()=>"Witness pubKeyHash output";var ll={};Object.defineProperty(ll,"__esModule",{value:!0});const pl=ns,dl=ns;function gl(t){const e=pl.compile(t);return 34===e.length&&e[0]===dl.OPS.OP_0&&32===e[1]}ll.check=gl,gl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(ul,"__esModule",{value:!0});const yl=ns,vl=Ec,ml=jc,wl=Yc,bl=al,El=ll;function _l(t,e){const r=yl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=yl.decompile(yl.compile(r.slice(0,-1))),o=yl.decompile(n);return!!o&&(!!yl.isPushOnly(i)&&(1===r.length?El.check(o)||bl.check(o):!(!wl.input.check(i)||!wl.output.check(o))||(!(!vl.input.check(i,e)||!vl.output.check(o))||!(!ml.input.check(i)||!ml.output.check(o)))))}ul.check=_l,_l.toJSON=()=>"scriptHash input";var Sl={};Object.defineProperty(Sl,"__esModule",{value:!0});const Il=ns,Tl=ns;function Ol(t){const e=Il.compile(t);return 23===e.length&&e[0]===Tl.OPS.OP_HASH160&&20===e[1]&&e[22]===Tl.OPS.OP_EQUAL}Sl.check=Ol,Ol.toJSON=()=>"scriptHash output",Object.defineProperty(sl,"__esModule",{value:!0});const Al=ul;sl.input=Al;const kl=Sl;sl.output=kl;var Pl={},Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const xl=ns,Rl=ns,Nl=ss,Bl=xo,Cl=Buffer.from("aa21a9ed","hex");function Ul(t){const e=xl.compile(t);return e.length>37&&e[0]===Rl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Ml.check=Ul,Ul.toJSON=()=>"Witness commitment output",Ml.encode=function(t){Bl(Nl.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Rl.OPS.OP_RETURN,e])},Ml.decode=function(t){return Bl(Ul,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Pl,"__esModule",{value:!0});const Ll=Ml;Pl.output=Ll;var Dl={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});const jl=ns;function ql(t){const e=jl.decompile(t);return 2===e.length&&jl.isCanonicalScriptSignature(e[0])&&function(t){return jl.isCanonicalPubKey(t)&&33===t.length}(e[1])}Hl.check=ql,ql.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Dl,"__esModule",{value:!0});const Fl=Hl;Dl.input=Fl;const Kl=al;Dl.output=Kl;var Gl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Vl=ns,$l=xo,zl=Ec,Xl=jc,Yl=Yc;function Jl(t,e){if($l($l.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=Vl.decompile(r);if(!n||0===n.length)return!1;const i=Vl.compile(t.slice(0,-1));return!(!Yl.input.check(i)||!Yl.output.check(n))||(!(!zl.input.check(i,e)||!zl.output.check(n))||!(!Xl.input.check(i)||!Xl.output.check(n)))}Wl.check=Jl,Jl.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Gl,"__esModule",{value:!0});const Zl=Wl;Gl.input=Zl;const Ql=ll;Gl.output=Ql,Object.defineProperty(bc,"__esModule",{value:!0});const tp=ns,ep=Ec,rp=Cc,np=jc,ip=Yc,op=sl,sp=Pl,up=Dl,ap=Gl,hp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};bc.types=hp,bc.output=function(t){if(up.output.check(t))return hp.P2WPKH;if(ap.output.check(t))return hp.P2WSH;if(ip.output.check(t))return hp.P2PKH;if(op.output.check(t))return hp.P2SH;const e=tp.decompile(t);if(!e)throw new TypeError("Invalid script");return ep.output.check(e)?hp.P2MS:np.output.check(e)?hp.P2PK:sp.output.check(e)?hp.WITNESS_COMMITMENT:rp.output.check(e)?hp.NULLDATA:hp.NONSTANDARD},bc.input=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return ip.input.check(r)?hp.P2PKH:op.input.check(r,e)?hp.P2SH:ep.input.check(r,e)?hp.P2MS:np.input.check(r)?hp.P2PK:hp.NONSTANDARD},bc.witness=function(t,e){const r=tp.decompile(t);if(!r)throw new TypeError("Invalid script");return up.input.check(r)?hp.P2WPKH:ap.input.check(r,e)?hp.P2WSH:hp.NONSTANDARD},Object.defineProperty(wc,"__esModule",{value:!0});const fp=Qo,cp=wa,lp=bc,pp=Xs,dp=ua,gp=ts,yp=es,vp=ns,mp=ns,wp=Ma,bp=ss,Ep=xo,_p=lp.types,Sp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Ip(t,e,r){try{Ep(t,e)}catch(t){throw new Error(r)}}class Tp{constructor(t=gp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new wp.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Tp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==_p.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=dp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=vp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Ep(Ep.maybe(Ep.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Ep(bp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Ep(bp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=cp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof wp.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=fp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=vp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Sp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Ip(Ep.Number,e.vin,"sign must include vin parameter as Number (input index)"),Ip(bp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Ip(Ep.maybe(Ep.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires redeemScript`),Ip(Ep.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Ip(Ep.Buffer,e.witnessScript,`${n} requires witnessScript`),Ip(Ep.Buffer,e.redeemScript,`${n} requires witnessScript`),Ip(bp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||wp.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Pp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Ep(bp.Satoshi,a),l.value=a}if(!Pp(l)){const t=function(t,e,r,n){if(r&&n){const i=yp.p2wsh({redeem:{output:n}}),o=yp.p2wsh({output:r}),s=yp.p2sh({redeem:{output:r}}),u=yp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Ap(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===_p.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:_p.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:_p.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=yp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=yp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Ap(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+vp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===_p.P2WPKH&&(o=yp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:_p.P2SH,prevOutScript:n.output,hasWitness:i.type===_p.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=yp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=yp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Ap(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+vp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===_p.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:_p.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===_p.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===_p.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Ap(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+vp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===_p.P2WPKH&&(n=yp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===_p.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=yp.p2pkh({pubkey:e}).output;return{prevOutType:_p.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:_p.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Pp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(wp.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Op(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Ap(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||lp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===_p.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Mp(t)&wp.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===wp.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Mp(t)&wp.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Mp(r);return n===wp.Transaction.SIGHASH_NONE||n===wp.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Op(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=lp.input(t,!0),i=lp.witness(e,!0);n===_p.NONSTANDARD&&(n=void 0),i===_p.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case _p.P2WPKH:{const{output:t,pubkey:r,signature:n}=yp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:_p.P2WPKH,pubkeys:[r],signatures:[n]}}case _p.P2PKH:{const{output:e,pubkey:r,signature:n}=yp.p2pkh({input:t});return{prevOutScript:e,prevOutType:_p.P2PKH,pubkeys:[r],signatures:[n]}}case _p.P2PK:{const{signature:e}=yp.p2pk({input:t});return{prevOutType:_p.P2PK,pubkeys:[void 0],signatures:[e]}}case _p.P2MS:{const{m:e,pubkeys:r,signatures:i}=yp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:_p.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===_p.P2SH){const{output:r,redeem:n}=yp.p2sh({input:t,witness:e}),i=lp.output(n.output),o=Op(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:_p.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===_p.P2WSH){const{output:r,redeem:n}=yp.p2wsh({input:t,witness:e}),i=lp.output(n.output);let o;return o=i===_p.P2WPKH?Op(n.input,n.witness,i):Op(vp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:_p.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:_p.NONSTANDARD,prevOutScript:t}}function Ap(t,e){Ep(bp.Buffer,t);const r=lp.output(t);switch(r){case _p.P2PKH:{if(!e)return{type:r};const n=yp.p2pkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2WPKH:{if(!e)return{type:r};const n=yp.p2wpkh({output:t}).hash,i=pp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case _p.P2PK:return{type:r,pubkeys:[yp.p2pk({output:t}).pubkey],signatures:[void 0]};case _p.P2MS:{const e=yp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case _p.P2PKH:if(0===n.length)break;if(0===i.length)break;return yp.p2pkh({pubkey:n[0],signature:i[0]});case _p.P2WPKH:if(0===n.length)break;if(0===i.length)break;return yp.p2wpkh({pubkey:n[0],signature:i[0]});case _p.P2PK:if(0===n.length)break;if(0===i.length)break;return yp.p2pk({signature:i[0]});case _p.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||mp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return yp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case _p.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return yp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case _p.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return yp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Pp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Mp(t){return t.readUInt8(t.length-1)}wc.TransactionBuilder=Tp,Object.defineProperty(It,"__esModule",{value:!0});const xp=Tt;It.bip32=xp;const Rp=Qo;It.address=Rp;const Np=Xs;var Bp=It.crypto=Np;const Cp=ua;It.ECPair=Cp;const Up=ts;It.networks=Up;const Lp=es;It.payments=Lp;const Dp=ns;It.script=Dp;var Hp=ma;It.Block=Hp.Block;var jp=nh;It.Psbt=jp.Psbt;var qp=ns;It.opcodes=qp.OPS;var Fp=Ma;It.Transaction=Fp.Transaction;var Kp=wc;It.TransactionBuilder=Kp.TransactionBuilder;var Gp={exports:{}};var Wp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var Vp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Wp,n=Vp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Gp,Gp.exports);const $p=["includePrerelease","loose","rtl"];var zp=t=>t?"object"!=typeof t?{loose:!0}:$p.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Xp=/^[0-9]+$/,Yp=(t,e)=>{const r=Xp.test(t),n=Xp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tYp(e,t)};const Zp=Vp,{MAX_LENGTH:Qp,MAX_SAFE_INTEGER:td}=Wp,{re:ed,t:rd}=Gp.exports,nd=zp,{compareIdentifiers:id}=Jp;class od{constructor(t,e){if(e=nd(e),t instanceof od){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Qp)throw new TypeError(`version is longer than ${Qp} characters`);Zp("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?ed[rd.LOOSE]:ed[rd.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>td||this.major<0)throw new TypeError("Invalid major version");if(this.minor>td||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>td||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var sd=od;const{MAX_LENGTH:ud}=Wp,{re:ad,t:hd}=Gp.exports,fd=sd,cd=zp;var ld=(t,e)=>{if(e=cd(e),t instanceof fd)return t;if("string"!=typeof t)return null;if(t.length>ud)return null;if(!(e.loose?ad[hd.LOOSE]:ad[hd.FULL]).test(t))return null;try{return new fd(t,e)}catch(t){return null}};const pd=ld;var dd=(t,e)=>{const r=pd(t,e);return r?r.version:null};const gd=ld;var yd=(t,e)=>{const r=gd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const vd=sd;var md=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new vd(t,r).inc(e,n).version}catch(t){return null}};const wd=sd;var bd=(t,e,r)=>new wd(t,r).compare(new wd(e,r));const Ed=bd;var _d=(t,e,r)=>0===Ed(t,e,r);const Sd=ld,Id=_d;var Td=(t,e)=>{if(Id(t,e))return null;{const r=Sd(t),n=Sd(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Od=sd;var Ad=(t,e)=>new Od(t,e).major;const kd=sd;var Pd=(t,e)=>new kd(t,e).minor;const Md=sd;var xd=(t,e)=>new Md(t,e).patch;const Rd=ld;var Nd=(t,e)=>{const r=Rd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Bd=bd;var Cd=(t,e,r)=>Bd(e,t,r);const Ud=bd;var Ld=(t,e)=>Ud(t,e,!0);const Dd=sd;var Hd=(t,e,r)=>{const n=new Dd(t,r),i=new Dd(e,r);return n.compare(i)||n.compareBuild(i)};const jd=Hd;var qd=(t,e)=>t.sort(((t,r)=>jd(t,r,e)));const Fd=Hd;var Kd=(t,e)=>t.sort(((t,r)=>Fd(r,t,e)));const Gd=bd;var Wd=(t,e,r)=>Gd(t,e,r)>0;const Vd=bd;var $d=(t,e,r)=>Vd(t,e,r)<0;const zd=bd;var Xd=(t,e,r)=>0!==zd(t,e,r);const Yd=bd;var Jd=(t,e,r)=>Yd(t,e,r)>=0;const Zd=bd;var Qd=(t,e,r)=>Zd(t,e,r)<=0;const tg=_d,eg=Xd,rg=Wd,ng=Jd,ig=$d,og=Qd;var sg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return tg(t,r,n);case"!=":return eg(t,r,n);case">":return rg(t,r,n);case">=":return ng(t,r,n);case"<":return ig(t,r,n);case"<=":return og(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const ug=sd,ag=ld,{re:hg,t:fg}=Gp.exports;var cg=(t,e)=>{if(t instanceof ug)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=hg[fg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),hg[fg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;hg[fg.COERCERTL].lastIndex=-1}else r=t.match(hg[fg.COERCE]);return null===r?null:ag(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},lg=pg;function pg(t){var e=this;if(e instanceof pg||(e=new pg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},pg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},pg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},pg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},pg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new pg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},pg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Mg=(t,e,r)=>{const n=t[Ag].get(e);if(n){const e=n.value;if(xg(t,e)){if(Ng(t,n),!t[_g])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Og].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Sg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Sg]&&r>t[Sg]},Rg=t=>{if(t[bg]>t[wg])for(let e=t[Og].tail;t[bg]>t[wg]&&null!==e;){const r=e.prev;Ng(t,e),e=r}},Ng=(t,e)=>{if(e){const r=e.value;t[Ig]&&t[Ig](r.key,r.value),t[bg]-=r.length,t[Ag].delete(r.key),t[Og].removeNode(e)}};class Bg{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Ng(t,r),t[_g]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Ug=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[wg]=t.max||1/0;const e=t.length||Pg;if(this[Eg]="function"!=typeof e?Pg:e,this[_g]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Sg]=t.maxAge||0,this[Ig]=t.dispose,this[Tg]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[wg]=t||1/0,Rg(this)}get max(){return this[wg]}set allowStale(t){this[_g]=!!t}get allowStale(){return this[_g]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Sg]=t,Rg(this)}get maxAge(){return this[Sg]}set lengthCalculator(t){"function"!=typeof t&&(t=Pg),t!==this[Eg]&&(this[Eg]=t,this[bg]=0,this[Og].forEach((t=>{t.length=this[Eg](t.value,t.key),this[bg]+=t.length}))),Rg(this)}get lengthCalculator(){return this[Eg]}get length(){return this[bg]}get itemCount(){return this[Og].length}rforEach(t,e){e=e||this;for(let r=this[Og].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Og].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Og].toArray().map((t=>t.key))}values(){return this[Og].toArray().map((t=>t.value))}reset(){this[Ig]&&this[Og]&&this[Og].length&&this[Og].forEach((t=>this[Ig](t.key,t.value))),this[Ag]=new Map,this[Og]=new mg,this[bg]=0}dump(){return this[Og].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Og]}set(t,e,r){if((r=r||this[Sg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Eg](e,t);if(this[Ag].has(t)){if(i>this[wg])return Ng(this,this[Ag].get(t)),!1;const o=this[Ag].get(t).value;return this[Ig]&&(this[Tg]||this[Ig](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[bg]+=i-o.length,o.length=i,this.get(t),Rg(this),!0}const o=new Bg(t,e,i,n,r);return o.length>this[wg]?(this[Ig]&&this[Ig](t,e),!1):(this[bg]+=o.length,this[Og].unshift(o),this[Ag].set(t,this[Og].head),Rg(this),!0)}has(t){if(!this[Ag].has(t))return!1;const e=this[Ag].get(t).value;return!xg(this,e)}get(t){return Mg(this,t,!0)}peek(t){return Mg(this,t,!1)}pop(){const t=this[Og].tail;return t?(Ng(this,t),t.value):null}del(t){Ng(this,this[Ag].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Ag].forEach(((t,e)=>Mg(this,e,!1)))}};class Lg{constructor(t,e){if(e=jg(e),t instanceof Lg)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Lg(t.raw,e);if(t instanceof qg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Xg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Yg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=Hg.get(e);if(r)return r;const n=this.options.loose,i=n?Gg[Wg.HYPHENRANGELOOSE]:Gg[Wg.HYPHENRANGE];t=t.replace(i,ay(this.options.includePrerelease)),Fg("hyphen replace",t),t=t.replace(Gg[Wg.COMPARATORTRIM],Vg),Fg("comparator trim",t,Gg[Wg.COMPARATORTRIM]),t=(t=(t=t.replace(Gg[Wg.TILDETRIM],$g)).replace(Gg[Wg.CARETTRIM],zg)).split(/\s+/).join(" ");const o=n?Gg[Wg.COMPARATORLOOSE]:Gg[Wg.COMPARATOR],s=t.split(" ").map((t=>Zg(t,this.options))).join(" ").split(/\s+/).map((t=>uy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new qg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Xg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return Hg.set(e,a),a}intersects(t,e){if(!(t instanceof Lg))throw new TypeError("a Range is required");return this.set.some((r=>Jg(r,e)&&t.set.some((t=>Jg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Kg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Yg=t=>""===t.value,Jg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},Zg=(t,e)=>(Fg("comp",t,e),t=ry(t,e),Fg("caret",t),t=ty(t,e),Fg("tildes",t),t=iy(t,e),Fg("xrange",t),t=sy(t,e),Fg("stars",t),t),Qg=t=>!t||"x"===t.toLowerCase()||"*"===t,ty=(t,e)=>t.trim().split(/\s+/).map((t=>ey(t,e))).join(" "),ey=(t,e)=>{const r=e.loose?Gg[Wg.TILDELOOSE]:Gg[Wg.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Fg("tilde",t,e,r,n,i,o),Qg(r)?s="":Qg(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Qg(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Fg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Fg("tilde return",s),s}))},ry=(t,e)=>t.trim().split(/\s+/).map((t=>ny(t,e))).join(" "),ny=(t,e)=>{Fg("caret",t,e);const r=e.loose?Gg[Wg.CARETLOOSE]:Gg[Wg.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Fg("caret",t,e,r,i,o,s),Qg(r)?u="":Qg(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Qg(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Fg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Fg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Fg("caret return",u),u}))},iy=(t,e)=>(Fg("replaceXRanges",t,e),t.split(/\s+/).map((t=>oy(t,e))).join(" ")),oy=(t,e)=>{t=t.trim();const r=e.loose?Gg[Wg.XRANGELOOSE]:Gg[Wg.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Fg("xRange",t,r,n,i,o,s,u);const a=Qg(i),h=a||Qg(o),f=h||Qg(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Fg("xRange return",r),r}))},sy=(t,e)=>(Fg("replaceStars",t,e),t.trim().replace(Gg[Wg.STAR],"")),uy=(t,e)=>(Fg("replaceGTE0",t,e),t.trim().replace(Gg[e.includePrerelease?Wg.GTE0PRE:Wg.GTE0],"")),ay=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=Qg(n)?"":Qg(i)?`>=${n}.0.0${t?"-0":""}`:Qg(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Qg(h)?"":Qg(f)?`<${+h+1}.0.0-0`:Qg(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),hy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},fy=Symbol("SemVer ANY");class cy{static get ANY(){return fy}constructor(t,e){if(e=py(e),t instanceof cy){if(t.loose===!!e.loose)return t;t=t.value}vy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===fy?this.value="":this.value=this.operator+this.semver.version,vy("comp",this)}parse(t){const e=this.options.loose?dy[gy.COMPARATORLOOSE]:dy[gy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new my(r[2],this.options.loose):this.semver=fy}toString(){return this.value}test(t){if(vy("Comparator.test",t,this.options.loose),this.semver===fy||t===fy)return!0;if("string"==typeof t)try{t=new my(t,this.options)}catch(t){return!1}return yy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof cy))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new wy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new wy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=yy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=yy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var ly=cy;const py=zp,{re:dy,t:gy}=Gp.exports,yy=sg,vy=Vp,my=sd,wy=Dg,by=Dg;var Ey=(t,e,r)=>{try{e=new by(e,r)}catch(t){return!1}return e.test(t)};const _y=Dg;var Sy=(t,e)=>new _y(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Iy=sd,Ty=Dg;var Oy=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Ty(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Iy(n,r)))})),n};const Ay=sd,ky=Dg;var Py=(t,e,r)=>{let n=null,i=null,o=null;try{o=new ky(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Ay(n,r)))})),n};const My=sd,xy=Dg,Ry=Wd;var Ny=(t,e)=>{t=new xy(t,e);let r=new My("0.0.0");if(t.test(r))return r;if(r=new My("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new My(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Ry(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Ry(r,i)||(r=i)}return r&&t.test(r)?r:null};const By=Dg;var Cy=(t,e)=>{try{return new By(t,e).range||"*"}catch(t){return null}};const Uy=sd,Ly=ly,{ANY:Dy}=Ly,Hy=Dg,jy=Ey,qy=Wd,Fy=$d,Ky=Qd,Gy=Jd;var Wy=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Uy(t,n),e=new Hy(e,n),r){case">":i=qy,o=Ky,s=Fy,u=">",a=">=";break;case"<":i=Fy,o=Gy,s=qy,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(jy(t,e,n))return!1;for(let r=0;r{t.semver===Dy&&(t=new Ly(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const Vy=Wy;var $y=(t,e,r)=>Vy(t,e,">",r);const zy=Wy;var Xy=(t,e,r)=>zy(t,e,"<",r);const Yy=Dg;var Jy=(t,e,r)=>(t=new Yy(t,r),e=new Yy(e,r),t.intersects(e));const Zy=Ey,Qy=bd;const tv=Dg,ev=ly,{ANY:rv}=ev,nv=Ey,iv=bd,ov=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===rv){if(1===e.length&&e[0].semver===rv)return!0;t=r.includePrerelease?[new ev(">=0.0.0-0")]:[new ev(">=0.0.0")]}if(1===e.length&&e[0].semver===rv){if(r.includePrerelease)return!0;e=[new ev(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=sv(i,e,r):"<"===e.operator||"<="===e.operator?o=uv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=iv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!nv(t,String(i),r))return null;if(o&&!nv(t,String(o),r))return null;for(const n of e)if(!nv(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=sv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!nv(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=uv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!nv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},sv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},uv=(t,e,r)=>{if(!t)return e;const n=iv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var av=(t,e,r={})=>{if(t===e)return!0;t=new tv(t,r),e=new tv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=ov(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const hv=Gp.exports;var fv={re:hv.re,src:hv.src,tokens:hv.t,SEMVER_SPEC_VERSION:Wp.SEMVER_SPEC_VERSION,SemVer:sd,compareIdentifiers:Jp.compareIdentifiers,rcompareIdentifiers:Jp.rcompareIdentifiers,parse:ld,valid:dd,clean:yd,inc:md,diff:Td,major:Ad,minor:Pd,patch:xd,prerelease:Nd,compare:bd,rcompare:Cd,compareLoose:Ld,compareBuild:Hd,sort:qd,rsort:Kd,gt:Wd,lt:$d,eq:_d,neq:Xd,gte:Jd,lte:Qd,cmp:sg,coerce:cg,Comparator:ly,Range:Dg,satisfies:Ey,toComparators:Sy,maxSatisfying:Oy,minSatisfying:Py,minVersion:Ny,validRange:Cy,outside:Wy,gtr:$y,ltr:Xy,intersects:Jy,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Qy(t,e,r)));for(const t of s){Zy(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Tv(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ov(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Av(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}yv.prototype=Object.create(null),vv.EventEmitter=vv,vv.usingDomains=!1,vv.prototype.domain=void 0,vv.prototype._events=void 0,vv.prototype._maxListeners=void 0,vv.defaultMaxListeners=10,vv.init=function(){this.domain=null,vv.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new yv,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},vv.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},vv.prototype.getMaxListeners=function(){return mv(this)},vv.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:wv(r,f,this);break;case 2:bv(r,f,this,arguments[1]);break;case 3:Ev(r,f,this,arguments[1],arguments[2]);break;case 4:_v(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new yv,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var kv=Object.freeze({__proto__:null,default:vv,EventEmitter:vv});function Pv(){throw new Error("setTimeout has not been defined")}function Mv(){throw new Error("clearTimeout has not been defined")}var xv=Pv,Rv=Mv;function Nv(t){if(xv===setTimeout)return setTimeout(t,0);if((xv===Pv||!xv)&&setTimeout)return xv=setTimeout,setTimeout(t,0);try{return xv(t,0)}catch(e){try{return xv.call(null,t,0)}catch(e){return xv.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xv=setTimeout),"function"==typeof global.clearTimeout&&(Rv=clearTimeout);var Bv,Cv=[],Uv=!1,Lv=-1;function Dv(){Uv&&Bv&&(Uv=!1,Bv.length?Cv=Bv.concat(Cv):Lv=-1,Cv.length&&Hv())}function Hv(){if(!Uv){var t=Nv(Dv);Uv=!0;for(var e=Cv.length;e;){for(Bv=Cv,Cv=[];++Lv1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),nm(e)?r.showHidden=e:e&&_m(r,e),hm(r.showHidden)&&(r.showHidden=!1),hm(r.depth)&&(r.depth=2),hm(r.colors)&&(r.colors=!1),hm(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Jv),Qv(r,t,r.depth)}function Jv(t,e){var r=Yv.styles[e];return r?"["+Yv.colors[r][0]+"m"+t+"["+Yv.colors[r][1]+"m":t}function Zv(t,e){return t}function Qv(t,e,r){if(t.customInspect&&e&&dm(e.inspect)&&e.inspect!==Yv&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return um(n)||(n=Qv(t,n,r)),n}var i=function(t,e){if(hm(e))return t.stylize("undefined","undefined");if(um(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(sm(e))return t.stylize(""+e,"number");if(nm(e))return t.stylize(""+e,"boolean");if(im(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),pm(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return tm(e);if(0===o.length){if(dm(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(fm(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(lm(e))return t.stylize(Date.prototype.toString.call(e),"date");if(pm(e))return tm(e)}var a,h="",f=!1,c=["{","}"];(rm(e)&&(f=!0,c=["[","]"]),dm(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return fm(e)&&(h=" "+RegExp.prototype.toString.call(e)),lm(e)&&(h=" "+Date.prototype.toUTCString.call(e)),pm(e)&&(h=" "+tm(e)),0!==o.length||f&&0!=e.length?r<0?fm(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function tm(t){return"["+Error.prototype.toString.call(t)+"]"}function em(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Sm(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=im(r)?Qv(t,a.value,null):Qv(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),hm(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function rm(t){return Array.isArray(t)}function nm(t){return"boolean"==typeof t}function im(t){return null===t}function om(t){return null==t}function sm(t){return"number"==typeof t}function um(t){return"string"==typeof t}function am(t){return"symbol"==typeof t}function hm(t){return void 0===t}function fm(t){return cm(t)&&"[object RegExp]"===vm(t)}function cm(t){return"object"==typeof t&&null!==t}function lm(t){return cm(t)&&"[object Date]"===vm(t)}function pm(t){return cm(t)&&("[object Error]"===vm(t)||t instanceof Error)}function dm(t){return"function"==typeof t}function gm(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function ym(t){return Buffer.isBuffer(t)}function vm(t){return Object.prototype.toString.call(t)}function mm(t){return t<10?"0"+t.toString(10):t.toString(10)}Yv.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]},Yv.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var wm=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bm(){var t=new Date,e=[mm(t.getHours()),mm(t.getMinutes()),mm(t.getSeconds())].join(":");return[t.getDate(),wm[t.getMonth()],e].join(" ")}function Em(){console.log("%s - %s",bm(),Wv.apply(null,arguments))}function _m(t,e){if(!e||!cm(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Sm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Im={inherits:Kv,_extend:_m,log:Em,isBuffer:ym,isPrimitive:gm,isFunction:dm,isError:pm,isDate:lm,isObject:cm,isRegExp:fm,isUndefined:hm,isSymbol:am,isString:um,isNumber:sm,isNullOrUndefined:om,isNull:im,isBoolean:nm,isArray:rm,inspect:Yv,deprecate:Vv,format:Wv,debuglog:Xv},Tm=Object.freeze({__proto__:null,format:Wv,deprecate:Vv,debuglog:Xv,inspect:Yv,isArray:rm,isBoolean:nm,isNull:im,isNullOrUndefined:om,isNumber:sm,isString:um,isSymbol:am,isUndefined:hm,isRegExp:fm,isObject:cm,isDate:lm,isError:pm,isFunction:dm,isPrimitive:gm,isBuffer:ym,log:Em,inherits:Kv,_extend:_m,default:Im});function Om(){this.head=null,this.tail=null,this.length=0}Om.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Om.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Om.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Om.prototype.clear=function(){this.head=this.tail=null,this.length=0},Om.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Om.prototype.concat=function(t){if(0===this.length)return I.alloc(0);if(1===this.length)return this.head.data;for(var e=I.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Am=I.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function km(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Am(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Mm;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xm;break;default:return void(this.write=Pm)}this.charBuffer=new I(6),this.charReceived=0,this.charLength=0}function Pm(t){return t.toString(this.encoding)}function Mm(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xm(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}km.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},km.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},km.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e},Bm.ReadableState=Nm;var Rm=Xv("stream");function Nm(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof aw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Om,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new km(t.encoding),this.encoding=t.encoding)}function Bm(t){if(!(this instanceof Bm))return new Bm(t);this._readableState=new Nm(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),vv.call(this)}function Cm(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,Dm(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&Dm(t))),function(t,e){e.readingMore||(e.readingMore=!0,jv(jm,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Um?t=Um:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function Dm(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Rm("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?jv(Hm,t):Hm(t))}function Hm(t){Rm("emit readable"),t.emit("readable"),Km(t)}function jm(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function Wm(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,jv(Vm,e,t))}function Vm(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function $m(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Rm("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Wm(this):Dm(this),null;if(0===(t=Lm(t,e))&&e.ended)return 0===e.length&&Wm(this),null;var n,i=e.needReadable;return Rm("need readable",i),(0===e.length||e.length-t0?Gm(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Wm(this)),null!==n&&this.emit("data",n),n},Bm.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Bm.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Rm("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Rm("onunpipe"),t===r&&h()}function s(){Rm("onend"),t.end()}n.endEmitted?jv(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Rm("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Km(t))}}(r);t.on("drain",u);var a=!1;function h(){Rm("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Rm("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==$m(n.pipes,t))&&!a&&(Rm("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Rm("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Rm("onfinish"),t.removeListener("close",p),g()}function g(){Rm("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Rm("pipe resume"),r.resume()),t},Bm.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},Jm.prototype._write=function(t,e,r){r(new Error("not implemented"))},Jm.prototype._writev=null,Jm.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,nw(t,e),r&&(e.finished?jv(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Kv(aw,Bm);for(var ow=Object.keys(Jm.prototype),sw=0;sw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Sw.alloc(0);for(var e=Sw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Ow(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Sw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Tw,value:function(t,e){return Iw(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Bw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Bw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Cw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Cw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Bw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Bw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Bw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Bw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Bw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Bw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Bw("ERR_STREAM_WRITE_AFTER_END","write after end"),Bw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Bw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Bw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Rw.codes=Nw;var Uw=Rw.codes.ERR_INVALID_OPT_VALUE;var Lw,Dw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Uw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},Hw=ww.deprecate,jw=ub;function qw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}ub.WritableState=sb;var Fw={deprecate:Hw},Kw=mw,Gw=ht.Buffer,Ww=r.Uint8Array||function(){};var Vw,$w=xw,zw=Dw.getHighWaterMark,Xw=Rw.codes,Yw=Xw.ERR_INVALID_ARG_TYPE,Jw=Xw.ERR_METHOD_NOT_IMPLEMENTED,Zw=Xw.ERR_MULTIPLE_CALLBACK,Qw=Xw.ERR_STREAM_CANNOT_PIPE,tb=Xw.ERR_STREAM_DESTROYED,eb=Xw.ERR_STREAM_NULL_VALUES,rb=Xw.ERR_STREAM_WRITE_AFTER_END,nb=Xw.ERR_UNKNOWN_ENCODING,ib=$w.errorOrDestroy;function ob(){}function sb(t,e,r){Lw=Lw||gb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Lw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=zw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Zw;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(pb,t,e),t._writableState.errorEmitted=!0,ib(t,n)):(i(n),t._writableState.errorEmitted=!0,ib(t,n),pb(t,e))}(t,r,n,e,i);else{var o=cb(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||fb(t,r),n?process.nextTick(hb,t,r,o,i):hb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new qw(this)}function ub(t){var e=this instanceof(Lw=Lw||gb);if(!e&&!Vw.call(ub,this))return new ub(t);this._writableState=new sb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Kw.call(this)}function ab(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new tb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function hb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),pb(t,e)}function fb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,ab(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new qw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(ab(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function cb(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function lb(t,e){t._final((function(r){e.pendingcb--,r&&ib(t,r),e.prefinished=!0,t.emit("prefinish"),pb(t,e)}))}function pb(t,e){var r=cb(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(lb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}Zt.exports(ub,Kw),sb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(sb.prototype,"buffer",{get:Fw.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Vw=Function.prototype[Symbol.hasInstance],Object.defineProperty(ub,Symbol.hasInstance,{value:function(t){return!!Vw.call(this,t)||this===ub&&(t&&t._writableState instanceof sb)}})):Vw=function(t){return t instanceof this},ub.prototype.pipe=function(){ib(this,new Qw)},ub.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,Gw.isBuffer(n)||n instanceof Ww);return s&&!Gw.isBuffer(t)&&(t=function(t){return Gw.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ob),i.ending?function(t,e){var r=new rb;ib(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new eb:"string"==typeof r||e.objectMode||(i=new Yw("chunk",["string","Buffer"],r)),!i||(ib(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Gw.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new nb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(ub.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(ub.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),ub.prototype._write=function(t,e,r){r(new Jw("_write()"))},ub.prototype._writev=null,ub.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,pb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(ub.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(ub.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),ub.prototype.destroy=$w.destroy,ub.prototype._undestroy=$w.undestroy,ub.prototype._destroy=function(t,e){e(t)};var db=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},gb=Eb,yb=aE,vb=jw;Zt.exports(Eb,yb);for(var mb=db(vb.prototype),wb=0;wb>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Pb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function Mb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function xb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Rb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Nb(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Bb(t){return t.toString(this.encoding)}function Cb(t){return t&&t.length?this.write(t):""}Ib.StringDecoder=Ab,Ab.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},Ab.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Ub=Rw.codes.ERR_STREAM_PREMATURE_CLOSE;function Lb(){}var Db,Hb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===cE.prototype||(e=function(t){return cE.from(t)}(e)),n)s.endEmitted?OE(t,new TE):xE(t,s,e,!0);else if(s.ended)OE(t,new SE);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?xE(t,s,e,!1):UE(t,s)):xE(t,s,e,!1)}else n||(s.reading=!1,UE(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=RE?t=RE:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function BE(t){var e=t._readableState;pE("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(pE("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(CE,t))}function CE(t){var e=t._readableState;pE("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,qE(t)}function UE(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(LE,t,e))}function LE(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function HE(t){pE("readable nexttick read 0"),t.read(0)}function jE(t,e){pE("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),qE(t),e.flowing&&!e.reading&&t.read(0)}function qE(t){var e=t._readableState;for(pE("flow",e.flowing);e.flowing&&null!==t.read(););}function FE(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function KE(t){var e=t._readableState;pE("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(GE,e,t))}function GE(t,e){if(pE("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function WE(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return pE("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?KE(this):BE(this),null;if(0===(t=NE(t,e))&&e.ended)return 0===e.length&&KE(this),null;var n,i=e.needReadable;return pE("need readable",i),(0===e.length||e.length-t0?FE(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&KE(this)),null!==n&&this.emit("data",n),n},PE.prototype._read=function(t){OE(this,new IE("_read()"))},PE.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,pE("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){pE("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,pE("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){pE("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;pE("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&hE(t,"data")&&(e.flowing=!0,qE(t))}}(r);t.on("drain",u);var a=!1;function h(e){pE("ondata");var i=t.write(e);pE("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==WE(n.pipes,t))&&!a&&(pE("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){pE("onerror",e),p(),t.removeListener("error",f),0===hE(t,"error")&&OE(t,e)}function c(){t.removeListener("finish",l),p()}function l(){pE("onfinish"),t.removeListener("close",c),p()}function p(){pE("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(pE("pipe resume"),r.resume()),t},PE.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,pE("on readable",n.length,n.reading),n.length?BE(this):n.reading||process.nextTick(HE,this))),r},PE.prototype.addListener=PE.prototype.on,PE.prototype.removeListener=function(t,e){var r=fE.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(DE,this),r},PE.prototype.removeAllListeners=function(t){var e=fE.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(DE,this),e},PE.prototype.resume=function(){var t=this._readableState;return t.flowing||(pE("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(jE,t,e))}(this,t)),t.paused=!1,this},PE.prototype.pause=function(){return pE("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(pE("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},PE.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(pE("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(pE("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(l_),s||(o.forEach(l_),i(n))}))}));return e.reduce(p_)};!function(t,e){var r=yw;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=aE).Stream=r||e,e.Readable=e,e.Writable=jw,e.Duplex=gb,e.Transform=VE,e.PassThrough=i_,e.finished=Hb,e.pipeline=g_)}(gv,gv.exports);var y_=h.exports.Buffer,v_=gv.exports.Transform;function m_(t){v_.call(this),this._block=y_.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,Zt.exports)(m_,v_),m_.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},m_.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},m_.prototype.update=function(t,e){if(function(t,e){if(!y_.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");y_.isBuffer(t)||(t=y_.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},m_.prototype._update=function(){throw new Error("_update is not implemented")},m_.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},m_.prototype._digest=function(){throw new Error("_digest is not implemented")};var w_=m_,b_=ht.Buffer,E_=Zt.exports,__=w_,S_=new Array(16),I_=[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],T_=[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],O_=[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],A_=[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],k_=[0,1518500249,1859775393,2400959708,2840853838],P_=[1352829926,1548603684,1836072691,2053994217,0];function M_(){__.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function x_(t,e){return t<>>32-e}function R_(t,e,r,n,i,o,s,u){return x_(t+(e^r^n)+o+s|0,u)+i|0}function N_(t,e,r,n,i,o,s,u){return x_(t+(e&r|~e&n)+o+s|0,u)+i|0}function B_(t,e,r,n,i,o,s,u){return x_(t+((e|~r)^n)+o+s|0,u)+i|0}function C_(t,e,r,n,i,o,s,u){return x_(t+(e&n|r&~n)+o+s|0,u)+i|0}function U_(t,e,r,n,i,o,s,u){return x_(t+(e^(r|~n))+o+s|0,u)+i|0}E_(M_,__),M_.prototype._update=function(){for(var t=S_,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=R_(r,n,i,o,s,t[I_[l]],k_[0],O_[l]),d=U_(u,a,h,f,c,t[T_[l]],P_[0],A_[l])):l<32?(p=N_(r,n,i,o,s,t[I_[l]],k_[1],O_[l]),d=C_(u,a,h,f,c,t[T_[l]],P_[1],A_[l])):l<48?(p=B_(r,n,i,o,s,t[I_[l]],k_[2],O_[l]),d=B_(u,a,h,f,c,t[T_[l]],P_[2],A_[l])):l<64?(p=C_(r,n,i,o,s,t[I_[l]],k_[3],O_[l]),d=N_(u,a,h,f,c,t[T_[l]],P_[3],A_[l])):(p=U_(r,n,i,o,s,t[I_[l]],k_[4],O_[l]),d=R_(u,a,h,f,c,t[T_[l]],P_[4],A_[l])),r=s,s=o,o=x_(i,10),i=n,n=p,u=c,c=f,f=x_(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},M_.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=b_.alloc?b_.alloc(20):new b_(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var L_=M_,D_={exports:{}},H_=h.exports.Buffer;function j_(t,e){this._block=H_.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}j_.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=H_.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},j_.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var q_=j_,F_=Zt.exports,K_=q_,G_=h.exports.Buffer,W_=[1518500249,1859775393,-1894007588,-899497514],V_=new Array(80);function $_(){this.init(),this._w=V_,K_.call(this,64,56)}function z_(t){return t<<30|t>>>2}function X_(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}F_($_,K_),$_.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},$_.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+X_(f,i,o,s)+u+r[h]+W_[f];u=s,s=o,o=z_(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},$_.prototype._hash=function(){var t=G_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var Y_=$_,J_=Zt.exports,Z_=q_,Q_=h.exports.Buffer,tS=[1518500249,1859775393,-1894007588,-899497514],eS=new Array(80);function rS(){this.init(),this._w=eS,Z_.call(this,64,56)}function nS(t){return t<<5|t>>>27}function iS(t){return t<<30|t>>>2}function oS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}J_(rS,Z_),rS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},rS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=nS(n)+oS(f,i,o,s)+u+r[h]+tS[f]|0;u=s,s=o,o=iS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},rS.prototype._hash=function(){var t=Q_.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var sS=rS,uS=Zt.exports,aS=q_,hS=h.exports.Buffer,fS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cS=new Array(64);function lS(){this.init(),this._w=cS,aS.call(this,64,56)}function pS(t,e,r){return r^t&(e^r)}function dS(t,e,r){return t&e|r&(t|e)}function gS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function yS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function vS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function mS(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}uS(lS,aS),lS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},lS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=mS(e[f-2])+e[f-7]+vS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+yS(s)+pS(s,u,a)+fS[c]+e[c]|0,p=gS(r)+dS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},lS.prototype._hash=function(){var t=hS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var wS=lS,bS=Zt.exports,ES=wS,_S=q_,SS=h.exports.Buffer,IS=new Array(64);function TS(){this.init(),this._w=IS,_S.call(this,64,56)}bS(TS,ES),TS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},TS.prototype._hash=function(){var t=SS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var OS=TS,AS=Zt.exports,kS=q_,PS=h.exports.Buffer,MS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xS=new Array(160);function RS(){this.init(),this._w=xS,kS.call(this,128,112)}function NS(t,e,r){return r^t&(e^r)}function BS(t,e,r){return t&e|r&(t|e)}function CS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function US(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function LS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function DS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function HS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function jS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function qS(t,e){return t>>>0>>0?1:0}AS(RS,kS),RS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},RS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=LS(w,b),_=DS(b,w),S=HS(w=e[m-4],b=e[m-4+1]),I=jS(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],k=e[m-32+1],P=_+O|0,M=E+T+qS(P,_)|0;M=(M=M+S+qS(P=P+I|0,I)|0)+A+qS(P=P+k|0,k)|0,e[m]=M,e[m+1]=P}for(var x=0;x<160;x+=2){M=e[x],P=e[x+1];var R=BS(r,n,i),N=BS(f,c,l),B=CS(r,f),C=CS(f,r),U=US(s,d),L=US(d,s),D=MS[x],H=MS[x+1],j=NS(s,u,a),q=NS(d,g,y),F=v+L|0,K=h+U+qS(F,v)|0;K=(K=(K=K+j+qS(F=F+q|0,q)|0)+D+qS(F=F+H|0,H)|0)+M+qS(F=F+P|0,P)|0;var G=C+N|0,W=B+R+qS(G,C)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+K+qS(d=p+F|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=K+W+qS(f=F+G|0,F)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+qS(this._al,f)|0,this._bh=this._bh+n+qS(this._bl,c)|0,this._ch=this._ch+i+qS(this._cl,l)|0,this._dh=this._dh+o+qS(this._dl,p)|0,this._eh=this._eh+s+qS(this._el,d)|0,this._fh=this._fh+u+qS(this._fl,g)|0,this._gh=this._gh+a+qS(this._gl,y)|0,this._hh=this._hh+h+qS(this._hl,v)|0},RS.prototype._hash=function(){var t=PS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var FS=RS,KS=Zt.exports,GS=FS,WS=q_,VS=h.exports.Buffer,$S=new Array(160);function zS(){this.init(),this._w=$S,WS.call(this,128,112)}KS(zS,GS),zS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},zS.prototype._hash=function(){var t=VS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var XS=zS,YS=D_.exports=function(t){t=t.toLowerCase();var e=YS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};YS.sha=Y_,YS.sha1=sS,YS.sha224=OS,YS.sha256=wS,YS.sha384=XS,YS.sha512=FS;var JS=D_.exports;function ZS(t){return(new L_).update(JS("sha256").update(t).digest()).digest()}var QS,tI=(QS=function(t,e){return QS=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},QS(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}QS(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),eI=function(t,e){this.psbt=t,this.masterFp=e},rI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(eI),nI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(rI),iI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new cv,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Bp.sha256(Buffer.from("TapTweak","utf-8"));return Bp.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(xt.exports.pointAddScalar(e,r)).slice(1)},e}(rI),oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=this.createRedeemScript(t),n=ZS(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=ZS(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(rI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return tI(e,t),e.prototype.singleKeyCondition=function(t){var e=new cv,r=ZS(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(rI),uI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},aI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return lI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new cI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new cI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function LI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,UI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,UI(t.script.length),t.script])}))),r}function DI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,UI(t.script.length),t.script,t.sequence])}));var a=LI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),UI(t.inputs.length),s,a])}var HI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new pI(e,dI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return HI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I;return jI(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new _I,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new iI(e,r):t.additionals.includes("bech32")?new sI(e,r):t.segwit?new oI(e,r):new nI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new cv).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new cv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new cv;BI(h,f),BI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new cv).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}NI(t,r)}}(r),I=function(t){var e,r,n=new cv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new cv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function nT(t,e,r){return tT(this,void 0,void 0,(function(){var n,i,o,s;return eT(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function iT(t,e,r,n){return void 0===n&&(n=[]),tT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R=this;return eT(this,(function(N){switch(N.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return tT(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return eT(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>pv?pv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=rT(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,nT(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return nT(t,e)},[4,nT(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(o.length)]),e)];case 1:N.sent(),N.label=2;case 2:N.trys.push([2,8,9,10]),d=rT(o),g=d.next(),N.label=3;case 3:return g.done?[3,7]:(y=g.value,v=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),m=f?y.tree||Buffer.from([0]):Buffer.alloc(0),O=Buffer.concat([y.prevout,m,v?Buffer.from([0]):UI(y.script.length)]),[4,nT(t,O)]);case 4:return N.sent(),[4,f?p(Buffer.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:N.sent(),N.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=N.sent(),k={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(k)throw k.error}return[7];case 10:return[4,nT(t,UI(s.length))];case 11:N.sent(),N.label=12;case 12:N.trys.push([12,17,18,19]),b=rT(s),E=b.next(),N.label=13;case 13:return E.done?[3,16]:(_=E.value,O=Buffer.concat([_.amount,f?Buffer.from([0,0]):Buffer.alloc(0),UI(_.script.length),_.script]),[4,nT(t,O)]);case 14:N.sent(),N.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=N.sent(),M={error:S},[3,19];case 18:try{E&&!E.done&&(x=b.return)&&x.call(b)}finally{if(M)throw M.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=Buffer.concat(I),T=f?O:Buffer.concat([UI(O.length),O])),[4,l(Buffer.concat([u,T||Buffer.alloc(0)]))];case 20:return A=N.sent(),QI(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var oT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},sT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aT(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function hT(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),oT(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return sT(this,(function(k){switch(k.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),UI(r.inputs.length)]),[4,aT(t,e,!0,a,i,o,s)];case 1:k.sent(),h=0,f=s.includes("decred"),k.label=2;case 2:k.trys.push([2,15,16,17]),c=uT(r.inputs),l=c.next(),k.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),UI(p.script.length)]),[4,aT(t,e,!1,a,i,o,s)]);case 4:if(k.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>pv?pv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(Buffer.concat([p.script.slice(v,v+m),p.sequence])),v+=m;k.label=5;case 5:k.trys.push([5,10,11,12]),O=void 0,w=uT(y),b=w.next(),k.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,aT(t,e,!1,E,i,o,s)]);case 7:k.sent(),k.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=k.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,k.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=k.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=c.return)&&T.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function fT(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=JS("sha256").update(JS("sha256").update(DI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function cT(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=wt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var lT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},pT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:pv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var yT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ST={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function IT(t,e){return bT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C,U,L,D,H,j,q,F,K,G,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return ET(this,(function(ht){switch(ht.label){case 0:if(r=wT(wT({},ST),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,mT(t)];case 2:return v=ht.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||fv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ht.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),E=c.includes("stealthcoin"),_=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),T=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,O=Buffer.alloc(0),A=Buffer.alloc(0),k=Buffer.alloc(4),l&&!b?k.writeUInt32LE(S?2147483652:2147483651,0):E?k.writeUInt32LE(2,0):k.writeUInt32LE(1,0),P=[],M=[],x=[],R=[],N=!0,B=!1,C={inputs:[],version:k,timestamp:Buffer.alloc(0)},U=T&&!y?fT:iT,L=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=_T(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:j=ht.sent(),VI("hw","got trustedInput="+j),(q=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:dv,0),P.push({trustedInput:!0,value:Buffer.from(j,"hex"),sequence:q}),ht.label=8;case 8:F=$[0].outputs,K=$[1],F&&K<=F.length-1&&M.push(F[K]),l&&!b?(C.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),C.nExpiryHeight=l,C.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(C.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return G=ht.sent(),ut={error:G},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(C.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:dv,0),{script:O,prevout:A,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),ZS(R[it]),Buffer.from([136,172])]):M[it].script,X=Object.assign({},C),Y=T?[P[it]]:P,T?X.inputs=[wT(wT({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,hT(t,!T&&N,X,Y,T,!!l&&!b,c,y)]):[3,34];case 27:return ht.sent(),T?[3,31]:B||!o?[3,29]:[4,dT(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,gT(t,L,c)];case 30:ht.sent(),ht.label=31;case 31:return N&&(d(),w(1,0)),[4,cT(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),x.push(J),C.inputs[it].script=O,N&&(N=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},xT={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function RT(t,e){return kT(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,k,P,M,x,R,N,B,C;return PT(this,(function(U){switch(U.label){case 0:r=AT(AT({},xT),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?fT:iT,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),E=MT(n),_=E.next(),U.label=2;case 2:return _.done?[3,6]:(P=_.value,v?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=U.sent(),(A=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:dv,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:A}),U.label=4;case 4:I=P[0].outputs,T=P[1],I&&T<=I.length-1&&d.push(I[T]),U.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=U.sent(),B={error:O},[3,9];case 8:try{_&&!_.done&&(C=E.return)&&C.call(E)}finally{if(B)throw B.error}return[7];case 9:for(k=0;k=4&&"number"==typeof n[k][3]?n[k][3]:dv,0),m.inputs.push({script:f,prevout:c,sequence:A});return a?[4,hT(t,!0,m,p,!0)]:[3,12];case 10:return U.sent(),[4,gT(t,b)];case 11:U.sent(),U.label=12;case 12:k=0,U.label=13;case 13:return k=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[k].script,x=Object.assign({},m),R=a?[p[k]]:p,a?x.inputs=[AT(AT({},x.inputs[k]),{script:M})]:x.inputs[k].script=M,[4,hT(t,!a&&y,x,R,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,gT(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,cT(t,i[k],s,u)];case 17:N=U.sent(),g.push(a?N.toString("hex"):N.slice(0,N.length-1).toString("hex")),m.inputs[k].script=f,y&&(y=!1),U.label=18;case 18:return k++,[3,13];case 19:return[2,g]}}))}))}var NT=function(){return NT=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,u()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),IT(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),RT(this.transport,t)},t}();function LT(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var DT=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function HT(t){return JS("sha256").update(t).digest()}var jT,qT=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new hI(t.map((function(t){return fI(t)}))),this.values=e,this.valuesTree=new hI(e.map((function(t){return fI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([UI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),FT=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),KT=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},GT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},zT=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(jT||(jT={}));var YT,JT,ZT=function(){},QT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=jT.YIELD,n.results=e,n}return VT(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(ZT),tO=function(t){function e(e,r){var n=t.call(this)||this;return n.code=jT.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=UI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,zT([],$T(a.slice(-f)),!1)),Buffer.concat(zT([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],$T(a.slice(0,h)),!1))},e}(ZT),rO=function(t){function e(e){var r=t.call(this)||this;return r.code=jT.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return VT(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(YT||(YT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(JT||(JT={}));var aO=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return oO(this,void 0,void 0,(function(){var n,i,o;return sO(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,JT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return oO(this,void 0,void 0,(function(){return sO(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(YT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),mt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return oO(this,void 0,void 0,(function(){var o,s;return sO(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new iO((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(YT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return oO(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,y,v,m,w,b,E,_,S;return sO(this,(function(I){switch(I.label){case 0:if(i=new WT(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new iO(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=uO(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=uO(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new hI(i.inputMapCommitments.map((function(t){return fI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new hI(i.outputMapCommitments.map((function(t){return fI(t)}))).getRoot(),[4,this.makeRequest(YT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),UI(i.getGlobalInputCount()),c,UI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=uO(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return oO(this,void 0,void 0,(function(){return sO(this,(function(t){return[2,this.makeRequest(YT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var hO=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},fO=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof FI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||lO(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(Buffer.from([3,0,0,128]))||y.equals(Buffer.from([4,0,0,128])),m=y.equals(Buffer.from([1,0,0,0]))||y.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(c=g.slice(a,4+a),a+=4);var w=CI(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new UT(this.transport)},t.prototype.new=function(){return new FI(new aO(this.transport))},t}();function lO(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var pO=Object.freeze({__proto__:null,default:cO}),dO={},gO={},yO={},vO={};Object.defineProperty(vO,"__esModule",{value:!0});var mO="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wO={},bO={};vO.addCustomErrorDeserializer=function(t,e){bO[t]=e};var EO=vO.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,wO[t]=e,e};function _O(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":mO(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=_O(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}vO.deserializeError=function t(e){if("object"===(void 0===e?"undefined":mO(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=bO[i];if(o)n=o(e);else{var s="Error"===i?Error:wO[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=EO(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},vO.serializeError=function(t){return t?"object"===(void 0===t?"undefined":mO(t))?_O(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(yO,"__esModule",{value:!0}),yO.StatusCodes=yO.DBNotReset=yO.DBWrongPassword=yO.NoDBPathGiven=yO.FirmwareOrAppUpdateRequired=yO.LedgerAPI5xx=yO.LedgerAPI4xx=yO.GenuineCheckFailed=yO.PairingFailed=yO.SyncError=yO.FeeTooHigh=yO.FeeRequired=yO.FeeNotLoaded=yO.CantScanQRCode=yO.ETHAddressNonEIP=yO.WrongAppForCurrency=yO.WrongDeviceForAccount=yO.WebsocketConnectionFailed=yO.WebsocketConnectionError=yO.DeviceShouldStayInApp=yO.TransportWebUSBGestureRequired=yO.TransportInterfaceNotAvailable=yO.TransportOpenUserCancelled=yO.UserRefusedOnDevice=yO.UserRefusedAllowManager=yO.UserRefusedFirmwareUpdate=yO.UserRefusedAddress=yO.UserRefusedDeviceNameChange=yO.UpdateYourApp=yO.UnavailableTezosOriginatedAccountSend=yO.UnavailableTezosOriginatedAccountReceive=yO.RecipientRequired=yO.MCUNotGenuineToDashboard=yO.UnexpectedBootloader=yO.TimeoutTagged=yO.RecommendUndelegation=yO.RecommendSubAccountsToEmpty=yO.PasswordIncorrectError=yO.PasswordsDontMatchError=yO.GasLessThanEstimate=yO.NotSupportedLegacyAddress=yO.NotEnoughGas=yO.NoAccessToCamera=yO.NotEnoughBalanceBecauseDestinationNotCreated=yO.NotEnoughSpendableBalance=yO.NotEnoughBalanceInParentAccount=yO.NotEnoughBalanceToDelegate=yO.NotEnoughBalance=yO.NoAddressesFound=yO.NetworkDown=yO.ManagerUninstallBTCDep=yO.ManagerNotEnoughSpaceError=yO.ManagerFirmwareNotEnoughSpaceError=yO.ManagerDeviceLockedError=yO.ManagerAppDepUninstallRequired=yO.ManagerAppDepInstallRequired=yO.ManagerAppRelyOnBTCError=yO.ManagerAppAlreadyInstalledError=yO.LedgerAPINotAvailable=yO.LedgerAPIErrorWithMessage=yO.LedgerAPIError=yO.UnknownMCU=yO.LatestMCUInstalledError=yO.InvalidAddressBecauseDestinationIsAlsoSource=yO.InvalidAddress=yO.InvalidXRPTag=yO.HardResetFail=yO.FeeEstimationFailed=yO.EthAppPleaseEnableContractData=yO.EnpointConfigError=yO.DisconnectedDeviceDuringOperation=yO.DisconnectedDevice=yO.DeviceSocketNoBulkStatus=yO.DeviceSocketFail=yO.DeviceNameInvalid=yO.DeviceHalted=yO.DeviceInOSUExpected=yO.DeviceOnDashboardUnexpected=yO.DeviceOnDashboardExpected=yO.DeviceNotGenuineError=yO.DeviceGenuineSocketEarlyClose=yO.DeviceAppVerifyNotSupported=yO.CurrencyNotSupported=yO.CashAddrNotSupported=yO.CantOpenDevice=yO.BtcUnmatchedApp=yO.BluetoothRequired=yO.AmountRequired=yO.AccountNotSupported=yO.AccountNameRequiredError=yO.addCustomErrorDeserializer=yO.createCustomErrorClass=yO.deserializeError=yO.serializeError=void 0,yO.TransportError=IO,yO.getAltStatusMessage=OO,yO.TransportStatusError=AO;var SO=vO;function IO(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}yO.serializeError=SO.serializeError,yO.deserializeError=SO.deserializeError,yO.createCustomErrorClass=SO.createCustomErrorClass,yO.addCustomErrorDeserializer=SO.addCustomErrorDeserializer,yO.AccountNameRequiredError=(0,SO.createCustomErrorClass)("AccountNameRequired"),yO.AccountNotSupported=(0,SO.createCustomErrorClass)("AccountNotSupported"),yO.AmountRequired=(0,SO.createCustomErrorClass)("AmountRequired"),yO.BluetoothRequired=(0,SO.createCustomErrorClass)("BluetoothRequired"),yO.BtcUnmatchedApp=(0,SO.createCustomErrorClass)("BtcUnmatchedApp"),yO.CantOpenDevice=(0,SO.createCustomErrorClass)("CantOpenDevice"),yO.CashAddrNotSupported=(0,SO.createCustomErrorClass)("CashAddrNotSupported"),yO.CurrencyNotSupported=(0,SO.createCustomErrorClass)("CurrencyNotSupported"),yO.DeviceAppVerifyNotSupported=(0,SO.createCustomErrorClass)("DeviceAppVerifyNotSupported"),yO.DeviceGenuineSocketEarlyClose=(0,SO.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),yO.DeviceNotGenuineError=(0,SO.createCustomErrorClass)("DeviceNotGenuine"),yO.DeviceOnDashboardExpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardExpected"),yO.DeviceOnDashboardUnexpected=(0,SO.createCustomErrorClass)("DeviceOnDashboardUnexpected"),yO.DeviceInOSUExpected=(0,SO.createCustomErrorClass)("DeviceInOSUExpected"),yO.DeviceHalted=(0,SO.createCustomErrorClass)("DeviceHalted"),yO.DeviceNameInvalid=(0,SO.createCustomErrorClass)("DeviceNameInvalid"),yO.DeviceSocketFail=(0,SO.createCustomErrorClass)("DeviceSocketFail"),yO.DeviceSocketNoBulkStatus=(0,SO.createCustomErrorClass)("DeviceSocketNoBulkStatus"),yO.DisconnectedDevice=(0,SO.createCustomErrorClass)("DisconnectedDevice"),yO.DisconnectedDeviceDuringOperation=(0,SO.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),yO.EnpointConfigError=(0,SO.createCustomErrorClass)("EnpointConfig"),yO.EthAppPleaseEnableContractData=(0,SO.createCustomErrorClass)("EthAppPleaseEnableContractData"),yO.FeeEstimationFailed=(0,SO.createCustomErrorClass)("FeeEstimationFailed"),yO.HardResetFail=(0,SO.createCustomErrorClass)("HardResetFail"),yO.InvalidXRPTag=(0,SO.createCustomErrorClass)("InvalidXRPTag"),yO.InvalidAddress=(0,SO.createCustomErrorClass)("InvalidAddress"),yO.InvalidAddressBecauseDestinationIsAlsoSource=(0,SO.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),yO.LatestMCUInstalledError=(0,SO.createCustomErrorClass)("LatestMCUInstalledError"),yO.UnknownMCU=(0,SO.createCustomErrorClass)("UnknownMCU"),yO.LedgerAPIError=(0,SO.createCustomErrorClass)("LedgerAPIError"),yO.LedgerAPIErrorWithMessage=(0,SO.createCustomErrorClass)("LedgerAPIErrorWithMessage"),yO.LedgerAPINotAvailable=(0,SO.createCustomErrorClass)("LedgerAPINotAvailable"),yO.ManagerAppAlreadyInstalledError=(0,SO.createCustomErrorClass)("ManagerAppAlreadyInstalled"),yO.ManagerAppRelyOnBTCError=(0,SO.createCustomErrorClass)("ManagerAppRelyOnBTC"),yO.ManagerAppDepInstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepInstallRequired"),yO.ManagerAppDepUninstallRequired=(0,SO.createCustomErrorClass)("ManagerAppDepUninstallRequired"),yO.ManagerDeviceLockedError=(0,SO.createCustomErrorClass)("ManagerDeviceLocked"),yO.ManagerFirmwareNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),yO.ManagerNotEnoughSpaceError=(0,SO.createCustomErrorClass)("ManagerNotEnoughSpace"),yO.ManagerUninstallBTCDep=(0,SO.createCustomErrorClass)("ManagerUninstallBTCDep"),yO.NetworkDown=(0,SO.createCustomErrorClass)("NetworkDown"),yO.NoAddressesFound=(0,SO.createCustomErrorClass)("NoAddressesFound"),yO.NotEnoughBalance=(0,SO.createCustomErrorClass)("NotEnoughBalance"),yO.NotEnoughBalanceToDelegate=(0,SO.createCustomErrorClass)("NotEnoughBalanceToDelegate"),yO.NotEnoughBalanceInParentAccount=(0,SO.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),yO.NotEnoughSpendableBalance=(0,SO.createCustomErrorClass)("NotEnoughSpendableBalance"),yO.NotEnoughBalanceBecauseDestinationNotCreated=(0,SO.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),yO.NoAccessToCamera=(0,SO.createCustomErrorClass)("NoAccessToCamera"),yO.NotEnoughGas=(0,SO.createCustomErrorClass)("NotEnoughGas"),yO.NotSupportedLegacyAddress=(0,SO.createCustomErrorClass)("NotSupportedLegacyAddress"),yO.GasLessThanEstimate=(0,SO.createCustomErrorClass)("GasLessThanEstimate"),yO.PasswordsDontMatchError=(0,SO.createCustomErrorClass)("PasswordsDontMatch"),yO.PasswordIncorrectError=(0,SO.createCustomErrorClass)("PasswordIncorrect"),yO.RecommendSubAccountsToEmpty=(0,SO.createCustomErrorClass)("RecommendSubAccountsToEmpty"),yO.RecommendUndelegation=(0,SO.createCustomErrorClass)("RecommendUndelegation"),yO.TimeoutTagged=(0,SO.createCustomErrorClass)("TimeoutTagged"),yO.UnexpectedBootloader=(0,SO.createCustomErrorClass)("UnexpectedBootloader"),yO.MCUNotGenuineToDashboard=(0,SO.createCustomErrorClass)("MCUNotGenuineToDashboard"),yO.RecipientRequired=(0,SO.createCustomErrorClass)("RecipientRequired"),yO.UnavailableTezosOriginatedAccountReceive=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),yO.UnavailableTezosOriginatedAccountSend=(0,SO.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),yO.UpdateYourApp=(0,SO.createCustomErrorClass)("UpdateYourApp"),yO.UserRefusedDeviceNameChange=(0,SO.createCustomErrorClass)("UserRefusedDeviceNameChange"),yO.UserRefusedAddress=(0,SO.createCustomErrorClass)("UserRefusedAddress"),yO.UserRefusedFirmwareUpdate=(0,SO.createCustomErrorClass)("UserRefusedFirmwareUpdate"),yO.UserRefusedAllowManager=(0,SO.createCustomErrorClass)("UserRefusedAllowManager"),yO.UserRefusedOnDevice=(0,SO.createCustomErrorClass)("UserRefusedOnDevice"),yO.TransportOpenUserCancelled=(0,SO.createCustomErrorClass)("TransportOpenUserCancelled"),yO.TransportInterfaceNotAvailable=(0,SO.createCustomErrorClass)("TransportInterfaceNotAvailable"),yO.TransportWebUSBGestureRequired=(0,SO.createCustomErrorClass)("TransportWebUSBGestureRequired"),yO.DeviceShouldStayInApp=(0,SO.createCustomErrorClass)("DeviceShouldStayInApp"),yO.WebsocketConnectionError=(0,SO.createCustomErrorClass)("WebsocketConnectionError"),yO.WebsocketConnectionFailed=(0,SO.createCustomErrorClass)("WebsocketConnectionFailed"),yO.WrongDeviceForAccount=(0,SO.createCustomErrorClass)("WrongDeviceForAccount"),yO.WrongAppForCurrency=(0,SO.createCustomErrorClass)("WrongAppForCurrency"),yO.ETHAddressNonEIP=(0,SO.createCustomErrorClass)("ETHAddressNonEIP"),yO.CantScanQRCode=(0,SO.createCustomErrorClass)("CantScanQRCode"),yO.FeeNotLoaded=(0,SO.createCustomErrorClass)("FeeNotLoaded"),yO.FeeRequired=(0,SO.createCustomErrorClass)("FeeRequired"),yO.FeeTooHigh=(0,SO.createCustomErrorClass)("FeeTooHigh"),yO.SyncError=(0,SO.createCustomErrorClass)("SyncError"),yO.PairingFailed=(0,SO.createCustomErrorClass)("PairingFailed"),yO.GenuineCheckFailed=(0,SO.createCustomErrorClass)("GenuineCheckFailed"),yO.LedgerAPI4xx=(0,SO.createCustomErrorClass)("LedgerAPI4xx"),yO.LedgerAPI5xx=(0,SO.createCustomErrorClass)("LedgerAPI5xx"),yO.FirmwareOrAppUpdateRequired=(0,SO.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),yO.NoDBPathGiven=(0,SO.createCustomErrorClass)("NoDBPathGiven"),yO.DBWrongPassword=(0,SO.createCustomErrorClass)("DBWrongPassword"),yO.DBNotReset=(0,SO.createCustomErrorClass)("DBNotReset"),IO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportError",(function(t){return new IO(t.message,t.id)}));var TO=yO.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function OO(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function AO(t){this.name="TransportStatusError";var e=Object.keys(TO).find((function(e){return TO[e]===t}))||"UNKNOWN_ERROR",r=OO(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}AO.prototype=new Error,(0,SO.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new AO(t.statusCode)})),Object.defineProperty(gO,"__esModule",{value:!0}),gO.getAltStatusMessage=gO.StatusCodes=gO.TransportStatusError=gO.TransportError=void 0;var kO,PO=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:Buffer.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[xO.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new xO.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(Buffer.concat([Buffer.from([e,r,i,o]),Buffer.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new xO.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=NO(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new xO.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return PO(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new xO.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new xO.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();BO.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",BO.ErrorMessage_NoDeviceFound="No Ledger device found",gO.default=BO;var CO={};Object.defineProperty(CO,"__esModule",{value:!0});var UO=yO;function LO(t){var e=Buffer.alloc(2);return e.writeUInt16BE(t,0),e}var DO={data:Buffer.alloc(0),dataLength:0,sequence:0};CO.default=function(t,e){return{makeBlocks:function(r){var n=Buffer.concat([LO(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=Buffer.concat([n,Buffer.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var HO={};Object.defineProperty(HO,"__esModule",{value:!0});var jO=Object.assign||function(t){for(var e=1;e>8;return KO.find((function(t){return t.productIdMM===r}))},HO.identifyProductName=function(t){var e=FO[t];return KO.find((function(t){return t.id===e}))};var GO=[],WO={};for(var VO in qO){var $O=qO[VO],zO=$O.bluetoothSpec;if(zO)for(var XO=0;XO0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",oA());case 6:case"end":return t.stop()}}),t,this)}))),function(){return iA.apply(this,arguments)});var uA=HO;function aA(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var hA=[{vendorId:uA.ledgerUSBVendorId}];eA.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(dO,"__esModule",{value:!0});var fA=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,lA.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:f=r.sent,c=Buffer.from(f.data.buffer),(0,dA.log)("hid-frame","<= "+c.toString("hex")),h=o.reduceResponse(h,c),r.next=14;break;case 23:return(0,dA.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new gA.DisconnectedDeviceDuringOperation(e.message);throw e}))}},EA=dO.default=wA,_A=Object.freeze(e({__proto__:null,default:EA},[dO]));t.Btc=pO,t.TransportWebUSB=_A,Object.defineProperty(t,"__esModule",{value:!0})})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util')) : + typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$1, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.require$$1)); +})(this, (function (exports, require$$0$1, require$$0$2, require$$0$3, require$$0$4, require$$1) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); + } + + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); + var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); + var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); + var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); + var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + /* + * Bitcoin BIP32 path helpers + * (C) 2016 Alex Beregszaszi + */ + + const HARDENED = 0x80000000; + + var BIPPath = function (path) { + if (!Array.isArray(path)) { + throw new Error('Input must be an Array') + } + if (path.length === 0) { + throw new Error('Path must contain at least one level') + } + for (var i = 0; i < path.length; i++) { + if (typeof path[i] !== 'number') { + throw new Error('Path element is not a number') + } + } + this.path = path; + }; + + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false + } + }; + + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false + } + }; + + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) + }; + + BIPPath.fromString = function (text, reqRoot) { + // skip the root + if (/^m\//i.test(text)) { + text = text.slice(2); + } else if (reqRoot) { + throw new Error('Root element is required') + } + + var path = text.split('/'); + var ret = new Array(path.length); + for (var i = 0; i < path.length; i++) { + var tmp = /(\d+)([hH\']?)/.exec(path[i]); + if (tmp === null) { + throw new Error('Invalid input') + } + ret[i] = parseInt(tmp[1], 10); + + if (ret[i] >= HARDENED) { + throw new Error('Invalid child index') + } + + if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { + ret[i] += HARDENED; + } else if (tmp[2].length != 0) { + throw new Error('Invalid modifier') + } + } + return new BIPPath(ret) + }; + + BIPPath.prototype.toPathArray = function () { + return this.path + }; + + BIPPath.prototype.toString = function (noRoot, oldStyle) { + var ret = new Array(this.path.length); + for (var i = 0; i < this.path.length; i++) { + var tmp = this.path[i]; + if (tmp & HARDENED) { + ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); + } else { + ret[i] = tmp; + } + } + return (noRoot ? '' : 'm/') + ret.join('/') + }; + + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; + + var bip32Path = BIPPath; + + var createHash$3 = require$$0__default["default"].createHash; + + var safeBuffer = {exports: {}}; + + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer = require$$0__default$1["default"]; + 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) + }; + }(safeBuffer, safeBuffer.exports)); + + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; + } + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; + } + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } + } + var src$2 = base$2; + + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + var bs58 = basex(ALPHABET$1); + + var base58 = bs58; + var Buffer$g = safeBuffer.exports.Buffer; + + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); + + return base58.encode(Buffer$g.concat([ + payload, + checksum + ], payload.length + 4)) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } + }; + + var createHash$2 = createHash$3; + var bs58checkBase = base$1; + + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() + } + + var bs58check$5 = bs58checkBase(sha256x2); + + function pathElementsToBuffer(paths) { + var buffer = Buffer.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } + + var src$1 = {}; + + var src = {}; + + var bip32$1 = {}; + + var crypto$4 = {}; + + var createHmac$2 = require$$0__default["default"].createHmac; + + Object.defineProperty(crypto$4, "__esModule", { value: true }); + const createHash$1 = createHash$3; + const createHmac$1 = createHmac$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } + } + crypto$4.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$4.hmacSHA512 = hmacSHA512; + + var tinySecp256k1 = {exports: {}}; + + var bn = {exports: {}}; + + (function (module) { + (function (module, exports) { + + // 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 = require('buffer').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) ; 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); + }; + })(module, commonjsGlobal); + }(bn)); + + var elliptic = {}; + + var name = "elliptic"; + var version = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0 = { + name: name, + version: version, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; + + var utils$n = {}; + + var minimalisticAssert = assert$f; + + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } + + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; + + var utils$m = {}; + + (function (exports) { + + 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; + }; + }(utils$m)); + + (function (exports) { + + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; + + 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; + }(utils$n)); + + var brorand = {exports: {}}; + + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; + } + brorand.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$3 = require('crypto'); + if (typeof crypto$3.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$3.randomBytes(n); + }; + } catch (e) { + } + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); + } + } + var base = 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$e(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$e(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]; + 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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; + }; + + var inherits$c = {exports: {}}; + + var inherits_browser = {exports: {}}; + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } + + try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + inherits$c.exports = util.inherits; + } catch (e) { + /* istanbul ignore next */ + inherits$c.exports = inherits_browser.exports; + } + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$b = inherits$c.exports; + var Base$2 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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$b(ShortCurve, Base$2); + var short = 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$7(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$7(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$d(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$7(vec.a, 16), + b: new BN$7(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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$b(Point$2, Base$2.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.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$2.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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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$b(JPoint, Base$2.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$7(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; + }; + + var BN$6 = bn.exports; + var inherits$a = inherits$c.exports; + var Base$1 = base; + + var utils$j = utils$n; + + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); + + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$a(MontCurve, Base$1); + var mont = 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$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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$a(Point$1, Base$1.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); + }; + + Point$1.prototype.precompute = function precompute() { + // No-op + }; + + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; + + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point$1.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$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$9 = inherits$c.exports; + var Base = base; + + var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$9(EdwardsCurve, Base); + var edwards = 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$5(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$5(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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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$9(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; + + (function (exports) { + + var curve = exports; + + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); + + var curves$2 = {}; + + var hash$3 = {}; + + var utils$h = {}; + + var assert$b = minimalisticAssert; + var inherits$8 = inherits$c.exports; + + utils$h.inherits = inherits$8; + + 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; + } + utils$h.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.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; + } + utils$h.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.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; + } + utils$h.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.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; + } + utils$h.split32 = split32; + + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; + + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; + + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; + + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; + + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; + + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; + + function sum64$1(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; + } + utils$h.sum64 = sum64$1; + + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; + + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; + + function sum64_4_hi$1(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; + } + utils$h.sum64_4_hi = sum64_4_hi$1; + + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; + + function sum64_5_hi$1(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; + } + utils$h.sum64_5_hi = sum64_5_hi$1; + + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; + + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; + + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; + + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; + + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; + + var common$5 = {}; + + var utils$g = utils$h; + var assert$a = minimalisticAssert; + + function BlockHash$4() { + 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; + } + common$5.BlockHash = BlockHash$4; + + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); + + return this._digest(enc); + }; + + BlockHash$4.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; + }; + + var sha$2 = {}; + + var common$4 = {}; + + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; + + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); + } + common$4.ft_1 = ft_1$1; + + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; + + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + common$4.maj32 = maj32$1; + + function p32(x, y, z) { + return x ^ y ^ z; + } + common$4.p32 = p32; + + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$4.s0_256 = s0_256$1; + + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$4.s1_256 = s1_256$1; + + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + common$4.g0_256 = g0_256$1; + + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + common$4.g1_256 = g1_256$1; + + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; + + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; + + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; + + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); + } + + utils$e.inherits(SHA1, BlockHash$3); + var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; + + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; + + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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$2 = common$2.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$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; + + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; + + SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } + + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; + + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; + + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; + + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; + + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; + + var BlockHash$1 = common$1.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$2() { + if (!(this instanceof SHA512$2)) + return new SHA512$2(); + + BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); + var _512 = SHA512$2; + + SHA512$2.blockSize = 1024; + SHA512$2.outSize = 512; + SHA512$2.hmacStrength = 192; + SHA512$2.padLength = 128; + + SHA512$2.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$2.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$8(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); + 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); + 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$2.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.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; + } + + var utils$a = utils$h; + + var SHA512$1 = _512; + + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512$1.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; + } + utils$a.inherits(SHA384, SHA512$1); + var _384 = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); + }; + + sha$2.sha1 = _1; + sha$2.sha224 = _224; + sha$2.sha256 = _256; + sha$2.sha384 = _384; + sha$2.sha512 = _512; + + var ripemd = {}; + + var utils$9 = utils$h; + var common = common$5; + + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; + var BlockHash = common.BlockHash; + + function RIPEMD160$1() { + if (!(this instanceof RIPEMD160$1)) + return new RIPEMD160$1(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; + } + utils$9.inherits(RIPEMD160$1, BlockHash); + ripemd.ripemd160 = RIPEMD160$1; + + RIPEMD160$1.blockSize = 512; + RIPEMD160$1.outSize = 160; + RIPEMD160$1.hmacStrength = 192; + RIPEMD160$1.padLength = 64; + + RIPEMD160$1.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$4(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$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$9.toHex32(this.h, 'little'); + else + return utils$9.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$4(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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); + } + var hmac = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(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); + }; + + (function (exports) { + var hash = exports; + + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha$2; + hash.ripemd = ripemd; + hash.hmac = hmac; + + // 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; + }(hash$3)); + + (function (exports) { + + var curves = exports; + + var hash = hash$3; + var curve$1 = curve; + var utils = utils$n; + + var assert = utils.assert; + + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.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 = require('./precomputed/secp256k1'); + } 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, + ], + }); + }(curves$2)); + + var hash$2 = hash$3; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; + + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; + + HmacDRBG$1.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$1.prototype._hmac = function hmac() { + return new hash$2.hmac(this.hash, this.K); + }; + + HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); + + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG$1.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$7.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$7.encode(res, enc); + }; + + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; + + function KeyPair$4(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); + } + var key$1 = KeyPair$4; + + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; + + KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + var signature$1 = Signature$3; + + 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$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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$3(r); + this.s = new BN$3(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$3.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$5.encode(res, enc); + }; + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); + }; + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); + }; + + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; + + EC$1.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(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + + EC$1.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$1.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$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); + } + + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; + + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; + + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; + + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; + + var key = KeyPair$2; + + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.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$1(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes$1(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + 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$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + var signature = Signature$1; + + var hash$1 = hash$3; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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$1.sha512; + } + + var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = createHmac$2; + + const ONE1 = Buffer.alloc(1, 1); + const ZERO1 = Buffer.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer.alloc(32, 0); + let v = Buffer.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; + } + + return T + } + + var rfc6979 = deterministicGenerateK$1; + + const BN = bn.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer.alloc(32, 0); + const EC_GROUP_ORDER = Buffer.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return Buffer.isBuffer(x) && x.length === 32 + } + + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isPoint (p) { + if (!Buffer.isBuffer(p)) return false + if (p.length < 33) return false + + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true + } + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false + } + + function __isPointCompressed (p) { + return p[0] !== 0x04 + } + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) + } + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return Buffer.isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 + } + + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } + + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer.from(P._encode(compressed)) } + + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) + } + + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) + } + + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + + const compressed = assumeCompression(__compressed, p); + + return getEncoded(pp, compressed) + } + + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) + } + + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null + + return getEncoded(qq, compressed) + } + + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function sign (hash, x) { + return __sign(hash, x) + } + + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) + } + + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); + + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); + + if (Q.isInfinity()) return false + + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer + } + + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) + } + + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign, + signWithEntropy, + verify + }; + + try { + tinySecp256k1.exports = require('./native'); + } catch (err) { + tinySecp256k1.exports = js; + } + + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); + } + + var native$1 = types$c; + + var native = native$1; + + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } + + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); + } + } + + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' + } + + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') + } + + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); + + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + } + + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } + + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); + } + + captureStackTrace(e); + return e + } + + var errors$1 = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors$1; + + function _Buffer (value) { + return Buffer.isBuffer(value) + } + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors$1; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str + }; + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; + } + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) }; + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected }; + + return _value + } + }; + + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; + + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) + } + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce$b(compile(type), value, strict) + } + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } + } + + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer(compressed ? 34 : 33); + + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result + } + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) + } + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw + }; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$2 = crypto$4; + const bs58check$3 = bs58check$5; + const ecc$6 = tinySecp256k1.exports; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); + } + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; + } + get depth() { + return this.__DEPTH; + } + get index() { + return this.__INDEX; + } + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; + } + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; + } + get privateKey() { + return this.__D; + } + get identifier() { + return crypto$2.hash160(this.publicKey); + } + get fingerprint() { + return this.identifier.slice(0, 4); + } + get compressed() { + return true; + } + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; + } + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$2.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); + } + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); + } + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) + } + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } + return hd; + } + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$2.hmacSHA512(Buffer.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; + + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; + + var address$1 = {}; + + var networks$3 = {}; + + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + + var payments$4 = {}; + + var embed = {}; + + var script$1 = {}; + + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { + return ( + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); + } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$f = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } + + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + } + } + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$f.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature + } + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer.concat([ZERO$1, x], 1 + x.length); + return x; + } + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); + } + + return size + } + + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; + + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; + + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; + + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; + + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + + number = buffer.readUInt32LE(offset + 1); + size = 5; + } + + return { + opcode: opcode, + number: number, + size: size + } + } + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; + + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; + } + + var map_1 = map; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = tinySecp256k1.exports; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); + } + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); + } + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); + } + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; + } + function chunksIsBuffer(buf) { + return Buffer.isBuffer(buf); + } + function chunksIsArray(buf) { + return types.Array(buf); + } + function singleChunkIsBuffer(buf) { + return Buffer.isBuffer(buf); + } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; + } + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; + } + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); + } + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer.from(chunkStr, 'hex'); + }), + ); + } + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); + } + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); + } + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; + } + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!Buffer.isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); + + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); + } + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; + } + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); + } + embed.p2data = p2data; + + var p2ms$3 = {}; + + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = tinySecp256k1.exports; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + + var p2pk$3 = {}; + + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = tinySecp256k1.exports; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); + } + p2pk$3.p2pk = p2pk$2; + + var p2pkh$4 = {}; + + var crypto$1 = {}; + + Object.defineProperty(crypto$1, '__esModule', { value: true }); + const createHash = createHash$3; + function ripemd160$2(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } + } + crypto$1.ripemd160 = ripemd160$2; + function sha1$1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$1.sha1 = sha1$1; + function sha256$2(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$1.sha256 = sha256$2; + function hash160$1(buffer) { + return ripemd160$2(sha256$2(buffer)); + } + crypto$1.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$2(sha256$2(buffer)); + } + crypto$1.hash256 = hash256$1; + + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$1; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = tinySecp256k1.exports; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2pkh$4.p2pkh = p2pkh$3; + + var p2sh$1 = {}; + + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$1; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; + } + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); + return { + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!Buffer.isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); + } + p2sh$1.p2sh = p2sh; + + var p2wpkh$2 = {}; + + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk + } + + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + + return result + } + + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' + + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } + + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) + } + + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result + } + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } + + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$1; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = tinySecp256k1.exports; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2wpkh$2.p2wpkh = p2wpkh$1; + + var p2wsh$1 = {}; + + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$1; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = tinySecp256k1.exports; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + function chunkHasUncompressedPubkey(chunk) { + if ( + Buffer.isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; + } + } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer.from(data), + }; + } + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); + } + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); + } + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } + } + throw new Error(address + ' has no matching Script'); + } + address$1.toOutputScript = toOutputScript; + + var ecpair = {}; + + var randombytes = require$$0__default["default"].randomBytes; + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = tinySecp256k1.exports; + const randomBytes = randombytes; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer$e = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer$e.allocUnsafe(encodingLength$1(number)); + if (!Buffer$e.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; + } + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer$e.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number + } + } + + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; + } + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; + } + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$1; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(Buffer.from(hex, 'hex'), false); + } + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; + } + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$1; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(Buffer.from(hex, 'hex')); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); + } + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } + } + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); + } + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); + } + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + Buffer.isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + Buffer.isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); + } + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); + } + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; + } + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; + } + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return Buffer.isBuffer(data); + } + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; + } + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; + } + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return Buffer.isBuffer(data); + } + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); + } + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; + } + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return Buffer.isBuffer(data); + } + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; + } + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer.concat([head, pSig.pubkey]), + value: pSig.signature, + }; + } + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + Buffer.isBuffer(data.pubkey) && + Buffer.isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); + } + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!Buffer.isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer.from(data, 'utf8'), + }; + } + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); + } + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; + } + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; + } + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; + } + sighashType$1.canAdd = canAdd$1; + + var witnessUtxo$1 = {}; + + var tools = {}; + + var varint$1 = {}; + + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); + } + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(_number)); + if (!Buffer.isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); + } + return buffer; + } + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!Buffer.isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; + + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer.from([0])); + return Buffer.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; + + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return Buffer.isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; + + var bip32Derivation$1 = {}; + + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer.from([TYPE_BYTE]); + const key = Buffer.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + Buffer.isBuffer(data.pubkey) && + Buffer.isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; + } + bip32Derivation$1.makeConverter = makeConverter$2; + + var checkPubkey$1 = {}; + + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } + } + checkPubkey$1.makeChecker = makeChecker; + + var redeemScript$1 = {}; + + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return Buffer.isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + redeemScript$1.makeConverter = makeConverter$1; + + var witnessScript$1 = {}; + + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return Buffer.isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + witnessScript$1.makeConverter = makeConverter; + + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; + + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + + var toBuffer = {}; + + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); + } + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); + }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; + + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); + + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); + } + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; + } + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; + } + + var utils = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; + } + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; + } + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } + } + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; + } + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; + } + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); + } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; + } + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$1; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + static fromBase64(data, opts = {}) { + const buffer = Buffer.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); + } + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); + } + return results.every(res => res === true); + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } + } + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!Buffer.isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !Buffer.isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + throws = true; + } + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); + } + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); + } + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; + } + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; + } + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return Buffer.isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; + } + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer.concat([buffer, Buffer.from(slice)]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !Buffer.isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } + + var transaction_builder = {}; + + var classify$1 = {}; + + var multisig$1 = {}; + + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); + } + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; + }; + + var output$e = {}; + + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; + }; + + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; + + var nulldata = {}; + + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; + }; + const output$c = { check: check$b }; + nulldata.output = output$c; + + var pubkey = {}; + + var input$9 = {}; + + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; + }; + + var output$b = {}; + + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; + }; + + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; + + var pubkeyhash = {}; + + var input$7 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; + }; + + var output$9 = {}; + + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; + }; + + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; + + var scripthash = {}; + + var input$5 = {}; + + var output$7 = {}; + + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; + + var output$6 = {}; + + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); + } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; + + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!Buffer.isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); + } + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; + } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; + + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); + } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; + + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; + + var witnesscommitment = {}; + + var output$3 = {}; + + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); + } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; + + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; + + var witnesspubkeyhash = {}; + + var input$3 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; + + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; + + var witnessscripthash = {}; + + var input$1 = {}; + + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!Buffer.isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; + + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; + + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; + + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$1; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); + } + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); + } + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, + }); + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; + } + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; + } + this.__USE_LOW_R = setting; + return setting; + } + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); + } + this.__TX.locktime = locktime; + } + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; + } + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); + } + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); + } + build() { + return this.__build(false); + } + buildIncomplete() { + return this.__build(true); + } + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); + } + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } + prevOutType = expanded.type; + } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; + } + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } + } + return tx; + } + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); + } + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); + } + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; + } + } + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; + } + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; + } + } + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); + } + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; + } + } + return { type }; + } + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, + }); + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); + } + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); + } + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); + } + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + } + } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); + } + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; + } + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); + } + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); + } + if (keyPair === undefined) { + throw new Error('sign requires keypair'); + } + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); + } + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } + + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$1; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + const debug$4 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$4; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$3 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } + + debug$3('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$3('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self + } + + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted + } + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } + } + + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } + } + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$2('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$2 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$2('comp', comp, options); + comp = replaceCarets(comp, options); + debug$2('caret', comp); + comp = replaceTildes(comp, options); + debug$2('tildes', comp); + comp = replaceXRanges(comp, options); + debug$2('xrange', comp); + comp = replaceStars(comp, options); + debug$2('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$2('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$2('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$2('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$2('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$2('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } + + debug$2('caret return', ret); + return ret + }) + }; + + const replaceXRanges = (comp, options) => { + debug$2('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$2('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$2('xRange return', ret); + + return ret + }) + }; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$2('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; + + const replaceGTE0 = (comp, options) => { + debug$2('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$2(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + }; + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } + } + + debug$1('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug$1('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug$1('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } + } + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug$1 = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true + }; + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; + + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + var readable = {exports: {}}; + + var stream = require$$0__default$2["default"]; + + function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + + function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + var _require$2 = require$$0__default$1["default"], + Buffer$d = _require$2.Buffer; + + var _require2 = require$$1__default["default"], + inspect = _require2.inspect; + + var custom = inspect && inspect.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$d.prototype.copy.call(src, target, offset); + } + + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck$2(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass$2(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$d.alloc(0); + var ret = Buffer$d.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$d.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread$1({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; + }(); + + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; + } + + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.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(self, err) { + self.emit('error', err); + } + + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } + + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; + + var errors = {}; + + const codes = {}; + + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; + } + + // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + + errors.codes = codes; + + var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; + } + + var state = { + getHighWaterMark: getHighWaterMark$2 + }; + + /** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + + var node = require$$1__default["default"].deprecate; + + var _stream_writable = Writable$1; + // there will be only 2 of these for each stream + + + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ + + /**/ + + + var Duplex$3; + /**/ + + Writable$1.WritableState = WritableState; + /**/ + + var internalUtil = { + deprecate: node + }; + /**/ + + /**/ + + var Stream$1 = stream; + /**/ + + + var Buffer$c = require$$0__default$1["default"].Buffer; + + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$c.from(chunk); + } + + function _isUint8Array$1(obj) { + return Buffer$c.isBuffer(obj) || obj instanceof OurUint8Array$1; + } + + var destroyImpl$1 = destroy_1; + + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; + + var _require$codes$3 = errors.codes, + ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + + inherits$c.exports(Writable$1, Stream$1); + + function nop() {} + + function WritableState(options, stream, isDuplex) { + Duplex$3 = Duplex$3 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + + + var realHasInstance; + + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$1, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$1) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } + + function Writable$1(options) { + Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$3; + if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. + + + Writable$1.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; + + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy$1(stream, er); + process.nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + + + function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy$1(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; + } + + Writable$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$c.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; + + Writable$1.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$c.from(chunk, encoding); + } + + return chunk; + } + + Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + + + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } // if there's something in the buffer waiting, then process it + + + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; + + Writable$1.prototype._writev = null; + + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + + function prefinish$1(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish$1(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; + } + + Object.defineProperty(Writable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl$1.destroy; + Writable$1.prototype._undestroy = destroyImpl$1.undestroy; + + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; + + /**/ + + var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; + }; + /**/ + + + var _stream_duplex = Duplex$2; + + var Readable$1 = _stream_readable; + + var Writable = _stream_writable; + + inherits$c.exports(Duplex$2, Readable$1); + + { + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; + } + } + + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); + Readable$1.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } + } + + Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer + + function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + Object.defineProperty(Duplex$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + var string_decoder = {}; + + /**/ + + var Buffer$b = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$b.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$b.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. + string_decoder.StringDecoder = StringDecoder$1; + function StringDecoder$1(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$b.allocUnsafe(nb); + } + + StringDecoder$1.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$1.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$1.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$1.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); + 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) : ''; + } + + var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; + + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; + } + + function noop$1() {} + + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } + + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } + + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty$1(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty$1(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; + + var async_iterator = createReadableStreamAsyncIterator$1; + + 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$3(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); }); }; } + + 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; + + function from$1(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator$3(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; + } + + var from_1 = from$1; + + var _stream_readable = Readable; + /**/ + + var Duplex$1; + /**/ + + Readable.ReadableState = ReadableState; + /**/ + + require$$0__default$3["default"].EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + /**/ + + + var Stream = stream; + /**/ + + + var Buffer$a = require$$0__default$1["default"].Buffer; + + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer(chunk) { + return Buffer$a.from(chunk); + } + + function _isUint8Array(obj) { + return Buffer$a.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ + + + var debugUtil = require$$1__default["default"]; + + var debug; + + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function debug() {}; + } + /**/ + + + var BufferList = buffer_list; + + var destroyImpl = destroy_1; + + var _require = state, + getHighWaterMark = _require.getHighWaterMark; + + var _require$codes$2 = errors.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + + var StringDecoder; + var createReadableStreamAsyncIterator; + var from; + + inherits$c.exports(Readable, Stream); + + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState(options, stream, isDuplex) { + Duplex$1 = Duplex$1 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + Duplex$1 = Duplex$1 || _stream_duplex; + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$1; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); + } + + Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + + + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer$a.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() + + + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$a.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); + } + + function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; + } + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. + + + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB + + + var MAX_HWM = 0x40000000; + + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; + } // you can override either this method, or the async _read(n) below. + + + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; + }; + + function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + + + function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } + } + + function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + + + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something + + + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; + }; + + Readable.prototype.addListener = Readable.prototype.on; + + Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; + }; + + Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; + }; + + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + + + Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + + + Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } + + return createReadableStreamAsyncIterator(this); + }; + } + + Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + + if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = from_1; + } + + return from(Readable, iterable, opts); + }; + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; + } + + var _stream_transform = Transform$2; + + var _require$codes$1 = errors.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + + var Duplex = _stream_duplex; + + inherits$c.exports(Transform$2, Duplex); + + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform$2(options) { + if (!(this instanceof Transform$2)) return new Transform$2(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); + } + + function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + + Transform$2.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + + + Transform$2.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + + Transform$2.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + + + Transform$2.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform$2.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + + var _stream_passthrough = PassThrough; + + var Transform$1 = _stream_transform; + + inherits$c.exports(PassThrough, Transform$1); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform$1.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + var eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + + var _require$codes = errors.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } + + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + + function call(fn) { + fn(); + } + + function pipe(from, to) { + return from.pipe(to); + } + + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + + var pipeline_1 = pipeline; + + (function (module, exports) { + var Stream = require$$0__default$2["default"]; + if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; + } else { + exports = module.exports = _stream_readable; + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + } + }(readable, readable.exports)); + + var Buffer$9 = safeBuffer.exports.Buffer; + var Transform = readable.exports.Transform; + var inherits$7 = inherits$c.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$9.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } + + function HashBase$1 (blockSize) { + Transform.call(this); + + this._block = Buffer$9.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + + this._finalized = false; + } + + inherits$7(HashBase$1, Transform); + + HashBase$1.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$1.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$1.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$9.isBuffer(data)) data = Buffer$9.from(data, encoding); + + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } + + return this + }; + + HashBase$1.prototype._update = function () { + throw new Error('_update is not implemented') + }; + + HashBase$1.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; + + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); + + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; + + return digest + }; + + HashBase$1.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; + + var hashBase = HashBase$1; + + var Buffer$8 = require$$0__default$1["default"].Buffer; + var inherits$6 = inherits$c.exports; + var HashBase = hashBase; + + var ARRAY16 = new Array(16); + + var zl = [ + 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 zr = [ + 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 sl = [ + 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 sr = [ + 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 + ]; + + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + + function RIPEMD160 () { + HashBase.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } + + inherits$6(RIPEMD160, HashBase); + + RIPEMD160.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; + + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } + + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; + + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } + + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; + + RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$8.alloc ? Buffer$8.alloc(20) : new Buffer$8(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + var ripemd160$1 = RIPEMD160; + + var sha_js = {exports: {}}; + + var Buffer$7 = safeBuffer.exports.Buffer; + + // prototype class for hash functions + function Hash$6 (blockSize, finalSize) { + this._block = Buffer$7.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + + Hash$6.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$7.from(data, enc); + } + + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } + } + + this._len += length; + return this + }; + + Hash$6.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; + + this._block[rem] = 0x80; + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + + var bits = this._len * 8; + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; + + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash + }; + + Hash$6.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; + + var hash = Hash$6; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits$5 = inherits$c.exports; + var Hash$5 = hash; + var Buffer$6 = safeBuffer.exports.Buffer; + + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; + + Hash$5.call(this, 64, 56); + } + + inherits$5(Sha, Hash$5); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } + + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha.prototype._hash = function () { + var H = Buffer$6.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha$1 = Sha; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits$4 = inherits$c.exports; + var Hash$4 = hash; + var Buffer$5 = safeBuffer.exports.Buffer; + + var K$2 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$4.call(this, 64, 56); + } + + inherits$4(Sha1, Hash$4); + + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha1.prototype._hash = function () { + var H = Buffer$5.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha1 = Sha1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$3 = inherits$c.exports; + var Hash$3 = hash; + var Buffer$4 = safeBuffer.exports.Buffer; + + var K$1 = [ + 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 W$3 = new Array(64); + + function Sha256$1 () { + this.init(); + + this._w = W$3; // new Array(64) + + Hash$3.call(this, 64, 56); + } + + inherits$3(Sha256$1, Hash$3); + + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; + + return this + }; + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256$1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; + + Sha256$1.prototype._hash = function () { + var H = Buffer$4.allocUnsafe(32); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + + return H + }; + + var sha256$1 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$2 = inherits$c.exports; + var Sha256 = sha256$1; + var Hash$2 = hash; + var Buffer$3 = safeBuffer.exports.Buffer; + + var W$2 = new Array(64); + + function Sha224 () { + this.init(); + + this._w = W$2; // new Array(64) + + Hash$2.call(this, 64, 56); + } + + inherits$2(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this + }; + + Sha224.prototype._hash = function () { + var H = Buffer$3.allocUnsafe(28); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H + }; + + var sha224 = Sha224; + + var inherits$1 = inherits$c.exports; + var Hash$1 = hash; + var Buffer$2 = safeBuffer.exports.Buffer; + + 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 W$1 = new Array(160); + + function Sha512 () { + this.init(); + this._w = W$1; + + Hash$1.call(this, 128, 112); + } + + inherits$1(Sha512, Hash$1); + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this + }; + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } + + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } + + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } + + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } + + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w; + + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); + + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; + + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; + + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + + W[i] = Wih; + W[i + 1] = Wil; + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; + + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); + + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j]; + var Kil = K[j + 1]; + + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); + + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } + + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; + + Sha512.prototype._hash = function () { + var H = Buffer$2.allocUnsafe(64); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + + return H + }; + + var sha512 = Sha512; + + var inherits = inherits$c.exports; + var SHA512 = sha512; + var Hash = hash; + var Buffer$1 = safeBuffer.exports.Buffer; + + var W = new Array(160); + + function Sha384 () { + this.init(); + this._w = W; + + Hash.call(this, 128, 112); + } + + inherits(Sha384, SHA512); + + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; + + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; + + return this + }; + + Sha384.prototype._hash = function () { + var H = Buffer$1.allocUnsafe(48); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H + }; + + var sha384 = Sha384; + + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() + }; + + exports$1.sha = sha$1; + exports$1.sha1 = sha1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$1; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; + + var sha = sha_js.exports; + + function hashPublicKey(buffer) { + return new ripemd160$1().update(sha("sha256").update(buffer).digest()).digest(); + } + + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$3(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$3(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$3(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer.concat([ + Buffer.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$3(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$3(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer.concat([Buffer.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$2([node.parent.rightChild.hash], __read$2(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$2([node.parent.leftChild.hash], __read$2(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$2(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); + }; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); + }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + }; + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); + }; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); + } + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; + } + }; + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer.from(k.substring(2), "hex")); + } + }); + return result; + }; + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); + }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer.from([])); + this.globalMap.set(key.toString(), value); + }; + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); + }; + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); + }; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); + }; + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$4({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); + }; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; + } + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + var b = Buffer.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); + } + } + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); + } + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); + } + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer.concat([ + inputBuffer, + input.prevout, + Buffer.from([0x00]), + input.sequence, + ]) + : Buffer.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer.alloc(0), + transaction.extraData || Buffer.alloc(0), + ]); + } + return Buffer.concat([ + transaction.version, + timestamp ? timestamp : Buffer.alloc(0), + transaction.nVersionGroupId || Buffer.alloc(0), + useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } + /** + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. + */ + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; + } + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$b(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$b(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$b(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$b(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); + }; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$b(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); + }; + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$b(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); + }; + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$b(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); + }); + }; + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$b(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); + }; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$b(this, void 0, void 0, function () { + var sigs; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); + }); + }; + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$1 = 0; + var subscribers$1 = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch$1(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen$1 = function (cb) { + subscribers$1.push(cb); + return function () { + var i = subscribers$1.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; + subscribers$1.pop(); + } + }; + }; + function dispatch$1(log) { + for (var i = 0; i < subscribers$1.length; i++) { + try { + subscribers$1[i](log); + } + catch (e) { + console.error(e); + } + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen$1; + } + + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$a(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$a(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$3({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + + /** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var NODE_ENV = process.env.NODE_ENV; + + var invariant = function(condition, format, a, b, c, d, e, f) { + if (NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var invariant_1 = invariant; + + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$9(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$9(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$9(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$9(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$9(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer.concat([ + transaction.version, + transaction.timestamp || Buffer.alloc(0), + transaction.nVersionGroupId || Buffer.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer.compare(version, Buffer.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer.from([0x00]) + : Buffer.alloc(0); + data = Buffer.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer.concat([ + output.amount, + isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer.concat(endData); + extraPart = isDecred + ? data + : Buffer.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer.concat([locktime, extraPart || Buffer.alloc(0)]))]; + case 20: + res = _c.sent(); + invariant_1(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$8(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$8(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer.concat([ + transaction.version, + transaction.timestamp || Buffer.alloc(0), + transaction.nVersionGroupId || Buffer.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$4(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer.from([0x01, inputValue.length]); + } + else { + prefix = Buffer.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer.from([0x00]); + } + } + data = Buffer.concat([ + prefix, + inputValue, + isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha("sha256") + .update(sha("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer.alloc(1); + prefixBuffer[0] = prefix; + return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), + Buffer.from([sigHashType]), + ]) + : Buffer.concat([ + pathsBuffer, + Buffer.from([0x00]), + lockTimeBuffer, + Buffer.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$7(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$7(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$6(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + invariant_1(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } + + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$5(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$2(__assign$2({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer.alloc(0); + nullPrevout = Buffer.alloc(0); + defaultVersion = Buffer.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer.concat([ + Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer.concat([ + Buffer.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer.alloc(1); + keySize = Buffer.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer.concat([ + Buffer.from("02", "hex"), + Buffer.from([signatures[i].length]), + signatures[i], + Buffer.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer.concat([witness, tmpScriptData]); + } + result = Buffer.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer.concat([ + result, + targetTransaction.nExpiryHeight || Buffer.alloc(0), + targetTransaction.extraData || Buffer.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer.concat([ + decredWitness_1, + Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer.from([0x00, 0x00, 0x00, 0x00]), + Buffer.from([0xff, 0xff, 0xff, 0xff]), + Buffer.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } + + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$4(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$4(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$4(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } + + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$3(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$3(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$1(__assign$1({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer.alloc(0); + nullPrevout = Buffer.alloc(0); + defaultVersion = Buffer.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer.from(trustedInput, "hex") + : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$1(__assign$1({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } + + var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$2(this, void 0, void 0, function () { + var res; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$2(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$2(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign(__assign({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer.concat([ + Buffer.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer.concat([ + asBufferUInt32BE(version), + Buffer.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$1().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$1(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$1([], __read$1(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$1([], __read$1(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$1([], __read$1(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer.from(request.subarray(1))); + this.progressCallback(); + return Buffer.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer.from([known_preimage[i]])); + } + } + return Buffer.concat([ + preimage_len_varint, + Buffer.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray([], __read(proof.slice(-n_leftover_elements)), false)); + } + return Buffer.concat(__spreadArray([ + mt.getLeafHash(leaf_index), + Buffer.from([proof.length]), + Buffer.from([n_response_elements]) + ], __read(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer.concat([Buffer.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer.concat(__spreadArray([ + Buffer.from([n_returned_elements]), + Buffer.from([element_len]) + ], __read(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$1(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } + } + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$1(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer.concat([Buffer.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); + + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$1(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$1(this, void 0, void 0, function () { + var response; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer.concat([ + Buffer.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$1(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer.concat([ + Buffer.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer.alloc(32, 0), + Buffer.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$1(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$1(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$1(this, void 0, void 0, function () { + return __generator$1(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer.alloc(0); + var nExpiryHeight = Buffer.alloc(0); + var nVersionGroupId = Buffer.alloc(0); + var extraData = Buffer.alloc(0); + var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); + var transaction = Buffer.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer.from([0x02, 0x00, 0x00, 0x00])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer.alloc(0); + var tree = Buffer.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } + + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@backpacker69/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + var TransportWebUSB$2 = {}; + + var Transport$1 = {}; + + var lib$2 = {}; + + var helpers = {}; + + Object.defineProperty(helpers, "__esModule", { + value: true + }); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + /* eslint-disable no-continue */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + + var errorClasses = {}; + var deserializers = {}; + + helpers.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { + deserializers[name] = deserializer; + }; + + var createCustomErrorClass = helpers.createCustomErrorClass = function createCustomErrorClass(name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + // $FlowFixMe + C.prototype = new Error(); + + errorClasses[name] = C; + // $FlowFixMe we can't easily type a subset of Error for now... + return C; + }; + + // inspired from https://github.com/programble/errio/blob/master/index.js + helpers.deserializeError = function deserializeError(object) { + if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } catch (e) { + // nothing + } + + var error = void 0; + if (typeof object.name === "string") { + var _object = object, + name = _object.name; + + var des = deserializers[name]; + if (des) { + error = des(object); + } else { + var _constructor = name === "Error" ? Error : errorClasses[name]; + + if (!_constructor) { + console.warn("deserializing an unknown class '" + name + "'"); + _constructor = createCustomErrorClass(name); + } + + error = Object.create(_constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } else { + error = new Error(object.message); + } + + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + helpers.serializeError = function serializeError(value) { + if (!value) return value; + if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var to = {}; + seen.push(from); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var key = _step.value; + + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + Object.defineProperty(lib$2, "__esModule", { + value: true + }); + lib$2.StatusCodes = lib$2.DBNotReset = lib$2.DBWrongPassword = lib$2.NoDBPathGiven = lib$2.FirmwareOrAppUpdateRequired = lib$2.LedgerAPI5xx = lib$2.LedgerAPI4xx = lib$2.GenuineCheckFailed = lib$2.PairingFailed = lib$2.SyncError = lib$2.FeeTooHigh = lib$2.FeeRequired = lib$2.FeeNotLoaded = lib$2.CantScanQRCode = lib$2.ETHAddressNonEIP = lib$2.WrongAppForCurrency = lib$2.WrongDeviceForAccount = lib$2.WebsocketConnectionFailed = lib$2.WebsocketConnectionError = lib$2.DeviceShouldStayInApp = lib$2.TransportWebUSBGestureRequired = lib$2.TransportInterfaceNotAvailable = lib$2.TransportOpenUserCancelled = lib$2.UserRefusedOnDevice = lib$2.UserRefusedAllowManager = lib$2.UserRefusedFirmwareUpdate = lib$2.UserRefusedAddress = lib$2.UserRefusedDeviceNameChange = lib$2.UpdateYourApp = lib$2.UnavailableTezosOriginatedAccountSend = lib$2.UnavailableTezosOriginatedAccountReceive = lib$2.RecipientRequired = lib$2.MCUNotGenuineToDashboard = lib$2.UnexpectedBootloader = lib$2.TimeoutTagged = lib$2.RecommendUndelegation = lib$2.RecommendSubAccountsToEmpty = lib$2.PasswordIncorrectError = lib$2.PasswordsDontMatchError = lib$2.GasLessThanEstimate = lib$2.NotSupportedLegacyAddress = lib$2.NotEnoughGas = lib$2.NoAccessToCamera = lib$2.NotEnoughBalanceBecauseDestinationNotCreated = lib$2.NotEnoughSpendableBalance = lib$2.NotEnoughBalanceInParentAccount = lib$2.NotEnoughBalanceToDelegate = lib$2.NotEnoughBalance = lib$2.NoAddressesFound = lib$2.NetworkDown = lib$2.ManagerUninstallBTCDep = lib$2.ManagerNotEnoughSpaceError = lib$2.ManagerFirmwareNotEnoughSpaceError = lib$2.ManagerDeviceLockedError = lib$2.ManagerAppDepUninstallRequired = lib$2.ManagerAppDepInstallRequired = lib$2.ManagerAppRelyOnBTCError = lib$2.ManagerAppAlreadyInstalledError = lib$2.LedgerAPINotAvailable = lib$2.LedgerAPIErrorWithMessage = lib$2.LedgerAPIError = lib$2.UnknownMCU = lib$2.LatestMCUInstalledError = lib$2.InvalidAddressBecauseDestinationIsAlsoSource = lib$2.InvalidAddress = lib$2.InvalidXRPTag = lib$2.HardResetFail = lib$2.FeeEstimationFailed = lib$2.EthAppPleaseEnableContractData = lib$2.EnpointConfigError = lib$2.DisconnectedDeviceDuringOperation = lib$2.DisconnectedDevice = lib$2.DeviceSocketNoBulkStatus = lib$2.DeviceSocketFail = lib$2.DeviceNameInvalid = lib$2.DeviceHalted = lib$2.DeviceInOSUExpected = lib$2.DeviceOnDashboardUnexpected = lib$2.DeviceOnDashboardExpected = lib$2.DeviceNotGenuineError = lib$2.DeviceGenuineSocketEarlyClose = lib$2.DeviceAppVerifyNotSupported = lib$2.CurrencyNotSupported = lib$2.CashAddrNotSupported = lib$2.CantOpenDevice = lib$2.BtcUnmatchedApp = lib$2.BluetoothRequired = lib$2.AmountRequired = lib$2.AccountNotSupported = lib$2.AccountNameRequiredError = lib$2.addCustomErrorDeserializer = lib$2.createCustomErrorClass = lib$2.deserializeError = lib$2.serializeError = undefined; + lib$2.TransportError = TransportError; + lib$2.getAltStatusMessage = getAltStatusMessage; + lib$2.TransportStatusError = TransportStatusError; + + var _helpers = helpers; + + lib$2.serializeError = _helpers.serializeError; + lib$2.deserializeError = _helpers.deserializeError; + lib$2.createCustomErrorClass = _helpers.createCustomErrorClass; + lib$2.addCustomErrorDeserializer = _helpers.addCustomErrorDeserializer; + lib$2.AccountNameRequiredError = (0, _helpers.createCustomErrorClass)("AccountNameRequired"); + lib$2.AccountNotSupported = (0, _helpers.createCustomErrorClass)("AccountNotSupported"); + lib$2.AmountRequired = (0, _helpers.createCustomErrorClass)("AmountRequired"); + lib$2.BluetoothRequired = (0, _helpers.createCustomErrorClass)("BluetoothRequired"); + lib$2.BtcUnmatchedApp = (0, _helpers.createCustomErrorClass)("BtcUnmatchedApp"); + lib$2.CantOpenDevice = (0, _helpers.createCustomErrorClass)("CantOpenDevice"); + lib$2.CashAddrNotSupported = (0, _helpers.createCustomErrorClass)("CashAddrNotSupported"); + lib$2.CurrencyNotSupported = (0, _helpers.createCustomErrorClass)("CurrencyNotSupported"); + lib$2.DeviceAppVerifyNotSupported = (0, _helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); + lib$2.DeviceGenuineSocketEarlyClose = (0, _helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); + lib$2.DeviceNotGenuineError = (0, _helpers.createCustomErrorClass)("DeviceNotGenuine"); + lib$2.DeviceOnDashboardExpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); + lib$2.DeviceOnDashboardUnexpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); + lib$2.DeviceInOSUExpected = (0, _helpers.createCustomErrorClass)("DeviceInOSUExpected"); + lib$2.DeviceHalted = (0, _helpers.createCustomErrorClass)("DeviceHalted"); + lib$2.DeviceNameInvalid = (0, _helpers.createCustomErrorClass)("DeviceNameInvalid"); + lib$2.DeviceSocketFail = (0, _helpers.createCustomErrorClass)("DeviceSocketFail"); + lib$2.DeviceSocketNoBulkStatus = (0, _helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); + lib$2.DisconnectedDevice = (0, _helpers.createCustomErrorClass)("DisconnectedDevice"); + lib$2.DisconnectedDeviceDuringOperation = (0, _helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); + lib$2.EnpointConfigError = (0, _helpers.createCustomErrorClass)("EnpointConfig"); + lib$2.EthAppPleaseEnableContractData = (0, _helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); + lib$2.FeeEstimationFailed = (0, _helpers.createCustomErrorClass)("FeeEstimationFailed"); + lib$2.HardResetFail = (0, _helpers.createCustomErrorClass)("HardResetFail"); + lib$2.InvalidXRPTag = (0, _helpers.createCustomErrorClass)("InvalidXRPTag"); + lib$2.InvalidAddress = (0, _helpers.createCustomErrorClass)("InvalidAddress"); + lib$2.InvalidAddressBecauseDestinationIsAlsoSource = (0, _helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); + lib$2.LatestMCUInstalledError = (0, _helpers.createCustomErrorClass)("LatestMCUInstalledError"); + lib$2.UnknownMCU = (0, _helpers.createCustomErrorClass)("UnknownMCU"); + lib$2.LedgerAPIError = (0, _helpers.createCustomErrorClass)("LedgerAPIError"); + lib$2.LedgerAPIErrorWithMessage = (0, _helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); + lib$2.LedgerAPINotAvailable = (0, _helpers.createCustomErrorClass)("LedgerAPINotAvailable"); + lib$2.ManagerAppAlreadyInstalledError = (0, _helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); + lib$2.ManagerAppRelyOnBTCError = (0, _helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); + lib$2.ManagerAppDepInstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); + lib$2.ManagerAppDepUninstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); + lib$2.ManagerDeviceLockedError = (0, _helpers.createCustomErrorClass)("ManagerDeviceLocked"); + lib$2.ManagerFirmwareNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); + lib$2.ManagerNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); + lib$2.ManagerUninstallBTCDep = (0, _helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); + lib$2.NetworkDown = (0, _helpers.createCustomErrorClass)("NetworkDown"); + lib$2.NoAddressesFound = (0, _helpers.createCustomErrorClass)("NoAddressesFound"); + lib$2.NotEnoughBalance = (0, _helpers.createCustomErrorClass)("NotEnoughBalance"); + lib$2.NotEnoughBalanceToDelegate = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); + lib$2.NotEnoughBalanceInParentAccount = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); + lib$2.NotEnoughSpendableBalance = (0, _helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); + lib$2.NotEnoughBalanceBecauseDestinationNotCreated = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); + lib$2.NoAccessToCamera = (0, _helpers.createCustomErrorClass)("NoAccessToCamera"); + lib$2.NotEnoughGas = (0, _helpers.createCustomErrorClass)("NotEnoughGas"); + lib$2.NotSupportedLegacyAddress = (0, _helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); + lib$2.GasLessThanEstimate = (0, _helpers.createCustomErrorClass)("GasLessThanEstimate"); + lib$2.PasswordsDontMatchError = (0, _helpers.createCustomErrorClass)("PasswordsDontMatch"); + lib$2.PasswordIncorrectError = (0, _helpers.createCustomErrorClass)("PasswordIncorrect"); + lib$2.RecommendSubAccountsToEmpty = (0, _helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); + lib$2.RecommendUndelegation = (0, _helpers.createCustomErrorClass)("RecommendUndelegation"); + lib$2.TimeoutTagged = (0, _helpers.createCustomErrorClass)("TimeoutTagged"); + lib$2.UnexpectedBootloader = (0, _helpers.createCustomErrorClass)("UnexpectedBootloader"); + lib$2.MCUNotGenuineToDashboard = (0, _helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); + lib$2.RecipientRequired = (0, _helpers.createCustomErrorClass)("RecipientRequired"); + lib$2.UnavailableTezosOriginatedAccountReceive = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); + lib$2.UnavailableTezosOriginatedAccountSend = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); + lib$2.UpdateYourApp = (0, _helpers.createCustomErrorClass)("UpdateYourApp"); + lib$2.UserRefusedDeviceNameChange = (0, _helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); + lib$2.UserRefusedAddress = (0, _helpers.createCustomErrorClass)("UserRefusedAddress"); + lib$2.UserRefusedFirmwareUpdate = (0, _helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); + lib$2.UserRefusedAllowManager = (0, _helpers.createCustomErrorClass)("UserRefusedAllowManager"); + lib$2.UserRefusedOnDevice = (0, _helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + lib$2.TransportOpenUserCancelled = (0, _helpers.createCustomErrorClass)("TransportOpenUserCancelled"); + lib$2.TransportInterfaceNotAvailable = (0, _helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); + lib$2.TransportWebUSBGestureRequired = (0, _helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); + lib$2.DeviceShouldStayInApp = (0, _helpers.createCustomErrorClass)("DeviceShouldStayInApp"); + lib$2.WebsocketConnectionError = (0, _helpers.createCustomErrorClass)("WebsocketConnectionError"); + lib$2.WebsocketConnectionFailed = (0, _helpers.createCustomErrorClass)("WebsocketConnectionFailed"); + lib$2.WrongDeviceForAccount = (0, _helpers.createCustomErrorClass)("WrongDeviceForAccount"); + lib$2.WrongAppForCurrency = (0, _helpers.createCustomErrorClass)("WrongAppForCurrency"); + lib$2.ETHAddressNonEIP = (0, _helpers.createCustomErrorClass)("ETHAddressNonEIP"); + lib$2.CantScanQRCode = (0, _helpers.createCustomErrorClass)("CantScanQRCode"); + lib$2.FeeNotLoaded = (0, _helpers.createCustomErrorClass)("FeeNotLoaded"); + lib$2.FeeRequired = (0, _helpers.createCustomErrorClass)("FeeRequired"); + lib$2.FeeTooHigh = (0, _helpers.createCustomErrorClass)("FeeTooHigh"); + lib$2.SyncError = (0, _helpers.createCustomErrorClass)("SyncError"); + lib$2.PairingFailed = (0, _helpers.createCustomErrorClass)("PairingFailed"); + lib$2.GenuineCheckFailed = (0, _helpers.createCustomErrorClass)("GenuineCheckFailed"); + lib$2.LedgerAPI4xx = (0, _helpers.createCustomErrorClass)("LedgerAPI4xx"); + lib$2.LedgerAPI5xx = (0, _helpers.createCustomErrorClass)("LedgerAPI5xx"); + lib$2.FirmwareOrAppUpdateRequired = (0, _helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); + + // db stuff, no need to translate + lib$2.NoDBPathGiven = (0, _helpers.createCustomErrorClass)("NoDBPathGiven"); + lib$2.DBWrongPassword = (0, _helpers.createCustomErrorClass)("DBWrongPassword"); + lib$2.DBNotReset = (0, _helpers.createCustomErrorClass)("DBNotReset"); + + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + //$FlowFixMe + TransportError.prototype = new Error(); + + (0, _helpers.addCustomErrorDeserializer)("TransportError", function (e) { + return new TransportError(e.message, e.id); + }); + + var StatusCodes = lib$2.StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { + return StatusCodes[k] === statusCode; + }) || "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + //$FlowFixMe + TransportStatusError.prototype = new Error(); + + (0, _helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { + return new TransportStatusError(e.statusCode); + }); + + Object.defineProperty(Transport$1, "__esModule", { + value: true + }); + Transport$1.getAltStatusMessage = Transport$1.StatusCodes = Transport$1.TransportStatusError = Transport$1.TransportError = undefined; + + var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _events2 = require$$0__default$3["default"]; + + var _events3 = _interopRequireDefault$1(_events2); + + var _errors$2 = lib$2; + + function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + function _asyncToGenerator$2(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + Transport$1.TransportError = _errors$2.TransportError; + Transport$1.TransportStatusError = _errors$2.TransportStatusError; + Transport$1.StatusCodes = _errors$2.StatusCodes; + Transport$1.getAltStatusMessage = _errors$2.getAltStatusMessage; + + /** + */ + + + /** + */ + + + /** + * type: add or remove event + * descriptor: a parameter that can be passed to open(descriptor) + * deviceModel: device info on the model (is it a nano s, nano x, ...) + * device: transport specific device info + */ + + /** + */ + + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport = function () { + function Transport() { + var _this = this; + + _classCallCheck$1(this, Transport); + + this.exchangeTimeout = 30000; + this._events = new _events3.default(); + + this.send = function () { + var _ref = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { + var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); + var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [_errors$2.StatusCodes.OK]; + var response, sw; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(data.length >= 256)) { + _context.next = 2; + break; + } + + throw new _errors$2.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + + case 2: + _context.next = 4; + return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); + + case 4: + response = _context.sent; + sw = response.readUInt16BE(response.length - 2); + + if (statusList.some(function (s) { + return s === sw; + })) { + _context.next = 8; + break; + } + + throw new _errors$2.TransportStatusError(sw); + + case 8: + return _context.abrupt("return", response); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee, _this); + })); + + return function (_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; + }(); + + this.exchangeAtomicImpl = function () { + var _ref2 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { + var resolveBusy, busyPromise, res; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!_this.exchangeBusyPromise) { + _context2.next = 2; + break; + } + + throw new _errors$2.TransportError("Transport race condition", "RaceCondition"); + + case 2: + resolveBusy = void 0; + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + + _this.exchangeBusyPromise = busyPromise; + _context2.prev = 5; + _context2.next = 8; + return f(); + + case 8: + res = _context2.sent; + return _context2.abrupt("return", res); + + case 10: + _context2.prev = 10; + + if (resolveBusy) resolveBusy(); + _this.exchangeBusyPromise = null; + return _context2.finish(10); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, _this, [[5,, 10, 14]]); + })); + + return function (_x7) { + return _ref2.apply(this, arguments); + }; + }(); + + this._appAPIlock = null; + } + + /** + * Statically check if a transport is supported on the user's platform/browser. + */ + + + /** + * List once all available descriptors. For a better granularity, checkout `listen()`. + * @return a promise of descriptors + * @example + * TransportFoo.list().then(descriptors => ...) + */ + + + /** + * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) + * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. + * each listen() call will first emit all potential device already connected and then will emit events can come over times, + * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. + * @param observer is an object with a next, error and complete function (compatible with observer pattern) + * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. + * @example + const sub = TransportFoo.listen({ + next: e => { + if (e.type==="add") { + sub.unsubscribe(); + const transport = await TransportFoo.open(e.descriptor); + ... + } + }, + error: error => {}, + complete: () => {} + }) + */ + + + /** + * attempt to create a Transport instance with potentially a descriptor. + * @param descriptor: the descriptor to open the transport with. + * @param timeout: an optional timeout + * @return a Promise of Transport instance + * @example + TransportFoo.open(descriptor).then(transport => ...) + */ + + + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + + + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + + + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + + + _createClass$1(Transport, [{ + key: "on", + + + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + value: function on(eventName, cb) { + this._events.on(eventName, cb); + } + + /** + * Stop listening to an event on an instance of transport. + */ + + }, { + key: "off", + value: function off(eventName, cb) { + this._events.removeListener(eventName, cb); + } + }, { + key: "emit", + value: function emit(event) { + var _events; + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); + } + + /** + * Enable or not logs of the binary exchange + */ + + }, { + key: "setDebugMode", + value: function setDebugMode() { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + } + + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + + }, { + key: "setExchangeTimeout", + value: function setExchangeTimeout(exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + } + + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + + }, { + key: "decorateAppAPIMethods", + value: function decorateAppAPIMethods(self, methods, scrambleKey) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var methodName = _step.value; + + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, { + key: "decorateAppAPIMethod", + value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { + var _this2 = this; + + return function () { + var _ref3 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var _appAPIlock; + + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _appAPIlock = _this2._appAPIlock; + + if (!_appAPIlock) { + _context3.next = 3; + break; + } + + return _context3.abrupt("return", Promise.reject(new _errors$2.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); + + case 3: + _context3.prev = 3; + + _this2._appAPIlock = methodName; + _this2.setScrambleKey(scrambleKey); + _context3.next = 8; + return f.apply(ctx, args); + + case 8: + return _context3.abrupt("return", _context3.sent); + + case 9: + _context3.prev = 9; + + _this2._appAPIlock = null; + return _context3.finish(9); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, _this2, [[3,, 9, 12]]); + })); + + return function () { + return _ref3.apply(this, arguments); + }; + }(); + } + }], [{ + key: "create", + + + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + value: function create() { + var _this3 = this; + + var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; + var listenTimeout = arguments[1]; + + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this3.listen({ + next: function next(e) { + found = true; + if (sub) sub.unsubscribe(); + if (listenTimeoutId) clearTimeout(listenTimeoutId); + _this3.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function error(e) { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function complete() { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + if (!found) { + reject(new _errors$2.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout ? setTimeout(function () { + sub.unsubscribe(); + reject(new _errors$2.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) : null; + }); + } + + // $FlowFixMe + + }]); + + return Transport; + }(); + + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + Transport$1.default = Transport; + + var hidFraming = {}; + + Object.defineProperty(hidFraming, "__esModule", { + value: true + }); + + var _errors$1 = lib$2; + + var Tag = 0x05; + + function asUInt16BE(value) { + var b = Buffer.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + + var initialAcc = { + data: Buffer.alloc(0), + dataLength: 0, + sequence: 0 + }; + + /** + * + */ + var createHIDframing = function createHIDframing(channel, packetSize) { + return { + makeBlocks: function makeBlocks(apdu) { + var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer.concat([data, // fill data with padding + Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); + + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function reduceResponse(acc, chunk) { + var _ref = acc || initialAcc, + data = _ref.data, + dataLength = _ref.dataLength, + sequence = _ref.sequence; + + if (chunk.readUInt16BE(0) !== channel) { + throw new _errors$1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new _errors$1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new _errors$1.TransportError("Invalid sequence", "InvalidSequence"); + } + + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function getReducedResult(acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + + hidFraming.default = createHIDframing; + + var lib$1 = {}; + + Object.defineProperty(lib$1, "__esModule", { + value: true + }); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + /** + * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) + * + ** Model + * Ledger Nano S : 0x10 + * Ledger Blue : 0x00 + * Ledger Nano X : 0x40 + * + ** Interface support bitfield + * Generic HID : 0x01 + * Keyboard HID : 0x02 + * U2F : 0x04 + * CCID : 0x08 + * WebUSB : 0x10 + */ + + lib$1.IIGenericHID = 0x01; + lib$1.IIKeyboardHID = 0x02; + lib$1.IIU2F = 0x04; + lib$1.IICCID = 0x08; + lib$1.IIWebUSB = 0x10; + + var devices = { + blue: { + id: "blue", + productName: "Ledger Blue", + productIdMM: 0x00, + legacyUsbProductId: 0x0000, + usbOnly: true, + memorySize: 480 * 1024, + blockSize: 4 * 1024 + }, + nanoS: { + id: "nanoS", + productName: "Ledger Nano S", + productIdMM: 0x10, + legacyUsbProductId: 0x0001, + usbOnly: true, + memorySize: 320 * 1024, + blockSize: 4 * 1024 + }, + nanoX: { + id: "nanoX", + productName: "Ledger Nano X", + productIdMM: 0x40, + legacyUsbProductId: 0x0004, + usbOnly: false, + memorySize: 2 * 1024 * 1024, + blockSize: 4 * 1024, + bluetoothSpec: [{ + // this is the legacy one (prototype version). we will eventually drop it. + serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", + notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", + writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" + }, { + serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", + notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", + writeUuid: "13d63400-2c97-0004-0002-4c6564676572" + }] + } + }; + + var productMap = { + Blue: "blue", + "Nano S": "nanoS", + "Nano X": "nanoX" + }; + + // $FlowFixMe + var devicesList = Object.values(devices); + + /** + * + */ + lib$1.ledgerUSBVendorId = 0x2c97; + + /** + * + */ + lib$1.getDeviceModel = function getDeviceModel(id) { + var info = devices[id]; + if (!info) throw new Error("device '" + id + "' does not exist"); + return info; + }; + + /** + * + */ + lib$1.identifyUSBProductId = function identifyUSBProductId(usbProductId) { + var legacy = devicesList.find(function (d) { + return d.legacyUsbProductId === usbProductId; + }); + if (legacy) return legacy; + + var mm = usbProductId >> 8; + var deviceModel = devicesList.find(function (d) { + return d.productIdMM === mm; + }); + return deviceModel; + }; + + lib$1.identifyProductName = function identifyProductName(productName) { + var productId = productMap[productName]; + var deviceModel = devicesList.find(function (d) { + return d.id === productId; + }); + + return deviceModel; + }; + + var bluetoothServices = []; + var serviceUuidToInfos = {}; + + for (var _id in devices) { + var _deviceModel = devices[_id]; + var _bluetoothSpec = _deviceModel.bluetoothSpec; + + if (_bluetoothSpec) { + for (var i = 0; i < _bluetoothSpec.length; i++) { + var spec = _bluetoothSpec[i]; + bluetoothServices.push(spec.serviceUuid); + serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); + } + } + } + + /** + * + */ + lib$1.getBluetoothServiceUuids = function getBluetoothServiceUuids() { + return bluetoothServices; + }; + + /** + * + */ + lib$1.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { + return serviceUuidToInfos[uuid.toLowerCase()]; + }; + + var lib = {}; + + Object.defineProperty(lib, "__esModule", { + value: true + }); + + + /** + * A Log object + */ + var id = 0; + var subscribers = []; + + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + lib.log = function log(type, message, data) { + var obj = { type: type, id: String(++id), date: new Date() }; + if (message) obj.message = message; + if (data) obj.data = data; + dispatch(obj); + }; + + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = lib.listen = function listen(cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } catch (e) { + console.error(e); + } + } + } + + // for debug purpose + commonjsGlobal.__ledgerLogsListen = listen; + + var webusb = {}; + + Object.defineProperty(webusb, "__esModule", { + value: true + }); + webusb.isSupported = webusb.getFirstLedgerDevice = webusb.getLedgerDevices = webusb.requestLedgerDevice = undefined; + + var requestLedgerDevice = webusb.requestLedgerDevice = function () { + var _ref = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + var device; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return navigator.usb.requestDevice({ filters: ledgerDevices }); + + case 2: + device = _context.sent; + return _context.abrupt("return", device); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function requestLedgerDevice() { + return _ref.apply(this, arguments); + }; + }(); + + var getLedgerDevices = webusb.getLedgerDevices = function () { + var _ref2 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var devices; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return navigator.usb.getDevices(); + + case 2: + devices = _context2.sent; + return _context2.abrupt("return", devices.filter(function (d) { + return d.vendorId === _devices$1.ledgerUSBVendorId; + })); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function getLedgerDevices() { + return _ref2.apply(this, arguments); + }; + }(); + + webusb.getFirstLedgerDevice = function () { + var _ref3 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var existingDevices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getLedgerDevices(); + + case 2: + existingDevices = _context3.sent; + + if (!(existingDevices.length > 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", existingDevices[0]); + + case 5: + return _context3.abrupt("return", requestLedgerDevice()); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function getFirstLedgerDevice() { + return _ref3.apply(this, arguments); + }; + }(); + + var _devices$1 = lib$1; + + function _asyncToGenerator$1(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + var ledgerDevices = [{ vendorId: _devices$1.ledgerUSBVendorId }]; + + webusb.isSupported = function isSupported() { + return Promise.resolve(!!navigator && + // $FlowFixMe + !!navigator.usb && typeof navigator.usb.getDevices === "function"); + }; + + Object.defineProperty(TransportWebUSB$2, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _hwTransport = Transport$1; + + var _hwTransport2 = _interopRequireDefault(_hwTransport); + + var _hidFraming = hidFraming; + + var _hidFraming2 = _interopRequireDefault(_hidFraming); + + var _devices = lib$1; + + var _logs = lib; + + var _errors = lib$2; + + var _webusb = webusb; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var configurationValue = 1; + var endpointNumber = 3; + + /** + * WebUSB Transport implementation + * @example + * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ + + var TransportWebUSB = function (_Transport) { + _inherits(TransportWebUSB, _Transport); + + function TransportWebUSB(device, interfaceNumber) { + _classCallCheck(this, TransportWebUSB); + + var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); + + _initialiseProps.call(_this); + + _this.device = device; + _this.interfaceNumber = interfaceNumber; + _this.deviceModel = (0, _devices.identifyUSBProductId)(device.productId); + return _this; + } + + /** + * Check if WebUSB transport is supported. + */ + + + /** + * List the WebUSB devices that was previously authorized by the user. + */ + + + /** + * Actively listen to WebUSB devices and emit ONE device + * that was either accepted before, if not it will trigger the native permission UI. + * + * Important: it must be called in the context of a UI click! + */ + + + _createClass(TransportWebUSB, [{ + key: "close", + + + /** + * Release the transport device + */ + value: function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.exchangeBusyPromise; + + case 2: + _context.next = 4; + return this.device.releaseInterface(this.interfaceNumber); + + case 4: + _context.next = 6; + return this.device.reset(); + + case 6: + _context.next = 8; + return this.device.close(); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _ref.apply(this, arguments); + } + + return close; + }() + + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + + }, { + key: "setScrambleKey", + value: function setScrambleKey() {} + }], [{ + key: "request", + + + /** + * Similar to create() except it will always display the device permission (even if some devices are already accepted). + */ + value: function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var device; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _webusb.requestLedgerDevice)(); + + case 2: + device = _context2.sent; + return _context2.abrupt("return", TransportWebUSB.open(device)); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function request() { + return _ref2.apply(this, arguments); + } + + return request; + }() + + /** + * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). + */ + + }, { + key: "openConnected", + value: function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var devices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _webusb.getLedgerDevices)(); + + case 2: + devices = _context3.sent; + + if (!(devices.length === 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", null); + + case 5: + return _context3.abrupt("return", TransportWebUSB.open(devices[0])); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function openConnected() { + return _ref3.apply(this, arguments); + } + + return openConnected; + }() + + /** + * Create a Ledger transport with a USBDevice + */ + + }, { + key: "open", + value: function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { + var iface, interfaceNumber, transport, onDisconnect; + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return device.open(); + + case 2: + if (!(device.configuration === null)) { + _context4.next = 5; + break; + } + + _context4.next = 5; + return device.selectConfiguration(configurationValue); + + case 5: + _context4.next = 7; + return device.reset(); + + case 7: + iface = device.configurations[0].interfaces.find(function (_ref5) { + var alternates = _ref5.alternates; + return alternates.some(function (a) { + return a.interfaceClass === 255; + }); + }); + + if (iface) { + _context4.next = 10; + break; + } + + throw new _errors.TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); + + case 10: + interfaceNumber = iface.interfaceNumber; + _context4.prev = 11; + _context4.next = 14; + return device.claimInterface(interfaceNumber); + + case 14: + _context4.next = 21; + break; + + case 16: + _context4.prev = 16; + _context4.t0 = _context4["catch"](11); + _context4.next = 20; + return device.close(); + + case 20: + throw new _errors.TransportInterfaceNotAvailable(_context4.t0.message); + + case 21: + transport = new TransportWebUSB(device, interfaceNumber); + + onDisconnect = function onDisconnect(e) { + if (device === e.device) { + // $FlowFixMe + navigator.usb.removeEventListener("disconnect", onDisconnect); + transport._emitDisconnect(new _errors.DisconnectedDevice()); + } + }; + // $FlowFixMe + + + navigator.usb.addEventListener("disconnect", onDisconnect); + return _context4.abrupt("return", transport); + + case 25: + case "end": + return _context4.stop(); + } + } + }, _callee4, this, [[11, 16]]); + })); + + function open(_x) { + return _ref4.apply(this, arguments); + } + + return open; + }() + }]); + + return TransportWebUSB; + }(_hwTransport2.default); + + TransportWebUSB.isSupported = _webusb.isSupported; + TransportWebUSB.list = _webusb.getLedgerDevices; + + TransportWebUSB.listen = function (observer) { + var unsubscribed = false; + (0, _webusb.getFirstLedgerDevice)().then(function (device) { + if (!unsubscribed) { + var deviceModel = (0, _devices.identifyUSBProductId)(device.productId); + observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); + observer.complete(); + } + }, function (error) { + if (window.DOMException && error instanceof window.DOMException && error.code === 18) { + observer.error(new _errors.TransportWebUSBGestureRequired(error.message)); + } else { + observer.error(new _errors.TransportOpenUserCancelled(error.message)); + } + }); + function unsubscribe() { + unsubscribed = true; + } + return { unsubscribe: unsubscribe }; + }; + + var _initialiseProps = function _initialiseProps() { + var _this2 = this; + + this.channel = Math.floor(Math.random() * 0xffff); + this.packetSize = 64; + this._disconnectEmitted = false; + + this._emitDisconnect = function (e) { + if (_this2._disconnectEmitted) return; + _this2._disconnectEmitted = true; + _this2.emit("disconnect", e); + }; + + this.exchange = function (apdu) { + return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { + var channel, packetSize, framing, blocks, i, result, acc, r, buffer; + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + channel = _this2.channel, packetSize = _this2.packetSize; + + (0, _logs.log)("apdu", "=> " + apdu.toString("hex")); + + framing = (0, _hidFraming2.default)(channel, packetSize); + + // Write... + + blocks = framing.makeBlocks(apdu); + i = 0; + + case 5: + if (!(i < blocks.length)) { + _context5.next = 12; + break; + } + + (0, _logs.log)("hid-frame", "=> " + blocks[i].toString("hex")); + _context5.next = 9; + return _this2.device.transferOut(endpointNumber, blocks[i]); + + case 9: + i++; + _context5.next = 5; + break; + + case 12: + + // Read... + result = void 0; + acc = void 0; + + case 14: + if (result = framing.getReducedResult(acc)) { + _context5.next = 23; + break; + } + + _context5.next = 17; + return _this2.device.transferIn(endpointNumber, packetSize); + + case 17: + r = _context5.sent; + buffer = Buffer.from(r.data.buffer); + + (0, _logs.log)("hid-frame", "<= " + buffer.toString("hex")); + acc = framing.reduceResponse(acc, buffer); + _context5.next = 14; + break; + + case 23: + + (0, _logs.log)("apdu", "<= " + result.toString("hex")); + return _context5.abrupt("return", result); + + case 25: + case "end": + return _context5.stop(); + } + } + }, _callee5, _this2); + }))).catch(function (e) { + if (e && e.message && e.message.includes("disconnected")) { + _this2._emitDisconnect(e); + throw new _errors.DisconnectedDeviceDuringOperation(e.message); + } + throw e; + }); + }; + }; + + var _default = TransportWebUSB$2.default = TransportWebUSB; + + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': _default + }, [TransportWebUSB$2])); + + exports.Btc = Btc$1; + exports.TransportWebUSB = TransportWebUSB$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); //# sourceMappingURL=build.js.map window.Btc = NewLedger.Btc.default; From b4a1d9ec23581ca9ac0ed9d066838b3d10d4cb13 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 15:06:53 +1100 Subject: [PATCH 13/78] ... --- js/ledger.js | 30905 +------------------------------------------------ 1 file changed, 3 insertions(+), 30902 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index a12e852e..27a3d3b7 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,30908 +2,9 @@ window.global = window; window.Buffer = buffer.Buffer; -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util')) : - typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$1, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.require$$1)); -})(this, (function (exports, require$$0$1, require$$0$2, require$$0$3, require$$0$4, require$$1) { 'use strict'; - - function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - - function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { - if (k !== 'default' && !(k in n)) { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - }); - return Object.freeze(n); - } - - var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); - var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); - var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); - var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); - var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - /* - * Bitcoin BIP32 path helpers - * (C) 2016 Alex Beregszaszi - */ - - const HARDENED = 0x80000000; - - var BIPPath = function (path) { - if (!Array.isArray(path)) { - throw new Error('Input must be an Array') - } - if (path.length === 0) { - throw new Error('Path must contain at least one level') - } - for (var i = 0; i < path.length; i++) { - if (typeof path[i] !== 'number') { - throw new Error('Path element is not a number') - } - } - this.path = path; - }; - - BIPPath.validatePathArray = function (path) { - try { - BIPPath.fromPathArray(path); - return true - } catch (e) { - return false - } - }; - - BIPPath.validateString = function (text, reqRoot) { - try { - BIPPath.fromString(text, reqRoot); - return true - } catch (e) { - return false - } - }; - - BIPPath.fromPathArray = function (path) { - return new BIPPath(path) - }; - - BIPPath.fromString = function (text, reqRoot) { - // skip the root - if (/^m\//i.test(text)) { - text = text.slice(2); - } else if (reqRoot) { - throw new Error('Root element is required') - } - - var path = text.split('/'); - var ret = new Array(path.length); - for (var i = 0; i < path.length; i++) { - var tmp = /(\d+)([hH\']?)/.exec(path[i]); - if (tmp === null) { - throw new Error('Invalid input') - } - ret[i] = parseInt(tmp[1], 10); - - if (ret[i] >= HARDENED) { - throw new Error('Invalid child index') - } - - if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { - ret[i] += HARDENED; - } else if (tmp[2].length != 0) { - throw new Error('Invalid modifier') - } - } - return new BIPPath(ret) - }; - - BIPPath.prototype.toPathArray = function () { - return this.path - }; - - BIPPath.prototype.toString = function (noRoot, oldStyle) { - var ret = new Array(this.path.length); - for (var i = 0; i < this.path.length; i++) { - var tmp = this.path[i]; - if (tmp & HARDENED) { - ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); - } else { - ret[i] = tmp; - } - } - return (noRoot ? '' : 'm/') + ret.join('/') - }; - - BIPPath.prototype.inspect = function () { - return 'BIPPath <' + this.toString() + '>' - }; - - var bip32Path = BIPPath; - - var createHash$3 = require$$0__default["default"].createHash; - - var safeBuffer = {exports: {}}; - - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - - (function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0__default$1["default"]; - 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) - }; - }(safeBuffer, safeBuffer.exports)); - - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; - } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; - } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; - } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str - } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; - } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; - } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } - } - var src$2 = base$2; - - var basex = src$2; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - - var bs58 = basex(ALPHABET$1); - - var base58 = bs58; - var Buffer$g = safeBuffer.exports.Buffer; - - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); - - return base58.encode(Buffer$g.concat([ - payload, - checksum - ], payload.length + 4)) - } - - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); - - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return - - return payload - } - - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return - - return decodeRaw(buffer) - } - - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload - } - - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } - }; - - var createHash$2 = createHash$3; - var bs58checkBase = base$1; - - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$2('sha256').update(buffer).digest(); - return createHash$2('sha256').update(tmp).digest() - } - - var bs58check$5 = bs58checkBase(sha256x2); - - function pathElementsToBuffer(paths) { - var buffer = Buffer.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; - } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); - } - } - return []; - } - - var src$1 = {}; - - var src = {}; - - var bip32$1 = {}; - - var crypto$4 = {}; - - var createHmac$2 = require$$0__default["default"].createHmac; - - Object.defineProperty(crypto$4, "__esModule", { value: true }); - const createHash$1 = createHash$3; - const createHmac$1 = createHmac$2; - function hash160$2(buffer) { - const sha256Hash = createHash$1('sha256') - .update(buffer) - .digest(); - try { - return createHash$1('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$1('ripemd160') - .update(sha256Hash) - .digest(); - } - } - crypto$4.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); - } - crypto$4.hmacSHA512 = hmacSHA512; - - var tinySecp256k1 = {exports: {}}; - - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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 = require('buffer').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) ; 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); - }; - })(module, commonjsGlobal); - }(bn)); - - var elliptic = {}; - - var name = "elliptic"; - var version = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0 = { - name: name, - version: version, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; - - var utils$n = {}; - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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; - }; - }(utils$m)); - - (function (exports) { - - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; - - 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; - }(utils$n)); - - var brorand = {exports: {}}; - - var r$1; - - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); - }; - - function Rand(rand) { - this.rand = rand; - } - brorand.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$3 = require('crypto'); - if (typeof crypto$3.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto$3.randomBytes(n); - }; - } catch (e) { - } - } - - var curve = {}; - - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; - - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN$8(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); - } - } - var base = 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$e(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$e(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]; - 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(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$l.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; - }; - - var inherits$c = {exports: {}}; - - var inherits_browser = {exports: {}}; - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - inherits_browser.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; - } - }; - } - - try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - inherits$c.exports = util.inherits; - } catch (e) { - /* istanbul ignore next */ - inherits$c.exports = inherits_browser.exports; - } - - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$b = inherits$c.exports; - var Base$2 = base; - - var assert$d = utils$k.assert; - - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); - - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(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$b(ShortCurve, Base$2); - var short = 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$7(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$7(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$d(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$7(vec.a, 16), - b: new BN$7(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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN$7(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$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$b(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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$b(JPoint, Base$2.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$7(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; - }; - - var BN$6 = bn.exports; - var inherits$a = inherits$c.exports; - var Base$1 = base; - - var utils$j = utils$n; - - function MontCurve(conf) { - Base$1.call(this, 'mont', conf); - - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); - } - inherits$a(MontCurve, Base$1); - var mont = 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$1(curve, x, z) { - Base$1.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$6(x, 16); - this.z = new BN$6(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$a(Point$1, Base$1.BasePoint); - - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; - - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; - - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; - - Point$1.prototype.precompute = function precompute() { - // No-op - }; - - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; - - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; - - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; - - Point$1.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$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; - - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; - }; - - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); - }; - - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$9 = inherits$c.exports; - var Base = base; - - var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits$9(EdwardsCurve, Base); - var edwards = 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$5(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$5(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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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$9(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; - - (function (exports) { - - var curve = exports; - - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); - - var curves$2 = {}; - - var hash$3 = {}; - - var utils$h = {}; - - var assert$b = minimalisticAssert; - var inherits$8 = inherits$c.exports; - - utils$h.inherits = inherits$8; - - 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; - } - utils$h.toArray = toArray; - - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils$h.toHex = toHex; - - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.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; - } - utils$h.toHex32 = toHex32; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils$h.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; - } - utils$h.zero8 = zero8; - - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.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; - } - utils$h.split32 = split32; - - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); - } - utils$h.rotr32 = rotr32$1; - - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; - - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; - - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; - - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; - - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - utils$h.sum32_5 = sum32_5$2; - - function sum64$1(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; - } - utils$h.sum64 = sum64$1; - - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - utils$h.sum64_hi = sum64_hi$1; - - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - utils$h.sum64_lo = sum64_lo$1; - - function sum64_4_hi$1(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; - } - utils$h.sum64_4_hi = sum64_4_hi$1; - - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; - - function sum64_5_hi$1(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; - } - utils$h.sum64_5_hi = sum64_5_hi$1; - - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; - } - utils$h.sum64_5_lo = sum64_5_lo$1; - - function rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - utils$h.rotr64_hi = rotr64_hi$1; - - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.rotr64_lo = rotr64_lo$1; - - function shr64_hi$1(ah, al, num) { - return ah >>> num; - } - utils$h.shr64_hi = shr64_hi$1; - - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.shr64_lo = shr64_lo$1; - - var common$5 = {}; - - var utils$g = utils$h; - var assert$a = minimalisticAssert; - - function BlockHash$4() { - 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; - } - common$5.BlockHash = BlockHash$4; - - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); - - return this._digest(enc); - }; - - BlockHash$4.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; - }; - - var sha$2 = {}; - - var common$4 = {}; - - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; - - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; - - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; - - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; - - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; - - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; - - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; - - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; - - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - common$4.g1_256 = g1_256$1; - - var utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; - - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; - - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; - - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); - } - - utils$e.inherits(SHA1, BlockHash$3); - var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); - }; - - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); - }; - - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; - - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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$2 = common$2.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$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$1; - - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; - - SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; - - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); - else - return utils$d.split32(this.h, 'big'); - }; - - var utils$c = utils$h; - var SHA256 = _256; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils$c.inherits(SHA224, SHA256); - var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); - }; - - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; - - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; - - var BlockHash$1 = common$1.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$2() { - if (!(this instanceof SHA512$2)) - return new SHA512$2(); - - BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); - var _512 = SHA512$2; - - SHA512$2.blockSize = 1024; - SHA512$2.outSize = 512; - SHA512$2.hmacStrength = 192; - SHA512$2.padLength = 128; - - SHA512$2.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$2.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$8(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); - 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); - 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$2.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.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; - } - - var utils$a = utils$h; - - var SHA512$1 = _512; - - function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512$1.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; - } - utils$a.inherits(SHA384, SHA512$1); - var _384 = SHA384; - - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; - - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); - }; - - sha$2.sha1 = _1; - sha$2.sha224 = _224; - sha$2.sha256 = _256; - sha$2.sha384 = _384; - sha$2.sha512 = _512; - - var ripemd = {}; - - var utils$9 = utils$h; - var common = common$5; - - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; - var BlockHash = common.BlockHash; - - function RIPEMD160$1() { - if (!(this instanceof RIPEMD160$1)) - return new RIPEMD160$1(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils$9.inherits(RIPEMD160$1, BlockHash); - ripemd.ripemd160 = RIPEMD160$1; - - RIPEMD160$1.blockSize = 512; - RIPEMD160$1.outSize = 160; - RIPEMD160$1.hmacStrength = 192; - RIPEMD160$1.padLength = 64; - - RIPEMD160$1.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$4(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$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); - else - return utils$9.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$4(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 - ]; - - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; - - 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$8.toArray(key, enc)); - } - var hmac = Hmac; - - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(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); - }; - - (function (exports) { - var hash = exports; - - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha$2; - hash.ripemd = ripemd; - hash.hmac = hmac; - - // 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; - }(hash$3)); - - (function (exports) { - - var curves = exports; - - var hash = hash$3; - var curve$1 = curve; - var utils = utils$n; - - var assert = utils.assert; - - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.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 = require('./precomputed/secp256k1'); - } 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, - ], - }); - }(curves$2)); - - var hash$2 = hash$3; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; - - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; - - HmacDRBG$1.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$1.prototype._hmac = function hmac() { - return new hash$2.hmac(this.hash, this.K); - }; - - HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); - - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; - }; - - HmacDRBG$1.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$7.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$7.encode(res, enc); - }; - - var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; - - function KeyPair$4(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); - } - var key$1 = KeyPair$4; - - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; - - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); - }; - - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; - - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); - }; - - KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; - - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(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$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); - }; - - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); - }; - - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); - }; - - KeyPair$4.prototype.inspect = function inspect() { - return ''; - }; - - var BN$3 = bn.exports; - - var utils$5 = utils$n; - var assert$4 = utils$5.assert; - - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; - - if (this._importDER(options, enc)) - return; - - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; - - 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$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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$3(r); - this.s = new BN$3(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$3.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$5.encode(res, enc); - }; - - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; - - var KeyPair$3 = key$1; - var Signature$2 = signature$1; - - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); - - options = curves$1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.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; - } - var ec = EC$1; - - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); - }; - - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); - }; - - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); - }; - - EC$1.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(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; - - EC$1.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$1.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$2(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$2(1)); - - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); - } - }; - - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); - - var n = this.n; - var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(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'); - }; - - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes$2(params.pub); - } - - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); - }; - - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); - }; - - KeyPair$2.prototype.secret = function secret() { - return this._secret; - }; - - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); - - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); - - cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); - - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); - - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); - - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); - }; - - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; - - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); - }; - - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); - }; - - var key = KeyPair$2; - - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.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$1(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; - } - - assert$1(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - 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$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); - - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); - - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); - - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); - - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; - - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; - - var signature = Signature$1; - - var hash$1 = hash$3; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; - - 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$1.sha512; - } - - var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); - }; - - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; - - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); - }; - - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; - - (function (exports) { - - var elliptic = exports; - - elliptic.version = require$$0.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; - - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); - - const createHmac = createHmac$2; - - const ONE1 = Buffer.alloc(1, 1); - const ZERO1 = Buffer.alloc(1, 0); - - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer.alloc(32, 0); - let v = Buffer.alloc(32, 1); - - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step E - v = createHmac('sha256', k).update(v).digest(); - - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step G - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); - - let T = v; - - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); - - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; - } - - return T - } - - var rfc6979 = deterministicGenerateK$1; - - const BN = bn.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; - - const ZERO32 = Buffer.alloc(32, 0); - const EC_GROUP_ORDER = Buffer.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); - - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; - - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; - - function isScalar (x) { - return Buffer.isBuffer(x) && x.length === 32 - } - - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isPoint (p) { - if (!Buffer.isBuffer(p)) return false - if (p.length < 33) return false - - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } - - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false - } - - function __isPointCompressed (p) { - return p[0] !== 0x04 - } - - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) - } - - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return Buffer.isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 - } - - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value - } - - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer.from(P._encode(compressed)) } - - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) - - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) - } - - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) - - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null - - return getEncoded(uu, compressed) - } - - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - - const compressed = assumeCompression(__compressed, p); - - return getEncoded(pp, compressed) - } - - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } - - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null - - return getEncoded(qq, compressed) - } - - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function sign (hash, x) { - return __sign(hash, x) - } - - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) - } - - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) - - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); - - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); - - if (Q.isInfinity()) return false - - r = Q.x.umod(n); - if (r.isZero() === 0) return false - - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false - - return true - }; - - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); - - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); - } - - const buffer = Buffer.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer - } - - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) - - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); - - if (strict && s.cmp(nDiv2) > 0) { - return false - } - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false - - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); - - // Compute s^-1 - const sInv = s.invm(n); - - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); - - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); - - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false - - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; - - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); - - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } - - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign, - signWithEntropy, - verify - }; - - try { - tinySecp256k1.exports = require('./native'); - } catch (err) { - tinySecp256k1.exports = js; - } - - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } - }; - - // TODO: deprecate - types$c.Null = types$c.Nil; - - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); - } - - var native$1 = types$c; - - var native = native$1; - - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] - } - - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) - } - - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value - } - - function captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } - } - - function tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' - - return type !== undefined ? type : '' - } - - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); - - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') - } - - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); - - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; - - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; - - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) - } - - function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } - - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; - - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) - } - - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; - - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); - - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } - - captureStackTrace(e); - return e - } - - var errors$1 = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 - }; - - var NATIVE$1 = native$1; - var ERRORS$1 = errors$1; - - function _Buffer (value) { - return Buffer.isBuffer(value) - } - - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } - - function _LengthN (type, length) { - var name = type.toJSON(); - - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true - - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; - - return Length - } - - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); - - function Range$b (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) - } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - }; - return _range - } - - var INT53_MAX = Math.pow(2, 53) - 1; - - function Finite (value) { - return typeof value === 'number' && isFinite(value) - } - function Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value - } - function UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value - } - - var types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$b, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; - - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); - } - - var extra = types$b; - - var ERRORS = errors$1; - var NATIVE = native$1; - - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; - - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; - - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false - - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; - - return _arrayOf - }, - - maybe: function maybe (type) { - type = compile(type); - - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; - - return _maybe - }, - - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); - - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } - - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } - } - - return true - } - - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; - } - - return _map - }, - - object: function object (uncompiled) { - var type = {}; - - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } - - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - var propertyName; - - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; - - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } - - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue - - throw new TfPropertyTypeError(undefined, propertyName) - } - } - - return true - } - _object.toJSON = function () { return tfJSON(type) }; - - return _object - }, - - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); - - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - - return _anyOf - }, - - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); - - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - - return _allOf - }, - - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type }; - - return _quacksLike - }, - - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); - - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false - - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; - - return _tuple - }, - - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected }; - - return _value - } - }; - - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; - - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) - - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } - - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } - - return TYPES.value(type) - } - - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true - - throw new TfTypeError(surrogate || type, value) - } - - // JIT - return typeforce$b(compile(type), value, strict) - } - - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } - - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } - - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } - - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; - - var typeforce_1 = typeforce$b; - - var bs58check$4 = bs58check$5; - - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') - - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false - } - } - - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') - - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') - - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } - - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer(compressed ? 34 : 33); - - result.writeUInt8(version, 0); - privateKey.copy(result, 1); - - if (compressed) { - result[33] = 0x01; - } - - return result - } - - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) - } - - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) - - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } - - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw - }; - - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$2 = crypto$4; - const bs58check$3 = bs58check$5; - const ecc$6 = tinySecp256k1.exports; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; - } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$2.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); - } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$2.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; - } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); - } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); - } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); - } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } - } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); - } - return hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); - } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); - } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); - } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); - } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$2.hmacSHA512(Buffer.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); - } - bip32$1.fromSeed = fromSeed; - - Object.defineProperty(src, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; - - var address$1 = {}; - - var networks$3 = {}; - - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - - var payments$4 = {}; - - var embed = {}; - - var script$1 = {}; - - var script_number = {}; - - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); - } - } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; - } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); - } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; - } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; - } - return buffer; - } - script_number.encode = encode$g; - - var script_signature = {}; - - var types$a = {}; - - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; - }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, - }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; - - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use - - var Buffer$f = safeBuffer.exports.Buffer; - - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false - - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false - - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false - - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true - } - - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } - } - - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer$f.allocUnsafe(6 + lenR + lenS); - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); - - return signature - } - - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f - }; - - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; - - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE - }; - - var OPS$9 = require$$7; - - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 - } - - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); - - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); - - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); - - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); - - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); - } - - return size - } - - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; - - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; - - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; - - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; - - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - - number = buffer.readUInt32LE(offset + 1); - size = 5; - } - - return { - opcode: opcode, - number: number, - size: size - } - } - - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c - }; - - var OPS$8 = require$$7; - - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } - - var map_1 = map; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = tinySecp256k1.exports; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return Buffer.isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return Buffer.isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; - } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; - } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode - } else { - chunks.push(opcode); - i += 1; - } - } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); - } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!Buffer.isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); - - var lazy$7 = {}; - - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; - }; - } - lazy$7.value = value; - - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } - } - return Object.assign(o, a); - } - embed.p2data = p2data; - - var p2ms$3 = {}; - - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = tinySecp256k1.exports; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); - } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); - } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); - } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); - } - } - return Object.assign(o, a); - } - p2ms$3.p2ms = p2ms$2; - - var p2pk$3 = {}; - - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = tinySecp256k1.exports; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); - } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); - } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); - } - } - return Object.assign(o, a); - } - p2pk$3.p2pk = p2pk$2; - - var p2pkh$4 = {}; - - var crypto$1 = {}; - - Object.defineProperty(crypto$1, '__esModule', { value: true }); - const createHash = createHash$3; - function ripemd160$2(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); - } - } - crypto$1.ripemd160 = ripemd160$2; - function sha1$1(buffer) { - return createHash('sha1') - .update(buffer) - .digest(); - } - crypto$1.sha1 = sha1$1; - function sha256$2(buffer) { - return createHash('sha256') - .update(buffer) - .digest(); - } - crypto$1.sha256 = sha256$2; - function hash160$1(buffer) { - return ripemd160$2(sha256$2(buffer)); - } - crypto$1.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$2(sha256$2(buffer)); - } - crypto$1.hash256 = hash256$1; - - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); - const bcrypto$6 = crypto$1; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = tinySecp256k1.exports; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - } - if (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2pkh$4.p2pkh = p2pkh$3; - - var p2sh$1 = {}; - - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$1; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } - } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!Buffer.isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); - } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - } - } - return Object.assign(o, a); - } - p2sh$1.p2sh = p2sh; - - var p2wpkh$2 = {}; - - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; - - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; - } - - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) - } - - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' - - chk = polymodStep(chk) ^ (c >> 5); - } - chk = polymodStep(chk); - - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk - } - - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - - prefix = prefix.toLowerCase(); - - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) - - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') - - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } - - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; - - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } - - return result - } - - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' - - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; - - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str - - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' - - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk - - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; - - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); - } - - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } - } - - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - } - - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - - throw new Error(res) - } - - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; - - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } - - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' - } - - return result - } - - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - } - - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - } - - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords - }; - - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); - const bcrypto$4 = crypto$1; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = tinySecp256k1.exports; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2wpkh$2.p2wpkh = p2wpkh$1; - - var p2wsh$1 = {}; - - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$1; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = tinySecp256k1.exports; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - function chunkHasUncompressedPubkey(chunk) { - if ( - Buffer.isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; - } else { - return false; - } - } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; - } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), - }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); - } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); - } - } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); - } - } - return Object.assign(o, a); - } - p2wsh$1.p2wsh = p2wsh; - - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; - - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer.from(data), - }; - } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); - } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); - } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); - } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; - } - } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; - - var ecpair = {}; - - var randombytes = require$$0__default["default"].randomBytes; - - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = tinySecp256k1.exports; - const randomBytes = randombytes; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; - - var block = {}; - - var bufferutils = {}; - - var Buffer$e = safeBuffer.exports.Buffer; - - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; - - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') - } - - function encode$b (number, buffer, offset) { - checkUInt53$1(number); - - if (!buffer) buffer = Buffer$e.allocUnsafe(encodingLength$1(number)); - if (!Buffer$e.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; - - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; - - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; - - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } - - return buffer - } - - function decode$a (buffer, offset) { - if (!Buffer$e.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - var first = buffer.readUInt8(offset); - - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first - - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) - - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) - - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); - - return number - } - } - - function encodingLength$1 (number) { - checkUInt53$1(number); - - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } - - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; - - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; - } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); - } - } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); - } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); - } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; - } - } - bufferutils.BufferReader = BufferReader$1; - - var transaction = {}; - - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$1; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; - } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); - } - const EMPTY_SCRIPT = Buffer.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, - }; - function isOutput(out) { - return out.value !== undefined; - } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; - } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); - } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); - } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); - } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); - } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; - } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; - } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; - } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); - } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; - } - // serialize and hash - const buffer = Buffer.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); - } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); - } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); - } - tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); - } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); - } else { - bufferWriter.writeSlice(txOut.valueBuffer); - } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); - } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; - } - } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; - - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') - - var length = values.length; - var results = values.concat(); - - while (length > 1) { - var j = 0; - - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer.concat([left, right]); - - results[j] = digestFn(data); - } - - length = j; - } - - return results[0] - }; - - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$1; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); - } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; - } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); - } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); - } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; - } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; - } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; - } - } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { - return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 - ); - } - function anyTxHasWitness(transactions) { - return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) - ); - } - - var psbt$1 = {}; - - var psbt = {}; - - var combiner = {}; - - var parser = {}; - - var fromBuffer = {}; - - var converter = {}; - - var typeFields = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); - - var globalXpub$1 = {}; - - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - Buffer.isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - Buffer.isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); - } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 - ); - } - globalXpub$1.canAddToArray = canAddToArray$1; - - var unsignedTx$1 = {}; - - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), - }; - } - unsignedTx$1.encode = encode$9; - - var finalScriptSig$1 = {}; - - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, - }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return Buffer.isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; - - var finalScriptWitness$1 = {}; - - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); - return { - key, - value: data, - }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return Buffer.isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); - } - finalScriptWitness$1.canAdd = canAdd$4; - - var nonWitnessUtxo$1 = {}; - - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, - }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return Buffer.isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; - } - nonWitnessUtxo$1.canAdd = canAdd$3; - - var partialSig$1 = {}; - - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, - }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer.concat([head, pSig.pubkey]), - value: pSig.signature, - }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { - return ( - Buffer.isBuffer(data.pubkey) && - Buffer.isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) - ); - } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!Buffer.isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; - - var porCommitment$1 = {}; - - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); - return { - key, - value: Buffer.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; - } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; - } - porCommitment$1.canAdd = canAdd$2; - - var sighashType$1 = {}; - - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.readUInt32LE(0); - } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; - } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; - } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; - } - sighashType$1.canAdd = canAdd$1; - - var witnessUtxo$1 = {}; - - var tools = {}; - - var varint$1 = {}; - - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) - throw new RangeError('value out of range'); - } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(_number)); - if (!Buffer.isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } - return buffer; - } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!Buffer.isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; - } - } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; - } - varint$1.encodingLength = encodingLength; - - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer.from([0])); - return Buffer.concat(buffers); - } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, - ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; - } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; - } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - tools.writeUInt64LE = writeUInt64LE; - - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); - } - return { - script, - value, - }; - } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, - }; - } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return Buffer.isBuffer(data.script) && typeof data.value === 'number'; - } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; - } - witnessUtxo$1.canAdd = canAdd; - - var bip32Derivation$1 = {}; - - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); - } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - function encode(data) { - const head = Buffer.from([TYPE_BYTE]); - const key = Buffer.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - Buffer.isBuffer(data.pubkey) && - Buffer.isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - return { - decode, - encode, - check, - expected, - canAddToArray, - }; - } - bip32Derivation$1.makeConverter = makeConverter$2; - - var checkPubkey$1 = {}; - - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); - if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } - } - return pubkey; - } - } - checkPubkey$1.makeChecker = makeChecker; - - var redeemScript$1 = {}; - - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return Buffer.isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - redeemScript$1.makeConverter = makeConverter$1; - - var witnessScript$1 = {}; - - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return Buffer.isBuffer(data); - } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - witnessScript$1.makeConverter = makeConverter; - - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), - }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), - }; - converter.outputs = outputs; - - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; - } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); - return { - key, - value, - }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); - } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; - } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', - ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); - } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); - } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); - } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); - } - inputKeyVals.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); - } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); - } - outputKeyVals.push(output); - } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); - } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); - } - } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; - } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); - } - } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - } - } - inputs.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - } - } - outputs.push(output); - } - return { globalMap, inputs, outputs }; - } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - - var toBuffer = {}; - - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); - } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); - }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); - } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along - return { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), - }; - } - toBuffer.psbtToKeyVals = psbtToKeyVals; - - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); - - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); - } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); - } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); - } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, - }); - } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); - }; - } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; - } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); - }); - return set; - } - - var utils = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; - } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); - } - if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 - ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); - } - } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } - }); - return count; - } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; - } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); - } - } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, - ); - } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; - } - } - } - }; - } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); - } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); - } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); - } - txBuf.writeUInt32LE(version, 0); - return txBuf; - } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!Buffer.isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); - } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; - } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); - - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, - }; - } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); - } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); - return this; - } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); - return this; - } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - return this; - } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); - return this; - } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; - } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } - return this; - } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; - } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); - } - } - psbt.Psbt = Psbt$1; - - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$1; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, - }; - /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. - */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); - } - static fromBase64(data, opts = {}) { - const buffer = Buffer.from(data, 'base64'); - return this.fromBuffer(buffer, opts); - } - static fromHex(data, opts = {}) { - const buffer = Buffer.from(data, 'hex'); - return this.fromBuffer(buffer, opts); - } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; - } - get inputCount() { - return this.data.inputs.length; - } - get version() { - return this.__CACHE.__TX.version; - } - set version(version) { - this.setVersion(version); - } - get locktime() { - return this.__CACHE.__TX.locktime; - } - set locktime(locktime) { - this.setLocktime(locktime); - } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); - } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); - } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; - } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; - } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; - } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; - } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; - } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); - } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; - } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; - } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); - } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; - } - addOutput(outputData) { - if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) - ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); - } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); - } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); - return tx; - } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); - } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); - return this; - } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, - ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); - return this; - } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), - ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); - } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) - ); - } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); - } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); - } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), - ); - return results.reduce((final, res) => res === true && final, true); - } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); - } - return results.every(res => res === true); - } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$1(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; - } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); - } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; - } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - }); - }); - } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); - } - toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); - } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); - } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; - } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); - } - return this; - } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; - } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; - } - } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); - } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; - } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!Buffer.isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); - } - addOutput(output) { - if ( - output.script === undefined || - output.value === undefined || - !Buffer.isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); - } - toBuffer() { - return this.tx.toBuffer(); - } - } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; - } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); - } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; - } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); - } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, - ); - } - } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } - }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } - }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } - }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, - ); - } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); - } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); - } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); - } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; - } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, - ); - } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } - } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, - ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; - } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); - throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, - ); - } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); - } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, - ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, - ); - } - return { - script: meaningfulScript, - sighashType, - hash, - }; - } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - } - return payment; - } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return Buffer.isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); - } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, - }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } - } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; - } - return res; - } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); - } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { - throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', - ); - } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; - } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); - } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); - } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; - } - function readVarSlice() { - return readSlice(readVarInt()); - } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; - } - return readVector(); - } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; - } - return text; - } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer.concat([buffer, Buffer.from(slice)]); - } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); - } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); - } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); - } - writeVector(witness); - return buffer; - } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, - }); - } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; - } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); - } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); - } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); - } - return c[inputIndex]; - } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); - } - } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; - if ( - !Buffer.isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); - } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); - } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) - throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', - ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; - } - return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', - }; - } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); - } - } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); - } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; - } - function range$1(n) { - return [...Array(n).keys()]; - } - - var transaction_builder = {}; - - var classify$1 = {}; - - var multisig$1 = {}; - - var input$b = {}; - - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); - } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); - } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); - } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - - var output$e = {}; - - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); - } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; - - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; - - var nulldata = {}; - - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; - } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - - var pubkey = {}; - - var input$9 = {}; - - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); - } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; - - var output$b = {}; - - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG - ); - } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; - - var pubkeyhash = {}; - - var input$7 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); - } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; - - var output$9 = {}; - - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG - ); - } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; - - var scripthash = {}; - - var input$5 = {}; - - var output$7 = {}; - - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 - ); - } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; - }; - - var output$6 = {}; - - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); - } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; - }; - - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!Buffer.isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), - ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) - ); - } - // match types - if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; - } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; - }; - - var output$5 = {}; - - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL - ); - } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; - }; - - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; - - var witnesscommitment = {}; - - var output$3 = {}; - - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); - } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); - } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); - } - output$3.decode = decode; - - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; - - var witnesspubkeyhash = {}; - - var input$3 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; - } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); - } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; - - var witnessscripthash = {}; - - var input$1 = {}; - - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!Buffer.isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; - if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; - } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; - - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; - } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; - } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; - } - classify$1.witness = classifyWitness; - - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$1; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); - } - } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; - } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; - } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); - } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; - } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; - } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; - } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; - } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); - } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); - } - build() { - return this.__build(false); - } - buildIncomplete() { - return this.__build(true); - } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), - ); - } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); - } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; - } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; - } - prevOutType = expanded.type; - } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); - } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, - ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; - } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); - } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; - } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); - }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); - } - } - return tx; - } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); - }); - }); - } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; - } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); - }) - ); - } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; - } - return false; - }); - }); - } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; - } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; - } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); - return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, - }; - } - } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); - } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; - } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); - } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); - return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, - }; - } - } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, - }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); - } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); - } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, - ); - } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - } - } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); - } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); - } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, - ); - } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; - } - } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', - ); - } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; - } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', - ); - } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); - } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); - } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, - ); - // updates inline - Object.assign(input, prepared); - } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); - } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); - } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); - } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; - } - - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; - const address = address$1; - src$1.address = address; - const crypto = crypto$1; - var crypto_1 = src$1.crypto = crypto; - const ECPair = ecpair; - src$1.ECPair = ECPair; - const networks = networks$3; - src$1.networks = networks; - const payments = payments$4; - src$1.payments = payments; - const script = script$1; - src$1.script = script; - var block_1 = block; - src$1.Block = block_1.Block; - var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$1.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - - var re$5 = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; - - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; - - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; - - const debug$4 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$4; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; - - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers - }; - - const debug$3 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; - - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); - - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) - } - - debug$3('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); - } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug$3('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } - } - - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; - - var parse_1 = parse$5; - - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; - - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; - - const SemVer$c = semver$1; - - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - - const parse$2 = parse_1; - const eq$1 = eq_1; - - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } - }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; - - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; - - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; - - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1 = prerelease; - - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; - - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1 = compareBuild$2; - - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; - - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; - - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; - - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; - - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; - - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; - - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; - - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; - - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt$2(a, b, loose) - - case '>=': - return gte$1(a, b, loose) - - case '<': - return lt$1(a, b, loose) - - case '<=': - return lte$1(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1 = coerce; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); - } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); - } - } - - return self - } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; - } - - if (prev) { - prev.next = next; - } - - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } - - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; - } - - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; - - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; - - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; - - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; - - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res - }; - - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } - - return acc - }; - - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } - - return acc - }; - - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; - - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr - }; - - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } - - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; - - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this - }; - - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); - - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } - - self.length++; - - return inserted - } - - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; - } - self.length++; - } - - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; - } - - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } - - this.list = list; - this.value = value; - - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } - - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } - } - - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); - - const naiveLength = () => 1; - - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; - - if (!options) - options = {}; - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; - - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA; - trim(this); - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); - } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } - } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); - } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true - } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false - } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) - } - - get (key) { - return get$1(this, key, true) - } - - peek (key) { - return get$1(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null - - del(this, node); - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)); - } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); - } - } - - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); - } - } - return hit.value - } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; - - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; - } - } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); - } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; - } - } - - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; - - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } - } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this - } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } - } - } - } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$2('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } - } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$2 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$2('comp', comp, options); - comp = replaceCarets(comp, options); - debug$2('caret', comp); - comp = replaceTildes(comp, options); - debug$2('tildes', comp); - comp = replaceXRanges(comp, options); - debug$2('xrange', comp); - comp = replaceStars(comp, options); - debug$2('stars', comp); - return comp - }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$2('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; - } - - debug$2('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$2('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$2('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$2('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$2('caret return', ret); - return ret - }) - }; - - const replaceXRanges = (comp, options) => { - debug$2('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') - }; - - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$2('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; - } - - debug$2('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$2('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; - - const replaceGTE0 = (comp, options) => { - debug$2('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$2(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 - } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } - } - - debug$1('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } - - debug$1('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); - } - } - - toString () { - return this.value - } - - test (version) { - debug$1('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) - } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } - } - - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug$1 = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; - - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } - } - }); - return max - }; - var maxSatisfying_1 = maxSatisfying; - - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); - } - } - }); - return min - }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null - }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true - }; - - var outside_1 = outside$2; - - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; - - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; - - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) - }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false - } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; - - var subset_1 = subset; - - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - var readable = {exports: {}}; - - var stream = require$$0__default$2["default"]; - - function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - - function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - var _require$2 = require$$0__default$1["default"], - Buffer$d = _require$2.Buffer; - - var _require2 = require$$1__default["default"], - inspect = _require2.inspect; - - var custom = inspect && inspect.custom || 'inspect'; - - function copyBuffer(src, target, offset) { - Buffer$d.prototype.copy.call(src, target, offset); - } - - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck$2(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass$2(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$d.alloc(0); - var ret = Buffer$d.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$d.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread$1({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; - } - - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); - } - - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.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(self, err) { - self.emit('error', err); - } - - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); - } - - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - - var errors = {}; - - const codes = {}; - - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; - } - - // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - - errors.codes = codes; - - var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; - - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; - } - - var state = { - getHighWaterMark: getHighWaterMark$2 - }; - - /** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - - var node = require$$1__default["default"].deprecate; - - var _stream_writable = Writable$1; - // there will be only 2 of these for each stream - - - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; - } - /* */ - - /**/ - - - var Duplex$3; - /**/ - - Writable$1.WritableState = WritableState; - /**/ - - var internalUtil = { - deprecate: node - }; - /**/ - - /**/ - - var Stream$1 = stream; - /**/ - - - var Buffer$c = require$$0__default$1["default"].Buffer; - - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$c.from(chunk); - } - - function _isUint8Array$1(obj) { - return Buffer$c.isBuffer(obj) || obj instanceof OurUint8Array$1; - } - - var destroyImpl$1 = destroy_1; - - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; - - var _require$codes$3 = errors.codes, - ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - - inherits$c.exports(Writable$1, Stream$1); - - function nop() {} - - function WritableState(options, stream, isDuplex) { - Duplex$3 = Duplex$3 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; - }; - - (function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. - - - var realHasInstance; - - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$1, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$1) return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; - } - - function Writable$1(options) { - Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$3; - if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream$1.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. - - - Writable$1.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; - - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy$1(stream, er); - process.nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. - - - function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy$1(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; - } - - Writable$1.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array$1(chunk); - - if (isBuf && !Buffer$c.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; - - Writable$1.prototype.cork = function () { - this._writableState.corked++; - }; - - Writable$1.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - - Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - Object.defineProperty(Writable$1.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$c.from(chunk, encoding); - } - - return chunk; - } - - Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } - } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } - } - - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - - - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it - - - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable$1.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; - - Writable$1.prototype._writev = null; - - Writable$1.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; - }; - - Object.defineProperty(Writable$1.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy$1(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); - } - - function prefinish$1(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish$1(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; - } - - Object.defineProperty(Writable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } - }); - Writable$1.prototype.destroy = destroyImpl$1.destroy; - Writable$1.prototype._undestroy = destroyImpl$1.undestroy; - - Writable$1.prototype._destroy = function (err, cb) { - cb(err); - }; - - /**/ - - var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; - }; - /**/ - - - var _stream_duplex = Duplex$2; - - var Readable$1 = _stream_readable; - - var Writable = _stream_writable; - - inherits$c.exports(Duplex$2, Readable$1); - - { - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; - } - } - - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$1.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } - } - - Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); // the no-half-open enforcer - - function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - Object.defineProperty(Duplex$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - - var string_decoder = {}; - - /**/ - - var Buffer$b = safeBuffer.exports.Buffer; - /**/ - - var isEncoding = Buffer$b.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$b.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. - string_decoder.StringDecoder = StringDecoder$1; - function StringDecoder$1(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$b.allocUnsafe(nb); - } - - StringDecoder$1.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$1.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$1.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$1.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); - 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) : ''; - } - - var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; - - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; - } - - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; - } - - var endOfStream = eos$1; - - var _Object$setPrototypeO; - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var finished = endOfStream; - - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); - - function createIterResult(value, done) { - return { - value: value, - done: done - }; - } - - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } - } - - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); - } - - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty$1(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty$1(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; - - var async_iterator = createReadableStreamAsyncIterator$1; - - 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$3(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); }); }; } - - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; - - function from$1(Readable, iterable, opts) { - var iterator; - - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); - - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. - - var reading = false; - - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; - - function next() { - return _next2.apply(this, arguments); - } - - function _next2() { - _next2 = _asyncToGenerator$3(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; - - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - - return readable; - } - - var from_1 = from$1; - - var _stream_readable = Readable; - /**/ - - var Duplex$1; - /**/ - - Readable.ReadableState = ReadableState; - /**/ - - require$$0__default$3["default"].EventEmitter; - - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ - - /**/ - - - var Stream = stream; - /**/ - - - var Buffer$a = require$$0__default$1["default"].Buffer; - - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer(chunk) { - return Buffer$a.from(chunk); - } - - function _isUint8Array(obj) { - return Buffer$a.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ - - - var debugUtil = require$$1__default["default"]; - - var debug; - - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); - } else { - debug = function debug() {}; - } - /**/ - - - var BufferList = buffer_list; - - var destroyImpl = destroy_1; - - var _require = state, - getHighWaterMark = _require.getHighWaterMark; - - var _require$codes$2 = errors.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - - var StringDecoder; - var createReadableStreamAsyncIterator; - var from; - - inherits$c.exports(Readable, Stream); - - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } - - function ReadableState(options, stream, isDuplex) { - Duplex$1 = Duplex$1 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - - function Readable(options) { - Duplex$1 = Duplex$1 || _stream_duplex; - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$1; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); - } - - Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - - Readable.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - - - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer$a.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() - - - Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$a.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); - } - - function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; - } - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. - - - Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB - - - var MAX_HWM = 0x40000000; - - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; - } // you can override either this method, or the async _read(n) below. - - - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; - }; - - function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - - - function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } - } - - function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - - - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } - } - - function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - - - Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something - - - Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; - }; - - Readable.prototype.addListener = Readable.prototype.on; - - Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; - }; - - Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; - }; - - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } - } - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - - - Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } - } - - function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - - - Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; - }; - - if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } - - return createReadableStreamAsyncIterator(this); - }; - } - - Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); // exposed for testing purposes only. - - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } - } - - function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } - - if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = from_1; - } - - return from(Readable, iterable, opts); - }; - } - - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; - } - - var _stream_transform = Transform$2; - - var _require$codes$1 = errors.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - - var Duplex = _stream_duplex; - - inherits$c.exports(Transform$2, Duplex); - - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } - - function Transform$2(options) { - if (!(this instanceof Transform$2)) return new Transform$2(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); - } - - function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } - } - - Transform$2.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - - - Transform$2.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); - }; - - Transform$2.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - - - Transform$2.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - Transform$2.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; - - function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } - - var _stream_passthrough = PassThrough; - - var Transform$1 = _stream_transform; - - inherits$c.exports(PassThrough, Transform$1); - - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$1.call(this, options); - } - - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - var eos; - - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } - - var _require$codes = errors.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } - - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; - } - - function call(fn) { - fn(); - } - - function pipe(from, to) { - return from.pipe(to); - } - - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); - } - - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } - - var pipeline_1 = pipeline; - - (function (module, exports) { - var Stream = require$$0__default$2["default"]; - if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; - } else { - exports = module.exports = _stream_readable; - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - } - }(readable, readable.exports)); - - var Buffer$9 = safeBuffer.exports.Buffer; - var Transform = readable.exports.Transform; - var inherits$7 = inherits$c.exports; - - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$9.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } - - function HashBase$1 (blockSize) { - Transform.call(this); - - this._block = Buffer$9.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; - - this._finalized = false; - } - - inherits$7(HashBase$1, Transform); - - HashBase$1.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase$1.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase$1.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$9.isBuffer(data)) data = Buffer$9.from(data, encoding); - - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } - - return this - }; - - HashBase$1.prototype._update = function () { - throw new Error('_update is not implemented') - }; - - HashBase$1.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); - - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; - - return digest - }; - - HashBase$1.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; - - var hashBase = HashBase$1; - - var Buffer$8 = require$$0__default$1["default"].Buffer; - var inherits$6 = inherits$c.exports; - var HashBase = hashBase; - - var ARRAY16 = new Array(16); - - var zl = [ - 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 zr = [ - 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 sl = [ - 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 sr = [ - 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 - ]; - - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - - function RIPEMD160 () { - HashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } - - inherits$6(RIPEMD160, HashBase); - - RIPEMD160.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; - - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; - - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } - - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; - } - - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$8.alloc ? Buffer$8.alloc(20) : new Buffer$8(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer - }; - - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } - - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } - - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } - - var ripemd160$1 = RIPEMD160; - - var sha_js = {exports: {}}; - - var Buffer$7 = safeBuffer.exports.Buffer; - - // prototype class for hash functions - function Hash$6 (blockSize, finalSize) { - this._block = Buffer$7.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } - - Hash$6.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$7.from(data, enc); - } - - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); - } - } - - this._len += length; - return this - }; - - Hash$6.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); - - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } - - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; - - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } - - this._update(this._block); - var hash = this._hash(); - - return enc ? hash.toString(enc) : hash - }; - - Hash$6.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; - - var hash = Hash$6; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - - var inherits$5 = inherits$c.exports; - var Hash$5 = hash; - var Buffer$6 = safeBuffer.exports.Buffer; - - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$5 = new Array(80); - - function Sha () { - this.init(); - this._w = W$5; - - Hash$5.call(this, 64, 56); - } - - inherits$5(Sha, Hash$5); - - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } - - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha$1 = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - - var inherits$4 = inherits$c.exports; - var Hash$4 = hash; - var Buffer$5 = safeBuffer.exports.Buffer; - - var K$2 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$4 = new Array(80); - - function Sha1 () { - this.init(); - this._w = W$4; - - Hash$4.call(this, 64, 56); - } - - inherits$4(Sha1, Hash$4); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } - - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } - - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$5.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha1 = Sha1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - var inherits$3 = inherits$c.exports; - var Hash$3 = hash; - var Buffer$4 = safeBuffer.exports.Buffer; - - var K$1 = [ - 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 W$3 = new Array(64); - - function Sha256$1 () { - this.init(); - - this._w = W$3; // new Array(64) - - Hash$3.call(this, 64, 56); - } - - inherits$3(Sha256$1, Hash$3); - - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this - }; - - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } - - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } - - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } - - Sha256$1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256$1.prototype._hash = function () { - var H = Buffer$4.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); - - return H - }; - - var sha256$1 = Sha256$1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - var inherits$2 = inherits$c.exports; - var Sha256 = sha256$1; - var Hash$2 = hash; - var Buffer$3 = safeBuffer.exports.Buffer; - - var W$2 = new Array(64); - - function Sha224 () { - this.init(); - - this._w = W$2; // new Array(64) - - Hash$2.call(this, 64, 56); - } - - inherits$2(Sha224, Sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this - }; - - Sha224.prototype._hash = function () { - var H = Buffer$3.allocUnsafe(28); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - - return H - }; - - var sha224 = Sha224; - - var inherits$1 = inherits$c.exports; - var Hash$1 = hash; - var Buffer$2 = safeBuffer.exports.Buffer; - - 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 W$1 = new Array(160); - - function Sha512 () { - this.init(); - this._w = W$1; - - Hash$1.call(this, 128, 112); - } - - inherits$1(Sha512, Hash$1); - - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; - - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - - return this - }; - - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } - - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } - - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } - - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } - - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } - - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } - - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } - - Sha512.prototype._update = function (M) { - var W = this._w; - - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; - - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - - W[i] = Wih; - W[i + 1] = Wil; - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); - - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j]; - var Kil = K[j + 1]; - - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function () { - var H = Buffer$2.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; - - var sha512 = Sha512; - - var inherits = inherits$c.exports; - var SHA512 = sha512; - var Hash = hash; - var Buffer$1 = safeBuffer.exports.Buffer; - - var W = new Array(160); - - function Sha384 () { - this.init(); - this._w = W; - - Hash.call(this, 128, 112); - } - - inherits(Sha384, SHA512); - - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; - - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - - return this - }; - - Sha384.prototype._hash = function () { - var H = Buffer$1.allocUnsafe(48); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; - - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); - - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() - }; - - exports$1.sha = sha$1; - exports$1.sha1 = sha1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$1; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; - - var sha = sha_js.exports; - - function hashPublicKey(buffer) { - return new ripemd160$1().update(sha("sha256").update(buffer).digest()).digest(); - } - - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$3(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); - }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); - }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); - }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$3(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; - }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; - }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$3(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; - }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); - }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; - }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer.concat([h, h, x])); - }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer.concat([ - Buffer.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$3(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; - }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); - } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; - }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]); - }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$3(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; - }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; - }; - return p2wpkh; - }(SingleKeyAccount)); - - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; - }; - Merkle.prototype.size = function () { - return this.leaves.length; - }; - Merkle.prototype.getLeaves = function () { - return this.leaves; - }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; - }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); - }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; - }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer.concat([Buffer.from([1]), left, right])); - }; - return Merkle; - }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; - } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; - } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$2([node.parent.rightChild.hash], __read$2(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$2([node.parent.leftChild.hash], __read$2(proveNode(node.parent)), false); - } - } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; - } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; - } - - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md - */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; - } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; - } - - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer.from([0, 1])); - } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } - } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); - } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); - } - - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$4.apply(this, arguments); - }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$2(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; - } - return NoSuchEntry; - }(Error)); - /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. - * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. - */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; - } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); - } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; - } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; - } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; - } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; - }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer.from(k.substring(2), "hex")); - } - }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); - }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); - }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$4({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer.from(value); - } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; - } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer.from(k, "hex")), value); - keyPair.serialize(buf); - } - buf.writeUInt8(0); - } - function b() { - return Buffer.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); - } - - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); - } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); - } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); - } - - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer.concat([ - inputBuffer, - input.prevout, - Buffer.from([0x00]), - input.sequence, - ]) - : Buffer.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer.alloc(0), - transaction.extraData || Buffer.alloc(0), - ]); - } - return Buffer.concat([ - transaction.version, - timestamp ? timestamp : Buffer.alloc(0), - transaction.nVersionGroupId || Buffer.alloc(0), - useWitness ? Buffer.from("0001", "hex") : Buffer.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); - } - - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver.major(appAndVersion.version) >= 2); - } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$b(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$b(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$b(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$b(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$b(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$b(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$b(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$b(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$b(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$b(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$b(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$b(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$b(this, void 0, void 0, function () { - var sigs; - return __generator$b(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); - }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); - } - - var id$1 = 0; - var subscribers$1 = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch$1(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen$1 = function (cb) { - subscribers$1.push(cb); - return function () { - var i = subscribers$1.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; - subscribers$1.pop(); - } - }; - }; - function dispatch$1(log) { - for (var i = 0; i < subscribers$1.length; i++) { - try { - subscribers$1[i](log); - } - catch (e) { - console.error(e); - } - } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen$1; - } - - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 - }; - function getWalletPublicKey(transport, options) { - return __awaiter$a(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$a(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$3({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); - } - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - - var NODE_ENV = process.env.NODE_ENV; - - var invariant = function(condition, format, a, b, c, d, e, f) { - if (NODE_ENV !== 'production') { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; - } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } - }; - - var invariant_1 = invariant; - - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$9(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$9(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$9(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$9(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$9(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer.concat([ - transaction.version, - transaction.timestamp || Buffer.alloc(0), - transaction.nVersionGroupId || Buffer.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer.compare(version, Buffer.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer.from([0x00]) - : Buffer.alloc(0); - data = Buffer.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer.concat([ - output.amount, - isDecred ? Buffer.from([0x00, 0x00]) : Buffer.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer.concat(endData); - extraPart = isDecred - ? data - : Buffer.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer.concat([locktime, extraPart || Buffer.alloc(0)]))]; - case 20: - res = _c.sent(); - invariant_1(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$8(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$8(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer.concat([ - transaction.version, - transaction.timestamp || Buffer.alloc(0), - transaction.nVersionGroupId || Buffer.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$4(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer.from([0x01, inputValue.length]); - } - else { - prefix = Buffer.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer.from([0x00]); - } - } - data = Buffer.concat([ - prefix, - inputValue, - isDecred ? Buffer.from([0x00]) : Buffer.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); - } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); - } - var hash = sha("sha256") - .update(sha("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); - } - hash = Buffer.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer.alloc(1); - prefixBuffer[0] = prefix; - return Buffer.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer.from([0x00, 0x00, 0x00, 0x00]), - Buffer.from([sigHashType]), - ]) - : Buffer.concat([ - pathsBuffer, - Buffer.from([0x00]), - lockTimeBuffer, - Buffer.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$7(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$7(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var getAppAndVersion = function (transport) { return __awaiter$6(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$6(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - invariant_1(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$5(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$2(__assign$2({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer.alloc(0); - nullPrevout = Buffer.alloc(0); - defaultVersion = Buffer.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer.concat([ - Buffer.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer.concat([ - Buffer.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer.alloc(1); - keySize = Buffer.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer.concat([ - Buffer.from("02", "hex"), - Buffer.from([signatures[i].length]), - signatures[i], - Buffer.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer.concat([witness, tmpScriptData]); - } - result = Buffer.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer.concat([ - result, - targetTransaction.nExpiryHeight || Buffer.alloc(0), - targetTransaction.extraData || Buffer.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer.concat([ - decredWitness_1, - Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer.from([0x00, 0x00, 0x00, 0x00]), - Buffer.from([0xff, 0xff, 0xff, 0xff]), - Buffer.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } - }); - }); - } - - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$4(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$4(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$4(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$3(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$3(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$1(__assign$1({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer.alloc(0); - nullPrevout = Buffer.alloc(0); - defaultVersion = Buffer.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer.from(trustedInput, "hex") - : Buffer.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$1(__assign$1({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign = (undefined && undefined.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$2(this, void 0, void 0, function () { - var res; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$2(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$2(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); - } - return getWalletPublicKey(this.transport, __assign(__assign({}, opts), { path: path })); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); - } - return signP2SHTransaction(this.transport, arg); - }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer.concat([ - Buffer.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); - }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer.concat([ - asBufferUInt32BE(version), - Buffer.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$1().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); - } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$1(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$1([], __read$1(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$1([], __read$1(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; - } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$1([], __read$1(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - - var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { - } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; - } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer.from(request.subarray(1))); - this.progressCallback(); - return Buffer.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer.from([known_preimage[i]])); - } - } - return Buffer.concat([ - preimage_len_varint, - Buffer.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; - } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray([], __read(proof.slice(-n_leftover_elements)), false)); - } - return Buffer.concat(__spreadArray([ - mt.getLeafHash(leaf_index), - Buffer.from([proof.length]), - Buffer.from([n_response_elements]) - ], __read(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; - } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer.concat([Buffer.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; - } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); - } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); - } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer.concat(__spreadArray([ - Buffer.from([n_returned_elements]), - Buffer.from([element_len]) - ], __read(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$1(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } - } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$1(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer.concat([Buffer.from([0]), el]); - this.addKnownPreimage(preimage); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); - } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); - } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); - - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$1(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$1(this, void 0, void 0, function () { - var response; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer.concat([ - Buffer.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$1(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer.concat([ - Buffer.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer.alloc(32, 0), - Buffer.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$1(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$1(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$1(this, void 0, void 0, function () { - return __generator$1(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer.from([]))]; - }); - }); - }; - return AppClient; - }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer.alloc(0); - var nExpiryHeight = Buffer.alloc(0); - var nVersionGroupId = Buffer.alloc(0); - var extraData = Buffer.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer.alloc(0); - var tree = Buffer.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); - } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); - } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } - else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } - } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; - } - - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@backpacker69/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); - } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); - }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; - } - return false; - } - - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); - - var TransportWebUSB$2 = {}; - - var Transport$1 = {}; - - var lib$2 = {}; - - var helpers = {}; - - Object.defineProperty(helpers, "__esModule", { - value: true - }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - - var errorClasses = {}; - var deserializers = {}; - - helpers.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; - - var createCustomErrorClass = helpers.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); - - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; - }; - - // inspired from https://github.com/programble/errio/blob/master/index.js - helpers.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } catch (e) { - // nothing - } - - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; - - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; - - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } - - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } else { - error = new Error(object.message); - } - - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - helpers.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; - - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - Object.defineProperty(lib$2, "__esModule", { - value: true - }); - lib$2.StatusCodes = lib$2.DBNotReset = lib$2.DBWrongPassword = lib$2.NoDBPathGiven = lib$2.FirmwareOrAppUpdateRequired = lib$2.LedgerAPI5xx = lib$2.LedgerAPI4xx = lib$2.GenuineCheckFailed = lib$2.PairingFailed = lib$2.SyncError = lib$2.FeeTooHigh = lib$2.FeeRequired = lib$2.FeeNotLoaded = lib$2.CantScanQRCode = lib$2.ETHAddressNonEIP = lib$2.WrongAppForCurrency = lib$2.WrongDeviceForAccount = lib$2.WebsocketConnectionFailed = lib$2.WebsocketConnectionError = lib$2.DeviceShouldStayInApp = lib$2.TransportWebUSBGestureRequired = lib$2.TransportInterfaceNotAvailable = lib$2.TransportOpenUserCancelled = lib$2.UserRefusedOnDevice = lib$2.UserRefusedAllowManager = lib$2.UserRefusedFirmwareUpdate = lib$2.UserRefusedAddress = lib$2.UserRefusedDeviceNameChange = lib$2.UpdateYourApp = lib$2.UnavailableTezosOriginatedAccountSend = lib$2.UnavailableTezosOriginatedAccountReceive = lib$2.RecipientRequired = lib$2.MCUNotGenuineToDashboard = lib$2.UnexpectedBootloader = lib$2.TimeoutTagged = lib$2.RecommendUndelegation = lib$2.RecommendSubAccountsToEmpty = lib$2.PasswordIncorrectError = lib$2.PasswordsDontMatchError = lib$2.GasLessThanEstimate = lib$2.NotSupportedLegacyAddress = lib$2.NotEnoughGas = lib$2.NoAccessToCamera = lib$2.NotEnoughBalanceBecauseDestinationNotCreated = lib$2.NotEnoughSpendableBalance = lib$2.NotEnoughBalanceInParentAccount = lib$2.NotEnoughBalanceToDelegate = lib$2.NotEnoughBalance = lib$2.NoAddressesFound = lib$2.NetworkDown = lib$2.ManagerUninstallBTCDep = lib$2.ManagerNotEnoughSpaceError = lib$2.ManagerFirmwareNotEnoughSpaceError = lib$2.ManagerDeviceLockedError = lib$2.ManagerAppDepUninstallRequired = lib$2.ManagerAppDepInstallRequired = lib$2.ManagerAppRelyOnBTCError = lib$2.ManagerAppAlreadyInstalledError = lib$2.LedgerAPINotAvailable = lib$2.LedgerAPIErrorWithMessage = lib$2.LedgerAPIError = lib$2.UnknownMCU = lib$2.LatestMCUInstalledError = lib$2.InvalidAddressBecauseDestinationIsAlsoSource = lib$2.InvalidAddress = lib$2.InvalidXRPTag = lib$2.HardResetFail = lib$2.FeeEstimationFailed = lib$2.EthAppPleaseEnableContractData = lib$2.EnpointConfigError = lib$2.DisconnectedDeviceDuringOperation = lib$2.DisconnectedDevice = lib$2.DeviceSocketNoBulkStatus = lib$2.DeviceSocketFail = lib$2.DeviceNameInvalid = lib$2.DeviceHalted = lib$2.DeviceInOSUExpected = lib$2.DeviceOnDashboardUnexpected = lib$2.DeviceOnDashboardExpected = lib$2.DeviceNotGenuineError = lib$2.DeviceGenuineSocketEarlyClose = lib$2.DeviceAppVerifyNotSupported = lib$2.CurrencyNotSupported = lib$2.CashAddrNotSupported = lib$2.CantOpenDevice = lib$2.BtcUnmatchedApp = lib$2.BluetoothRequired = lib$2.AmountRequired = lib$2.AccountNotSupported = lib$2.AccountNameRequiredError = lib$2.addCustomErrorDeserializer = lib$2.createCustomErrorClass = lib$2.deserializeError = lib$2.serializeError = undefined; - lib$2.TransportError = TransportError; - lib$2.getAltStatusMessage = getAltStatusMessage; - lib$2.TransportStatusError = TransportStatusError; - - var _helpers = helpers; - - lib$2.serializeError = _helpers.serializeError; - lib$2.deserializeError = _helpers.deserializeError; - lib$2.createCustomErrorClass = _helpers.createCustomErrorClass; - lib$2.addCustomErrorDeserializer = _helpers.addCustomErrorDeserializer; - lib$2.AccountNameRequiredError = (0, _helpers.createCustomErrorClass)("AccountNameRequired"); - lib$2.AccountNotSupported = (0, _helpers.createCustomErrorClass)("AccountNotSupported"); - lib$2.AmountRequired = (0, _helpers.createCustomErrorClass)("AmountRequired"); - lib$2.BluetoothRequired = (0, _helpers.createCustomErrorClass)("BluetoothRequired"); - lib$2.BtcUnmatchedApp = (0, _helpers.createCustomErrorClass)("BtcUnmatchedApp"); - lib$2.CantOpenDevice = (0, _helpers.createCustomErrorClass)("CantOpenDevice"); - lib$2.CashAddrNotSupported = (0, _helpers.createCustomErrorClass)("CashAddrNotSupported"); - lib$2.CurrencyNotSupported = (0, _helpers.createCustomErrorClass)("CurrencyNotSupported"); - lib$2.DeviceAppVerifyNotSupported = (0, _helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - lib$2.DeviceGenuineSocketEarlyClose = (0, _helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - lib$2.DeviceNotGenuineError = (0, _helpers.createCustomErrorClass)("DeviceNotGenuine"); - lib$2.DeviceOnDashboardExpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); - lib$2.DeviceOnDashboardUnexpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); - lib$2.DeviceInOSUExpected = (0, _helpers.createCustomErrorClass)("DeviceInOSUExpected"); - lib$2.DeviceHalted = (0, _helpers.createCustomErrorClass)("DeviceHalted"); - lib$2.DeviceNameInvalid = (0, _helpers.createCustomErrorClass)("DeviceNameInvalid"); - lib$2.DeviceSocketFail = (0, _helpers.createCustomErrorClass)("DeviceSocketFail"); - lib$2.DeviceSocketNoBulkStatus = (0, _helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - lib$2.DisconnectedDevice = (0, _helpers.createCustomErrorClass)("DisconnectedDevice"); - lib$2.DisconnectedDeviceDuringOperation = (0, _helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - lib$2.EnpointConfigError = (0, _helpers.createCustomErrorClass)("EnpointConfig"); - lib$2.EthAppPleaseEnableContractData = (0, _helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); - lib$2.FeeEstimationFailed = (0, _helpers.createCustomErrorClass)("FeeEstimationFailed"); - lib$2.HardResetFail = (0, _helpers.createCustomErrorClass)("HardResetFail"); - lib$2.InvalidXRPTag = (0, _helpers.createCustomErrorClass)("InvalidXRPTag"); - lib$2.InvalidAddress = (0, _helpers.createCustomErrorClass)("InvalidAddress"); - lib$2.InvalidAddressBecauseDestinationIsAlsoSource = (0, _helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - lib$2.LatestMCUInstalledError = (0, _helpers.createCustomErrorClass)("LatestMCUInstalledError"); - lib$2.UnknownMCU = (0, _helpers.createCustomErrorClass)("UnknownMCU"); - lib$2.LedgerAPIError = (0, _helpers.createCustomErrorClass)("LedgerAPIError"); - lib$2.LedgerAPIErrorWithMessage = (0, _helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - lib$2.LedgerAPINotAvailable = (0, _helpers.createCustomErrorClass)("LedgerAPINotAvailable"); - lib$2.ManagerAppAlreadyInstalledError = (0, _helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - lib$2.ManagerAppRelyOnBTCError = (0, _helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); - lib$2.ManagerAppDepInstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); - lib$2.ManagerAppDepUninstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); - lib$2.ManagerDeviceLockedError = (0, _helpers.createCustomErrorClass)("ManagerDeviceLocked"); - lib$2.ManagerFirmwareNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); - lib$2.ManagerNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); - lib$2.ManagerUninstallBTCDep = (0, _helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); - lib$2.NetworkDown = (0, _helpers.createCustomErrorClass)("NetworkDown"); - lib$2.NoAddressesFound = (0, _helpers.createCustomErrorClass)("NoAddressesFound"); - lib$2.NotEnoughBalance = (0, _helpers.createCustomErrorClass)("NotEnoughBalance"); - lib$2.NotEnoughBalanceToDelegate = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); - lib$2.NotEnoughBalanceInParentAccount = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); - lib$2.NotEnoughSpendableBalance = (0, _helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); - lib$2.NotEnoughBalanceBecauseDestinationNotCreated = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - lib$2.NoAccessToCamera = (0, _helpers.createCustomErrorClass)("NoAccessToCamera"); - lib$2.NotEnoughGas = (0, _helpers.createCustomErrorClass)("NotEnoughGas"); - lib$2.NotSupportedLegacyAddress = (0, _helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); - lib$2.GasLessThanEstimate = (0, _helpers.createCustomErrorClass)("GasLessThanEstimate"); - lib$2.PasswordsDontMatchError = (0, _helpers.createCustomErrorClass)("PasswordsDontMatch"); - lib$2.PasswordIncorrectError = (0, _helpers.createCustomErrorClass)("PasswordIncorrect"); - lib$2.RecommendSubAccountsToEmpty = (0, _helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); - lib$2.RecommendUndelegation = (0, _helpers.createCustomErrorClass)("RecommendUndelegation"); - lib$2.TimeoutTagged = (0, _helpers.createCustomErrorClass)("TimeoutTagged"); - lib$2.UnexpectedBootloader = (0, _helpers.createCustomErrorClass)("UnexpectedBootloader"); - lib$2.MCUNotGenuineToDashboard = (0, _helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); - lib$2.RecipientRequired = (0, _helpers.createCustomErrorClass)("RecipientRequired"); - lib$2.UnavailableTezosOriginatedAccountReceive = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); - lib$2.UnavailableTezosOriginatedAccountSend = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); - lib$2.UpdateYourApp = (0, _helpers.createCustomErrorClass)("UpdateYourApp"); - lib$2.UserRefusedDeviceNameChange = (0, _helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); - lib$2.UserRefusedAddress = (0, _helpers.createCustomErrorClass)("UserRefusedAddress"); - lib$2.UserRefusedFirmwareUpdate = (0, _helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - lib$2.UserRefusedAllowManager = (0, _helpers.createCustomErrorClass)("UserRefusedAllowManager"); - lib$2.UserRefusedOnDevice = (0, _helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - lib$2.TransportOpenUserCancelled = (0, _helpers.createCustomErrorClass)("TransportOpenUserCancelled"); - lib$2.TransportInterfaceNotAvailable = (0, _helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); - lib$2.TransportWebUSBGestureRequired = (0, _helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); - lib$2.DeviceShouldStayInApp = (0, _helpers.createCustomErrorClass)("DeviceShouldStayInApp"); - lib$2.WebsocketConnectionError = (0, _helpers.createCustomErrorClass)("WebsocketConnectionError"); - lib$2.WebsocketConnectionFailed = (0, _helpers.createCustomErrorClass)("WebsocketConnectionFailed"); - lib$2.WrongDeviceForAccount = (0, _helpers.createCustomErrorClass)("WrongDeviceForAccount"); - lib$2.WrongAppForCurrency = (0, _helpers.createCustomErrorClass)("WrongAppForCurrency"); - lib$2.ETHAddressNonEIP = (0, _helpers.createCustomErrorClass)("ETHAddressNonEIP"); - lib$2.CantScanQRCode = (0, _helpers.createCustomErrorClass)("CantScanQRCode"); - lib$2.FeeNotLoaded = (0, _helpers.createCustomErrorClass)("FeeNotLoaded"); - lib$2.FeeRequired = (0, _helpers.createCustomErrorClass)("FeeRequired"); - lib$2.FeeTooHigh = (0, _helpers.createCustomErrorClass)("FeeTooHigh"); - lib$2.SyncError = (0, _helpers.createCustomErrorClass)("SyncError"); - lib$2.PairingFailed = (0, _helpers.createCustomErrorClass)("PairingFailed"); - lib$2.GenuineCheckFailed = (0, _helpers.createCustomErrorClass)("GenuineCheckFailed"); - lib$2.LedgerAPI4xx = (0, _helpers.createCustomErrorClass)("LedgerAPI4xx"); - lib$2.LedgerAPI5xx = (0, _helpers.createCustomErrorClass)("LedgerAPI5xx"); - lib$2.FirmwareOrAppUpdateRequired = (0, _helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); - - // db stuff, no need to translate - lib$2.NoDBPathGiven = (0, _helpers.createCustomErrorClass)("NoDBPathGiven"); - lib$2.DBWrongPassword = (0, _helpers.createCustomErrorClass)("DBWrongPassword"); - lib$2.DBNotReset = (0, _helpers.createCustomErrorClass)("DBNotReset"); - - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); - - (0, _helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); - - var StatusCodes = lib$2.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, _helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); - - Object.defineProperty(Transport$1, "__esModule", { - value: true - }); - Transport$1.getAltStatusMessage = Transport$1.StatusCodes = Transport$1.TransportStatusError = Transport$1.TransportError = undefined; - - var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _events2 = require$$0__default$3["default"]; - - var _events3 = _interopRequireDefault$1(_events2); - - var _errors$2 = lib$2; - - function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - function _asyncToGenerator$2(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - Transport$1.TransportError = _errors$2.TransportError; - Transport$1.TransportStatusError = _errors$2.TransportStatusError; - Transport$1.StatusCodes = _errors$2.StatusCodes; - Transport$1.getAltStatusMessage = _errors$2.getAltStatusMessage; - - /** - */ - - - /** - */ - - - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck$1(this, Transport); - - this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [_errors$2.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new _errors$2.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer.concat([Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data])); - - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new _errors$2.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } - - throw new _errors$2.TransportError("Transport race condition", "RaceCondition"); - - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); - - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); - - case 10: - _context2.prev = 10; - - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); - - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); - - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); - - this._appAPIlock = null; - } - - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - - - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - _createClass$1(Transport, [{ - key: "on", - - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } - - /** - * Stop listening to an event on an instance of transport. - */ - - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; - - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - - /** - * Enable or not logs of the binary exchange - */ - - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; - - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new _errors$2.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new _errors$2.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new _errors$2.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - Transport$1.default = Transport; - - var hidFraming = {}; - - Object.defineProperty(hidFraming, "__esModule", { - value: true - }); - - var _errors$1 = lib$2; - - var Tag = 0x05; - - function asUInt16BE(value) { - var b = Buffer.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - - var initialAcc = { - data: Buffer.alloc(0), - dataLength: 0, - sequence: 0 - }; - - /** - * - */ - var createHIDframing = function createHIDframing(channel, packetSize) { - return { - makeBlocks: function makeBlocks(apdu) { - var data = Buffer.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer.concat([data, // fill data with padding - Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); - - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function reduceResponse(acc, chunk) { - var _ref = acc || initialAcc, - data = _ref.data, - dataLength = _ref.dataLength, - sequence = _ref.sequence; - - if (chunk.readUInt16BE(0) !== channel) { - throw new _errors$1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new _errors$1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new _errors$1.TransportError("Invalid sequence", "InvalidSequence"); - } - - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - - hidFraming.default = createHIDframing; - - var lib$1 = {}; - - Object.defineProperty(lib$1, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - /** - * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) - * - ** Model - * Ledger Nano S : 0x10 - * Ledger Blue : 0x00 - * Ledger Nano X : 0x40 - * - ** Interface support bitfield - * Generic HID : 0x01 - * Keyboard HID : 0x02 - * U2F : 0x04 - * CCID : 0x08 - * WebUSB : 0x10 - */ - - lib$1.IIGenericHID = 0x01; - lib$1.IIKeyboardHID = 0x02; - lib$1.IIU2F = 0x04; - lib$1.IICCID = 0x08; - lib$1.IIWebUSB = 0x10; - - var devices = { - blue: { - id: "blue", - productName: "Ledger Blue", - productIdMM: 0x00, - legacyUsbProductId: 0x0000, - usbOnly: true, - memorySize: 480 * 1024, - blockSize: 4 * 1024 - }, - nanoS: { - id: "nanoS", - productName: "Ledger Nano S", - productIdMM: 0x10, - legacyUsbProductId: 0x0001, - usbOnly: true, - memorySize: 320 * 1024, - blockSize: 4 * 1024 - }, - nanoX: { - id: "nanoX", - productName: "Ledger Nano X", - productIdMM: 0x40, - legacyUsbProductId: 0x0004, - usbOnly: false, - memorySize: 2 * 1024 * 1024, - blockSize: 4 * 1024, - bluetoothSpec: [{ - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" - }, { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572" - }] - } - }; - - var productMap = { - Blue: "blue", - "Nano S": "nanoS", - "Nano X": "nanoX" - }; - - // $FlowFixMe - var devicesList = Object.values(devices); - - /** - * - */ - lib$1.ledgerUSBVendorId = 0x2c97; - - /** - * - */ - lib$1.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; - - /** - * - */ - lib$1.identifyUSBProductId = function identifyUSBProductId(usbProductId) { - var legacy = devicesList.find(function (d) { - return d.legacyUsbProductId === usbProductId; - }); - if (legacy) return legacy; - - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { - return d.productIdMM === mm; - }); - return deviceModel; - }; - - lib$1.identifyProductName = function identifyProductName(productName) { - var productId = productMap[productName]; - var deviceModel = devicesList.find(function (d) { - return d.id === productId; - }); - - return deviceModel; - }; - - var bluetoothServices = []; - var serviceUuidToInfos = {}; - - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; - - if (_bluetoothSpec) { - for (var i = 0; i < _bluetoothSpec.length; i++) { - var spec = _bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); - } - } - } - - /** - * - */ - lib$1.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - lib$1.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; - - var lib = {}; - - Object.defineProperty(lib, "__esModule", { - value: true - }); - - - /** - * A Log object - */ - var id = 0; - var subscribers = []; - - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - lib.log = function log(type, message, data) { - var obj = { type: type, id: String(++id), date: new Date() }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = lib.listen = function listen(cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } - - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; - - var webusb = {}; - - Object.defineProperty(webusb, "__esModule", { - value: true - }); - webusb.isSupported = webusb.getFirstLedgerDevice = webusb.getLedgerDevices = webusb.requestLedgerDevice = undefined; - - var requestLedgerDevice = webusb.requestLedgerDevice = function () { - var _ref = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var device; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return navigator.usb.requestDevice({ filters: ledgerDevices }); - - case 2: - device = _context.sent; - return _context.abrupt("return", device); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function requestLedgerDevice() { - return _ref.apply(this, arguments); - }; - }(); - - var getLedgerDevices = webusb.getLedgerDevices = function () { - var _ref2 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var devices; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return navigator.usb.getDevices(); - - case 2: - devices = _context2.sent; - return _context2.abrupt("return", devices.filter(function (d) { - return d.vendorId === _devices$1.ledgerUSBVendorId; - })); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function getLedgerDevices() { - return _ref2.apply(this, arguments); - }; - }(); - - webusb.getFirstLedgerDevice = function () { - var _ref3 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var existingDevices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getLedgerDevices(); - - case 2: - existingDevices = _context3.sent; - - if (!(existingDevices.length > 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", existingDevices[0]); - - case 5: - return _context3.abrupt("return", requestLedgerDevice()); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); - - var _devices$1 = lib$1; - - function _asyncToGenerator$1(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - var ledgerDevices = [{ vendorId: _devices$1.ledgerUSBVendorId }]; - - webusb.isSupported = function isSupported() { - return Promise.resolve(!!navigator && - // $FlowFixMe - !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; - - Object.defineProperty(TransportWebUSB$2, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _hwTransport = Transport$1; - - var _hwTransport2 = _interopRequireDefault(_hwTransport); - - var _hidFraming = hidFraming; - - var _hidFraming2 = _interopRequireDefault(_hidFraming); - - var _devices = lib$1; - - var _logs = lib; - - var _errors = lib$2; - - var _webusb = webusb; - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - - var configurationValue = 1; - var endpointNumber = 3; - - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ - - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); - - function TransportWebUSB(device, interfaceNumber) { - _classCallCheck(this, TransportWebUSB); - - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); - - _initialiseProps.call(_this); - - _this.device = device; - _this.interfaceNumber = interfaceNumber; - _this.deviceModel = (0, _devices.identifyUSBProductId)(device.productId); - return _this; - } - - /** - * Check if WebUSB transport is supported. - */ - - - /** - * List the WebUSB devices that was previously authorized by the user. - */ - - - /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! - */ - - - _createClass(TransportWebUSB, [{ - key: "close", - - - /** - * Release the transport device - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.exchangeBusyPromise; - - case 2: - _context.next = 4; - return this.device.releaseInterface(this.interfaceNumber); - - case 4: - _context.next = 6; - return this.device.reset(); - - case 6: - _context.next = 8; - return this.device.close(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _ref.apply(this, arguments); - } - - return close; - }() - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey() {} - }], [{ - key: "request", - - - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var device; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return (0, _webusb.requestLedgerDevice)(); - - case 2: - device = _context2.sent; - return _context2.abrupt("return", TransportWebUSB.open(device)); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function request() { - return _ref2.apply(this, arguments); - } - - return request; - }() - - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ - - }, { - key: "openConnected", - value: function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var devices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return (0, _webusb.getLedgerDevices)(); - - case 2: - devices = _context3.sent; - - if (!(devices.length === 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", null); - - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function openConnected() { - return _ref3.apply(this, arguments); - } - - return openConnected; - }() - - /** - * Create a Ledger transport with a USBDevice - */ - - }, { - key: "open", - value: function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { - var iface, interfaceNumber, transport, onDisconnect; - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return device.open(); - - case 2: - if (!(device.configuration === null)) { - _context4.next = 5; - break; - } - - _context4.next = 5; - return device.selectConfiguration(configurationValue); - - case 5: - _context4.next = 7; - return device.reset(); - - case 7: - iface = device.configurations[0].interfaces.find(function (_ref5) { - var alternates = _ref5.alternates; - return alternates.some(function (a) { - return a.interfaceClass === 255; - }); - }); - - if (iface) { - _context4.next = 10; - break; - } - - throw new _errors.TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); - - case 10: - interfaceNumber = iface.interfaceNumber; - _context4.prev = 11; - _context4.next = 14; - return device.claimInterface(interfaceNumber); - - case 14: - _context4.next = 21; - break; - - case 16: - _context4.prev = 16; - _context4.t0 = _context4["catch"](11); - _context4.next = 20; - return device.close(); - - case 20: - throw new _errors.TransportInterfaceNotAvailable(_context4.t0.message); - - case 21: - transport = new TransportWebUSB(device, interfaceNumber); - - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new _errors.DisconnectedDevice()); - } - }; - // $FlowFixMe - - - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); - - case 25: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[11, 16]]); - })); - - function open(_x) { - return _ref4.apply(this, arguments); - } - - return open; - }() - }]); - - return TransportWebUSB; - }(_hwTransport2.default); - - TransportWebUSB.isSupported = _webusb.isSupported; - TransportWebUSB.list = _webusb.getLedgerDevices; - - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - (0, _webusb.getFirstLedgerDevice)().then(function (device) { - if (!unsubscribed) { - var deviceModel = (0, _devices.identifyUSBProductId)(device.productId); - observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); - observer.complete(); - } - }, function (error) { - if (window.DOMException && error instanceof window.DOMException && error.code === 18) { - observer.error(new _errors.TransportWebUSBGestureRequired(error.message)); - } else { - observer.error(new _errors.TransportOpenUserCancelled(error.message)); - } - }); - function unsubscribe() { - unsubscribed = true; - } - return { unsubscribe: unsubscribe }; - }; - - var _initialiseProps = function _initialiseProps() { - var _this2 = this; - - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; - - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; - - this.exchange = function (apdu) { - return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - channel = _this2.channel, packetSize = _this2.packetSize; - - (0, _logs.log)("apdu", "=> " + apdu.toString("hex")); - - framing = (0, _hidFraming2.default)(channel, packetSize); - - // Write... - - blocks = framing.makeBlocks(apdu); - i = 0; - - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } - - (0, _logs.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); - - case 9: - i++; - _context5.next = 5; - break; - - case 12: - - // Read... - result = void 0; - acc = void 0; - - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } - - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); - - case 17: - r = _context5.sent; - buffer = Buffer.from(r.data.buffer); - - (0, _logs.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; - - case 23: - - (0, _logs.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); - - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5, _this2); - }))).catch(function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this2._emitDisconnect(e); - throw new _errors.DisconnectedDeviceDuringOperation(e.message); - } - throw e; - }); - }; - }; - - var _default = TransportWebUSB$2.default = TransportWebUSB; - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': _default - }, [TransportWebUSB$2])); - - exports.Btc = Btc$1; - exports.TransportWebUSB = TransportWebUSB$1; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); -//# sourceMappingURL=build.js.map +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("crypto"),require("buffer"),require("stream"),require("events"),require("util")):"function"==typeof define&&define.amd?define(["exports","crypto","buffer","stream","events","util"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={},t.require$$0$1,t.require$$0$2,t.require$$0$3,t.require$$0$4,t.require$$1)}(this,(function(t,e,r,n,i,o){"use strict";function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function u(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var a=s(e),h=s(r),c=s(n),f=s(i),l=s(o),p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof y?e:y,o=Object.create(i.prototype),s=new P(n||[]);return o._invoke=function(t,e,r){var n=f;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return k()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===f)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=c(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function c(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var f="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function y(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(M([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=y.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=c(t[i],t,o);if("throw"!==a.type){var h=a.arg,f=h.value;return f&&"object"==typeof f&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(f).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=c(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function A(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function M(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),A(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;A(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:M(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});var d="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},g=[],y=[],v="undefined"!=typeof Uint8Array?Uint8Array:Array,m=!1;function w(){m=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+g[i>>12&63]+g[i>>6&63]+g[63&i]);return o.join("")}function E(t){var e;m||w();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=g[e>>2],i+=g[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=g[e>>10],i+=g[e>>4&63],i+=g[e<<2&63],i+="="),o.push(i),o.join("")}function _(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,c=-7,f=r?i-1:0,l=r?-1:1,p=t[e+f];for(f+=l,o=p&(1<<-c)-1,p>>=-c,c+=u;c>0;o=256*o+t[e+f],f+=l,c-=8);for(s=o&(1<<-c)-1,o>>=-c,c+=n;c>0;s=256*s+t[e+f],f+=l,c-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function S(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,c=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=c):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+f>=1?l/a:l*Math.pow(2,1-f))*a>=2&&(s++,a/=2),s+f>=c?(u=0,s=c):s+f>=1?(u=(e*a-1)*Math.pow(2,i),s+=f):(u=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var I={}.toString,T=Array.isArray||function(t){return"[object Array]"==I.call(t)};function O(){return P.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function A(t,e){if(O()=O())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+O().toString(16)+" bytes");return 0|t}function C(t){return!(null==t||!t._isBuffer)}function U(t,e){if(C(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return at(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ht(t).length;default:if(n)return at(t).length;e=(""+e).toLowerCase(),n=!0}}function L(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return J(this,e,r);case"utf8":case"utf-8":return $(this,e,r);case"ascii":return X(this,e,r);case"latin1":case"binary":return Y(this,e,r);case"base64":return W(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function D(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=P.from(e,n)),C(e))return 0===e.length?-1:H(t,e,r,n,i);if("number"==typeof e)return e&=255,P.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):H(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function H(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var c=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var f=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function W(t,e,r){return 0===e&&r===t.length?E(t):E(t.slice(e,r))}function $(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+f<=r)switch(f){case 1:h<128&&(c=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(c=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(c=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(c=a)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=f}return function(t){var e=t.length;if(e<=z)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},P.prototype.compare=function(t,e,r,n,i){if(!C(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),c=0;ci)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return F(this,t,e,r);case"utf8":case"utf-8":return q(this,t,e,r);case"ascii":return j(this,t,e,r);case"latin1":case"binary":return G(this,t,e,r);case"base64":return K(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},P.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var z=4096;function X(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function tt(t,e,r,n,i,o){if(!C(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function et(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function rt(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function nt(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function it(t,e,r,n,i){return i||nt(t,0,r,4),S(t,e,r,n,23,4),r+4}function ot(t,e,r,n,i){return i||nt(t,0,r,8),S(t,e,r,n,52,8),r+8}P.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},P.prototype.readUInt8=function(t,e){return e||Q(t,1,this.length),this[t]},P.prototype.readUInt16LE=function(t,e){return e||Q(t,2,this.length),this[t]|this[t+1]<<8},P.prototype.readUInt16BE=function(t,e){return e||Q(t,2,this.length),this[t]<<8|this[t+1]},P.prototype.readUInt32LE=function(t,e){return e||Q(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},P.prototype.readUInt32BE=function(t,e){return e||Q(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},P.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Q(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},P.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Q(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},P.prototype.readInt8=function(t,e){return e||Q(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},P.prototype.readInt16LE=function(t,e){e||Q(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},P.prototype.readInt16BE=function(t,e){e||Q(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},P.prototype.readInt32LE=function(t,e){return e||Q(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},P.prototype.readInt32BE=function(t,e){return e||Q(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},P.prototype.readFloatLE=function(t,e){return e||Q(t,4,this.length),_(this,t,!0,23,4)},P.prototype.readFloatBE=function(t,e){return e||Q(t,4,this.length),_(this,t,!1,23,4)},P.prototype.readDoubleLE=function(t,e){return e||Q(t,8,this.length),_(this,t,!0,52,8)},P.prototype.readDoubleBE=function(t,e){return e||Q(t,8,this.length),_(this,t,!1,52,8)},P.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||tt(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},P.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,1,255,0),P.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},P.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,65535,0),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):et(this,t,e,!0),e+2},P.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,65535,0),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):et(this,t,e,!1),e+2},P.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,4294967295,0),P.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):rt(this,t,e,!0),e+4},P.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,4294967295,0),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):rt(this,t,e,!1),e+4},P.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);tt(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},P.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);tt(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},P.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,1,127,-128),P.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},P.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,32767,-32768),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):et(this,t,e,!0),e+2},P.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,32767,-32768),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):et(this,t,e,!1),e+2},P.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,2147483647,-2147483648),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):rt(this,t,e,!0),e+4},P.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):rt(this,t,e,!1),e+4},P.prototype.writeFloatLE=function(t,e,r){return it(this,t,e,!0,r)},P.prototype.writeFloatBE=function(t,e,r){return it(this,t,e,!1,r)},P.prototype.writeDoubleLE=function(t,e,r){return ot(this,t,e,!0,r)},P.prototype.writeDoubleBE=function(t,e,r){return ot(this,t,e,!1,r)},P.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!P.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ht(t){return function(t){var e,r,n,i,o,s;m||w();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new v(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=y[t.charCodeAt(e)]<<2|y[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=y[t.charCodeAt(e)]<<10|y[t.charCodeAt(e+1)]<<4|y[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(st,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ct(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ft(t){return null!=t&&(!!t._isBuffer||lt(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&<(t.slice(0,0))}(t))}function lt(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}const pt=2147483648;var dt=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=pt)throw new Error("Invalid child index");if("h"===o[2]||"H"===o[2]||"'"===o[2])n[i]+=pt;else if(0!=o[2].length)throw new Error("Invalid modifier")}return new dt(n)},dt.prototype.toPathArray=function(){return this.path},dt.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var gt=dt,yt=a.default.createHash,vt={exports:{}}; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +!function(t,e){var r=h.default,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(vt,vt.exports);var mt=vt.exports.Buffer;var wt=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var c=e[t.charCodeAt(r)];if(255===c)return;for(var f=0,l=o-1;(0!==c||f>>0,h[l]=c%256>>>0,c=c/256>>>0;if(0!==c)throw new Error("Non-zero carry");i=f,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=mt.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=mt.from(e)),!mt.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,c=new Uint8Array(a);i!==o;){for(var f=e[i],l=0,p=a-1;(0!==f||l>>0,c[p]=f%s>>>0,f=f/s>>>0;if(0!==f)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===c[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],c=[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],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,f=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;c+=(s=(i=0|t.words[d])*(o=0|e.words[p])+f)/67108864|0,f=67108863&s}r.words[h]=0|f,a=0|c}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=c[t],p=f[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),c=this.clone();if(a){for(u=0;!c.isZero();u++)s=c.andln(255),c.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,P=0|s[6],M=8191&P,k=P>>>13,x=0|s[7],N=8191&x,R=x>>>13,C=0|s[8],U=8191&C,L=C>>>13,D=0|s[9],B=8191&D,H=D>>>13,F=0|u[0],q=8191&F,j=F>>>13,G=0|u[1],K=8191&G,V=G>>>13,W=0|u[2],$=8191&W,z=W>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ct=0|u[8],ft=8191&ct,lt=ct>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(f,q))|0)+((8191&(i=(i=Math.imul(f,j))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,j))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,j))+Math.imul(g,q)|0,o=Math.imul(g,j);var vt=(h+(n=n+Math.imul(f,K)|0)|0)+((8191&(i=(i=i+Math.imul(f,V)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,j))+Math.imul(m,q)|0,o=Math.imul(m,j),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,V)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,V)|0;var mt=(h+(n=n+Math.imul(f,$)|0)|0)+((8191&(i=(i=i+Math.imul(f,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,j))+Math.imul(E,q)|0,o=Math.imul(E,j),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,V)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,V)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(f,Y)|0)|0)+((8191&(i=(i=i+Math.imul(f,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,j))+Math.imul(I,q)|0,o=Math.imul(I,j),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,V)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,V)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(f,Q)|0)|0)+((8191&(i=(i=i+Math.imul(f,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,j))+Math.imul(A,q)|0,o=Math.imul(A,j),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,V)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(f,rt)|0)|0)+((8191&(i=(i=i+Math.imul(f,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(M,q),i=(i=Math.imul(M,j))+Math.imul(k,q)|0,o=Math.imul(k,j),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,V)|0)+Math.imul(A,K)|0,o=o+Math.imul(A,V)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(f,ot)|0)|0)+((8191&(i=(i=i+Math.imul(f,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,j))+Math.imul(R,q)|0,o=Math.imul(R,j),n=n+Math.imul(M,K)|0,i=(i=i+Math.imul(M,V)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,V)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(f,at)|0)|0)+((8191&(i=(i=i+Math.imul(f,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(U,q),i=(i=Math.imul(U,j))+Math.imul(L,q)|0,o=Math.imul(L,j),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(M,$)|0,i=(i=i+Math.imul(M,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(f,ft)|0)|0)+((8191&(i=(i=i+Math.imul(f,lt)|0)+Math.imul(l,ft)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,j))+Math.imul(H,q)|0,o=Math.imul(H,j),n=n+Math.imul(U,K)|0,i=(i=i+Math.imul(U,V)|0)+Math.imul(L,K)|0,o=o+Math.imul(L,V)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(R,$)|0,o=o+Math.imul(R,z)|0,n=n+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ft)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ft)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(f,dt)|0)|0)+((8191&(i=(i=i+Math.imul(f,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(B,K),i=(i=Math.imul(B,V))+Math.imul(H,K)|0,o=Math.imul(H,V),n=n+Math.imul(U,$)|0,i=(i=i+Math.imul(U,z)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Y)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ft)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ft)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(B,$),i=(i=Math.imul(B,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(U,Y)|0,i=(i=i+Math.imul(U,J)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ft)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ft)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(B,Y),i=(i=Math.imul(B,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(U,Q)|0,i=(i=i+Math.imul(U,tt)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(R,rt)|0,o=o+Math.imul(R,nt)|0,n=n+Math.imul(M,ot)|0,i=(i=i+Math.imul(M,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ft)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ft)|0,o=o+Math.imul(I,lt)|0;var Pt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(B,Q),i=(i=Math.imul(B,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(U,rt)|0,i=(i=i+Math.imul(U,nt)|0)+Math.imul(L,rt)|0,o=o+Math.imul(L,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(R,ot)|0,o=o+Math.imul(R,st)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(O,ft)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ft)|0,o=o+Math.imul(A,lt)|0;var Mt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(B,rt),i=(i=Math.imul(B,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(U,ot)|0,i=(i=i+Math.imul(U,st)|0)+Math.imul(L,ot)|0,o=o+Math.imul(L,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(R,at)|0,o=o+Math.imul(R,ht)|0,n=n+Math.imul(M,ft)|0,i=(i=i+Math.imul(M,lt)|0)+Math.imul(k,ft)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(B,ot),i=(i=Math.imul(B,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(U,at)|0,i=(i=i+Math.imul(U,ht)|0)+Math.imul(L,at)|0,o=o+Math.imul(L,ht)|0,n=n+Math.imul(N,ft)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(R,ft)|0,o=o+Math.imul(R,lt)|0;var xt=(h+(n=n+Math.imul(M,dt)|0)|0)+((8191&(i=(i=i+Math.imul(M,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(B,at),i=(i=Math.imul(B,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(U,ft)|0,i=(i=i+Math.imul(U,lt)|0)+Math.imul(L,ft)|0,o=o+Math.imul(L,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(R,dt)|0))<<13)|0;h=((o=o+Math.imul(R,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(B,ft),i=(i=Math.imul(B,lt))+Math.imul(H,ft)|0,o=Math.imul(H,lt);var Rt=(h+(n=n+Math.imul(U,dt)|0)|0)+((8191&(i=(i=i+Math.imul(U,gt)|0)+Math.imul(L,dt)|0))<<13)|0;h=((o=o+Math.imul(L,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863;var Ct=(h+(n=Math.imul(B,dt))|0)+((8191&(i=(i=Math.imul(B,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=Pt,a[13]=Mt,a[14]=kt,a[15]=xt,a[16]=Nt,a[17]=Rt,a[18]=Ct,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==c||h>=i);h--){var f=0|this.words[h];this.words[h]=c<<26-o|f>>>o,c=f&u}return a&&0!==c&&(a.words[a.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;f--){var l=67108864*(0|n.words[o.length+f])+(0|n.words[o.length+f-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,f);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,f),n.isZero()||(n.negative^=1);u&&(u.words[f]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var c=n.clone(),f=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(c),s.isub(f)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(c),a.isub(f)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,c=1;0==(e.words[0]&c)&&h<26;++h,c<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var f=0,l=1;0==(n.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(n.iushrn(f);f-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,h).cmp(a);)c.redIAdd(a);for(var f=this.pow(c,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],c=a-1;c>=0;c--){var f=h>>c&1;o!==r[0]&&(o=this.sqr(o)),0!==f||0!==s?(s<<=1,s|=f,(4===++u||0===n&&0===c)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,p)}(Ft);var qt={},jt="6.5.4",Gt={},Kt=Vt;function Vt(t,e){if(!t)throw new Error(e||"Assertion failed")}Vt.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Wt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Wt),function(t){var e=t,r=Ft.exports,n=Kt,i=Wt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Gt);var $t,zt={exports:{}};function Xt(t){this.rand=t}if(zt.exports=function(t){return $t||($t=new Xt(null)),$t.generate(t)},zt.exports.Rand=Xt,Xt.prototype.generate=function(t){return this._rand(t)},Xt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ie=ne;function oe(t,e){this.curve=t,this.type=e,this.precomputed=null}ne.prototype.point=function(){throw new Error("Not implemented")},ne.prototype.validate=function(){throw new Error("Not implemented")},ne.prototype._fixedNafMul=function(t,e){re(t.precomputed);var r=t._getDoubles(),n=te(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),c=this.jpoint(null,null,null),f=i;f>0;f--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];re(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},ne.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,c=this._wnafT3,f=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=ee(r[p],r[d]);for(f=Math.max(v[0].length,f),c[p]=new Array(f),c[d]=new Array(f),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},oe.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},de.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},de.prototype.pointFromX=function(t,e){(t=new ce(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},de.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},de.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ye.prototype.isInfinity=function(){return this.inf},ye.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ye.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ye.prototype.getX=function(){return this.x.fromRed()},ye.prototype.getY=function(){return this.y.fromRed()},ye.prototype.mul=function(t){return t=new ce(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ye.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ye.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ye.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ye.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ye.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},fe(ve,le.BasePoint),de.prototype.jpoint=function(t,e,r){return new ve(this,t,e,r)},ve.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},ve.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},ve.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),c=h.redMul(u),f=n.redMul(h),l=a.redSqr().redIAdd(c).redISub(f).redISub(f),p=a.redMul(f.redISub(l)).redISub(o.redMul(c)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},ve.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),c=r.redMul(a),f=u.redSqr().redIAdd(h).redISub(c).redISub(c),l=u.redMul(c.redISub(f)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(f,l,p)},ve.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},ve.prototype.inspect=function(){return this.isInfinity()?"":""},ve.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var me=Ft.exports,we=se.exports,be=ie,Ee=Gt;function _e(t){be.call(this,"mont",t),this.a=new me(t.a,16).toRed(this.red),this.b=new me(t.b,16).toRed(this.red),this.i4=new me(4).toRed(this.red).redInvm(),this.two=new me(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}we(_e,be);var Se=_e;function Ie(t,e,r){be.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new me(e,16),this.z=new me(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}_e.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},we(Ie,be.BasePoint),_e.prototype.decodePoint=function(t,e){return this.point(Ee.toArray(t,e),1)},_e.prototype.point=function(t,e){return new Ie(this,t,e)},_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},Ie.prototype.precompute=function(){},Ie.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1]||t.one)},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Ie.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},Ie.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},Ie.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},Ie.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},Ie.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Te=Gt,Oe=Ft.exports,Ae=se.exports,Pe=ie,Me=Te.assert;function ke(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,Pe.call(this,"edwards",t),this.a=new Oe(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new Oe(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new Oe(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Me(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}Ae(ke,Pe);var xe=ke;function Ne(t,e,r,n,i){Pe.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new Oe(e,16),this.y=new Oe(r,16),this.z=n?new Oe(n,16):this.curve.one,this.t=i&&new Oe(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}ke.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},ke.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},ke.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},ke.prototype.pointFromX=function(t,e){(t=new Oe(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},ke.prototype.pointFromY=function(t,e){(t=new Oe(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},ke.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},Ae(Ne,Pe.BasePoint),ke.prototype.pointFromJSON=function(t){return Ne.fromJSON(this,t)},ke.prototype.point=function(t,e,r,n){return new Ne(this,t,e,r,n)},Ne.fromJSON=function(t,e){return new Ne(t,e[0],e[1],e[2])},Ne.prototype.inspect=function(){return this.isInfinity()?"":""},Ne.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ne.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),c=i.redMul(u),f=s.redMul(o);return this.curve.point(a,h,f,c)},Ne.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ne.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ne.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),c=u.redMul(a),f=o.redMul(a),l=s.redMul(u);return this.curve.point(h,c,l,f)},Ne.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),c=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),f=n.redMul(a).redMul(c);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(f,e,r)},Ne.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ne.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ne.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ne.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ne.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ne.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ne.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ne.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ne.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ne.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ne.prototype.toP=Ne.prototype.normalize,Ne.prototype.mixedAdd=Ne.prototype.add,function(t){var e=t;e.base=ie,e.short=ge,e.mont=Se,e.edwards=xe}(Jt);var Re={},Ce={},Ue={},Le=Kt,De=se.exports;function Be(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function He(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Fe(t){return 1===t.length?"0"+t:t}function qe(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ue.inherits=De,Ue.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Be(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ue.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ue.rotr32=function(t,e){return t>>>e|t<<32-e},Ue.rotl32=function(t,e){return t<>>32-e},Ue.sum32=function(t,e){return t+e>>>0},Ue.sum32_3=function(t,e,r){return t+e+r>>>0},Ue.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ue.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ue.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ue.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ue.sum64_lo=function(t,e,r,n){return e+n>>>0},Ue.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ue.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ue.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var c=0,f=e;return c+=(f=f+n>>>0)>>0)>>0)>>0)>>0},Ue.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ue.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ue.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ue.shr64_hi=function(t,e,r){return t>>>r},Ue.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var je={},Ge=Ue,Ke=Kt;function Ve(){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}je.BlockHash=Ve,Ve.prototype.update=function(t,e){if(t=Ge.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ge.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},$e.g1_256=function(t){return ze(t,17)^ze(t,19)^t>>>10};var Ze=Ue,Qe=je,tr=$e,er=Ze.rotl32,rr=Ze.sum32,nr=Ze.sum32_5,ir=tr.ft_1,or=Qe.BlockHash,sr=[1518500249,1859775393,2400959708,3395469782];function ur(){if(!(this instanceof ur))return new ur;or.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ze.inherits(ur,or);var ar=ur;ur.blockSize=512,ur.outSize=160,ur.hmacStrength=80,ur.padLength=64,ur.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),Pn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Un=Cn;Cn.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},Cn.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Nn.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Fn=Ft.exports,qn=Gt,jn=qn.assert;function Gn(t,e){if(t instanceof Gn)return t;this._importDER(t,e)||(jn(t.r&&t.s,"Signature without r or s"),this.r=new Fn(t.r,16),this.s=new Fn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Kn=Gn;function Vn(){this.place=0}function Wn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function $n(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Gn.prototype._importDER=function(t,e){t=qn.toArray(t,e);var r=new Vn;if(48!==t[r.place++])return!1;var n=Wn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Wn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Wn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Fn(o),this.s=new Fn(u),this.recoveryParam=null,!0},Gn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=$n(e),r=$n(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];zn(n,e.length),(n=n.concat(e)).push(2),zn(n,r.length);var i=n.concat(r),o=[48];return zn(o,i.length),o=o.concat(i),qn.encode(o,t)};var Xn=Ft.exports,Yn=Un,Jn=Gt,Zn=Re,Qn=zt.exports,ti=Jn.assert,ei=Hn,ri=Kn;function ni(t){if(!(this instanceof ni))return new ni(t);"string"==typeof t&&(ti(Object.prototype.hasOwnProperty.call(Zn,t),"Unknown curve "+t),t=Zn[t]),t instanceof Zn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var ii=ni;ni.prototype.keyPair=function(t){return new ei(this,t)},ni.prototype.keyFromPrivate=function(t,e){return ei.fromPrivate(this,t,e)},ni.prototype.keyFromPublic=function(t,e){return ei.fromPublic(this,t,e)},ni.prototype.genKeyPair=function(t){t||(t={});for(var e=new Yn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Qn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Xn(2));;){var i=new Xn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},ni.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},ni.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Xn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Yn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Xn(1)),h=0;;h++){var c=n.k?n.k(h):new Xn(u.generate(this.n.byteLength()));if(!((c=this._truncateToN(c,!0)).cmpn(1)<=0||c.cmp(a)>=0)){var f=this.g.mul(c);if(!f.isInfinity()){var l=f.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=c.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(f.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new ri({r:p,s:d,recoveryParam:g})}}}}}},ni.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Xn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new ri(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},ni.prototype.recoverPubKey=function(t,e,r,n){ti((3&r)===r,"The recovery param is more than two bits"),e=new ri(e,n);var i=this.n,o=new Xn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var c=e.r.invm(i),f=i.sub(o).mul(c).umod(i),l=u.mul(c).umod(i);return this.g.mulAdd(f,s,l)},ni.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new ri(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var oi=Gt,si=oi.assert,ui=oi.parseBytes,ai=oi.cachedProperty;function hi(t,e){this.eddsa=t,this._secret=ui(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=ui(e.pub)}hi.fromPublic=function(t,e){return e instanceof hi?e:new hi(t,{pub:e})},hi.fromSecret=function(t,e){return e instanceof hi?e:new hi(t,{secret:e})},hi.prototype.secret=function(){return this._secret},ai(hi,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ai(hi,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ai(hi,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ai(hi,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ai(hi,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ai(hi,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),hi.prototype.sign=function(t){return si(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},hi.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},hi.prototype.getSecret=function(t){return si(this._secret,"KeyPair is public only"),oi.encode(this.secret(),t)},hi.prototype.getPublic=function(t){return oi.encode(this.pubBytes(),t)};var ci=hi,fi=Ft.exports,li=Gt,pi=li.assert,di=li.cachedProperty,gi=li.parseBytes;function yi(t,e){this.eddsa=t,"object"!=typeof e&&(e=gi(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),pi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof fi&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}di(yi,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),di(yi,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),di(yi,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),di(yi,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),yi.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},yi.prototype.toHex=function(){return li.encode(this.toBytes(),"hex").toUpperCase()};var vi=yi,mi=Ce,wi=Re,bi=Gt,Ei=bi.assert,_i=bi.parseBytes,Si=ci,Ii=vi;function Ti(t){if(Ei("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof Ti))return new Ti(t);t=wi[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=mi.sha512}var Oi=Ti;Ti.prototype.sign=function(t,e){t=_i(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},Ti.prototype.verify=function(t,e,r){t=_i(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},Ti.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Zi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Ci)&&(!(n.compare(Li)>=0)&&(4===e&&65===t.length))}function $i(t){return 4!==t[0]}function zi(t){return!!Ki(t)&&(t.compare(Ci)>0&&t.compare(Ui)<0)}function Xi(t,e){return void 0===t&&void 0!==e?$i(e):void 0===t||t}function Yi(t){return new xi(t)}function Ji(t){return t.toArrayLike(P,"be",32)}function Zi(t){return Ni.curve.decodePoint(t)}function Qi(t,e){return P.from(t._encode(e))}function to(t,e,r){if(!Ki(t))throw new TypeError(Gi);if(!zi(e))throw new TypeError(Fi);if(void 0!==r&&!Ki(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Yi(e),i=Yi(t);let o,s;Ri(t,e,(function(t){const e=Yi(t),r=Hi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Di),0!==o.isZero()&&(s=e.invm(Di).mul(i.add(n.mul(o))).umod(Di),0!==s.isZero()))}),zi,r),s.cmp(Bi)>0&&(s=Di.sub(s));const u=P.allocUnsafe(64);return Ji(o).copy(u,0),Ji(s).copy(u,32),u}var eo={isPoint:Wi,isPointCompressed:function(t){return!!Wi(t)&&$i(t)},isPrivate:zi,pointAdd:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Wi(e))throw new TypeError(qi);const n=Zi(t),i=Zi(e),o=n.add(i);return o.isInfinity()?null:Qi(o,Xi(r,t))},pointAddScalar:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Vi(e))throw new TypeError(ji);const n=Xi(r,t),i=Zi(t);if(0===e.compare(Ci))return Qi(i,n);const o=Yi(e),s=Hi.mul(o),u=i.add(s);return u.isInfinity()?null:Qi(u,n)},pointCompress:function(t,e){if(!Wi(t))throw new TypeError(qi);const r=Zi(t);if(r.isInfinity())throw new TypeError(qi);return Qi(r,Xi(e,t))},pointFromScalar:function(t,e){if(!zi(t))throw new TypeError(Fi);const r=Yi(t),n=Hi.mul(r);return n.isInfinity()?null:Qi(n,Xi(e))},pointMultiply:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Vi(e))throw new TypeError(ji);const n=Xi(r,t),i=Zi(t),o=Yi(e),s=i.mul(o);return s.isInfinity()?null:Qi(s,n)},privateAdd:function(t,e){if(!zi(t))throw new TypeError(Fi);if(!Vi(e))throw new TypeError(ji);const r=Yi(t),n=Yi(e),i=Ji(r.add(n).umod(Di));return zi(i)?i:null},privateSub:function(t,e){if(!zi(t))throw new TypeError(Fi);if(!Vi(e))throw new TypeError(ji);const r=Yi(t),n=Yi(e),i=Ji(r.sub(n).umod(Di));return zi(i)?i:null},sign:function(t,e){return to(t,e)},signWithEntropy:function(t,e,r){return to(t,e,r)},verify:function(t,e,r,n){if(!Ki(t))throw new TypeError(Gi);if(!Wi(e))throw new TypeError(qi);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return ft(t)&&64===t.length&&e.compare(Ui)<0&&r.compare(Ui)<0}(r))throw new TypeError("Expected Signature");const i=Zi(e),o=Yi(r.slice(0,32)),s=Yi(r.slice(32,64));if(n&&s.cmp(Bi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Yi(t),a=s.invm(Di),h=u.mul(a).umod(Di),c=o.mul(a).umod(Di),f=Hi.mulAdd(h,i,c);return!f.isInfinity()&&f.x.umod(Di).eq(o)}};try{Ht.exports=require("./native")}catch(t){Ht.exports=eo}var ro={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var no in ro.Null=ro.Nil,ro)ro[no].toJSON=function(t){return t}.bind(null,no);var io=ro,oo=io;function so(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function uo(t){return oo.Nil(t)?"":so(t.constructor)}function ao(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function ho(t){return oo.Function(t)?t.toJSON?t.toJSON():so(t):oo.Array(t)?"Array":t&&oo.Object(t)?"Object":void 0!==t?t:""}function co(t,e,r){var n=function(t){return oo.Function(t)?"":oo.String(t)?JSON.stringify(t):t&&oo.Object(t)?"":t}(e);return"Expected "+ho(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function fo(t,e,r){r=r||uo(e),this.message=co(t,e,r),ao(this,fo),this.__type=t,this.__value=e,this.__valueTypeName=r}function lo(t,e,r,n,i){t?(i=i||uo(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),co('property "'+ho(r)+o+ho(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',ao(this,fo),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}fo.prototype=Object.create(Error.prototype),fo.prototype.constructor=fo,lo.prototype=Object.create(Error.prototype),lo.prototype.constructor=fo;var po={TfTypeError:fo,TfPropertyTypeError:lo,tfCustomError:function(t,e){return new fo(t,{},e)},tfSubError:function(t,e,r){return t instanceof lo?(e=e+"."+t.__property,t=new lo(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof fo&&(t=new lo(t.__type,e,r,t.__value,t.__valueTypeName)),ao(t),t},tfJSON:ho,getValueTypeName:uo},go=io,yo=po;function vo(t){return ft(t)}function mo(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function wo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw yo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var bo=wo.bind(null,go.Array),Eo=wo.bind(null,vo),_o=wo.bind(null,mo),So=wo.bind(null,go.String);var Io=Math.pow(2,53)-1;var To={ArrayN:bo,Buffer:vo,BufferN:Eo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:mo,HexN:_o,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-Io&&t<=Io&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=Io&&Math.floor(t)===t}};for(var Oo in To)To[Oo].toJSON=function(t){return t}.bind(null,Oo);var Ao=To,Po=io,Mo=po.tfJSON,ko=po.TfTypeError,xo=po.TfPropertyTypeError,No=po.tfSubError,Ro=po.getValueTypeName,Co={arrayOf:function(t,e){function r(r,n){return!!Po.Array(r)&&(!Po.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return Lo(t,e,n)}catch(t){throw No(t,r)}}))))))}return t=Uo(t),e=e||{},r.toJSON=function(){var r="["+Mo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return Po.Nil(r)||e(r,n,t)}return e=Uo(e),r.toJSON=function(){return"?"+Mo(e)},r},map:function(t,e){function r(r,n){if(!Po.Object(r))return!1;if(Po.Nil(r))return!1;for(var i in r){try{e&&Lo(e,i,n)}catch(t){throw No(t,i,"key")}try{var o=r[i];Lo(t,o,n)}catch(t){throw No(t,i)}}return!0}return t=Uo(t),e&&(e=Uo(e)),r.toJSON=e?function(){return"{"+Mo(e)+": "+Mo(t)+"}"}:function(){return"{"+Mo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Uo(t[r]);function n(t,r){if(!Po.Object(t))return!1;if(Po.Nil(t))return!1;var n;try{for(n in e){Lo(e[n],t[n],r)}}catch(t){throw No(t,n)}if(r)for(n in t)if(!e[n])throw new xo(void 0,n);return!0}return n.toJSON=function(){return Mo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return t.some((function(t){try{return Lo(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Mo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return t.every((function(t){try{return Lo(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Mo).join(" & ")},e},quacksLike:function(t){function e(e){return t===Ro(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return!Po.Nil(e)&&(!Po.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return Lo(t,e[n],r)}catch(t){throw No(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Mo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Uo(t){if(Po.String(t))return"?"===t[0]?Co.maybe(t.slice(1)):Po[t]||Co.quacksLike(t);if(t&&Po.Object(t)){if(Po.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Co.arrayOf(t[0])}return Co.object(t)}return Po.Function(t)?t:Co.value(t)}function Lo(t,e,r,n){if(Po.Function(t)){if(t(e,r))return!0;throw new ko(n||t,e)}return Lo(Uo(t),e,r)}for(var Do in Co.oneOf=Co.anyOf,Po)Lo[Do]=Po[Do];for(Do in Co)Lo[Do]=Co[Do];var Bo=Ao;for(Do in Bo)Lo[Do]=Bo[Do];Lo.compile=Uo,Lo.TfTypeError=ko,Lo.TfPropertyTypeError=xo;var Ho=Lo,Fo=Tt;function qo(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function jo(t,e,r){var n=new P(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Go={decode:function(t,e){return qo(Fo.decode(t),e)},decodeRaw:qo,encode:function(t,e,r){return"number"==typeof t?Fo.encode(jo(t,e,r)):Fo.encode(jo(t.version,t.privateKey,t.compressed))},encodeRaw:jo};Object.defineProperty(Ct,"__esModule",{value:!0});const Ko=Ut,Vo=Tt,Wo=Ht.exports,$o=Ho,zo=Go,Xo=$o.BufferN(32),Yo=$o.compile({wif:$o.UInt8,bip32:{public:$o.UInt32,private:$o.UInt32}}),Jo={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Zo=2147483648,Qo=Math.pow(2,31)-1;function ts(t){return $o.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function es(t){return $o.UInt32(t)&&t<=Qo}class rs{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,$o(Yo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Wo.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Ko.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return os(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=P.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Vo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return zo.encode(this.network.wif,this.privateKey,!0)}derive(t){$o($o.UInt32,t);const e=t>=Zo,r=P.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Ko.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Wo.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Wo.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=os(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Wo.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=is(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return $o(es,t),this.derive(t+Zo)}derivePath(t){$o(ts,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Wo.sign(t,this.privateKey);{let e=Wo.sign(t,this.privateKey);const r=P.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Wo.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Wo.verify(t,this.publicKey,e)}}function ns(t,e,r){return is(t,e,r)}function is(t,e,r,n,i,o){if($o({privateKey:Xo,chainCode:Xo},{privateKey:t,chainCode:e}),r=r||Jo,!Wo.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new rs(t,void 0,e,r,n,i,o)}function os(t,e,r,n,i,o){if($o({publicKey:$o.BufferN(33),chainCode:Xo},{publicKey:t,chainCode:e}),r=r||Jo,!Wo.isPoint(t))throw new TypeError("Point is not on the curve");return new rs(void 0,t,e,r,n,i,o)}Ct.fromBase58=function(t,e){const r=Vo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Jo;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=is(r.slice(46,78),u,e,i,s,o)}else{a=os(r.slice(45,78),u,e,i,s,o)}return a},Ct.fromPrivateKey=ns,Ct.fromPublicKey=function(t,e,r){return os(t,e,r)},Ct.fromSeed=function(t,e){if($o($o.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Jo;const r=Ko.hmacSHA512(P.from("Bitcoin seed","utf8"),t);return ns(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Rt,"__esModule",{value:!0});var ss=Ct;Rt.fromSeed=ss.fromSeed,Rt.fromBase58=ss.fromBase58,Rt.fromPublicKey=ss.fromPublicKey,Rt.fromPrivateKey=ss.fromPrivateKey;var us={},as={};Object.defineProperty(as,"__esModule",{value:!0}),as.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},as.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},as.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var hs={},cs={},fs={},ls={};Object.defineProperty(ls,"__esModule",{value:!0}),ls.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=P.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var ps={},ds={};Object.defineProperty(ds,"__esModule",{value:!0});const gs=Ho,ys=Math.pow(2,31)-1;function vs(t){return gs.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ds.UInt31=function(t){return gs.UInt32(t)&&t<=ys},ds.BIP32Path=vs,vs.toJSON=()=>"BIP32 derivation path",ds.Signer=function(t){return(gs.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ds.Satoshi=function(t){return gs.UInt53(t)&&t<=21e14},ds.ECPoint=gs.quacksLike("Point"),ds.Network=gs.compile({messagePrefix:gs.oneOf(gs.Buffer,gs.String),bip32:{public:gs.UInt32,private:gs.UInt32},pubKeyHash:gs.UInt8,scriptHash:gs.UInt8,wif:gs.UInt8}),ds.Buffer256bit=gs.BufferN(32),ds.Hash160bit=gs.BufferN(20),ds.Hash256bit=gs.BufferN(32),ds.Number=gs.Number,ds.Array=gs.Array,ds.Boolean=gs.Boolean,ds.String=gs.String,ds.Buffer=gs.Buffer,ds.Hex=gs.Hex,ds.maybe=gs.maybe,ds.tuple=gs.tuple,ds.UInt8=gs.UInt8,ds.UInt32=gs.UInt32,ds.Function=gs.Function,ds.BufferN=gs.BufferN,ds.Null=gs.Null,ds.oneOf=gs.oneOf;var ms=vt.exports.Buffer;var ws={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=ms.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(ps,"__esModule",{value:!0});const bs=ds,Es=ws,_s=Ho,Ss=P.alloc(1,0);function Is(t){let e=0;for(;0===t[e];)++e;return e===t.length?Ss:128&(t=t.slice(e))[0]?P.concat([Ss,t],1+t.length):t}function Ts(t){0===t[0]&&(t=t.slice(1));const e=P.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}ps.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Es.decode(t.slice(0,-1)),i=Ts(n.r),o=Ts(n.s);return{signature:P.concat([i,o],64),hashType:e}},ps.encode=function(t,e){_s({signature:bs.BufferN(64),hashType:bs.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=P.allocUnsafe(1);n.writeUInt8(e,0);const i=Is(t.slice(0,32)),o=Is(t.slice(32,64));return P.concat([Es.encode(i,o),n])};var Os={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},As=Os;function Ps(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===As.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==As.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},ks=Os,xs={};for(var Ns in ks){xs[ks[Ns]]=Ns}var Rs=xs;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ls,r=ps,n=ds,i=ws,o=Ht.exports,s=Ms,u=Ho;t.OPS=Os;const a=Rs,h=t.OPS.OP_RESERVED;function c(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function f(t){return n.Array(t)&&t.every(c)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return ft(t)}function d(t){return ft(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=P.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=f,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),P.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(f,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?P.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!ft(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(fs);var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0}),Cs.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Cs.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(cs,"__esModule",{value:!0});const Us=as,Ls=fs,Ds=Cs,Bs=Ho,Hs=Ls.OPS;cs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Bs({network:Bs.maybe(Bs.Object),output:Bs.maybe(Bs.Buffer),data:Bs.maybe(Bs.arrayOf(Bs.Buffer))},t);const r={name:"embed",network:t.network||Us.bitcoin};if(Ds.prop(r,"output",(()=>{if(t.data)return Ls.compile([Hs.OP_RETURN].concat(t.data))})),Ds.prop(r,"data",(()=>{if(t.output)return Ls.decompile(t.output).slice(1)})),e.validate&&t.output){const e=Ls.decompile(t.output);if(e[0]!==Hs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Bs.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Fs={};Object.defineProperty(Fs,"__esModule",{value:!0});const qs=as,js=fs,Gs=Cs,Ks=js.OPS,Vs=Ho,Ws=Ht.exports,$s=Ks.OP_RESERVED;function zs(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Fs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return js.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ks.OP_0)}e=Object.assign({validate:!0},e||{}),Vs({network:Vs.maybe(Vs.Object),m:Vs.maybe(Vs.Number),n:Vs.maybe(Vs.Number),output:Vs.maybe(Vs.Buffer),pubkeys:Vs.maybe(Vs.arrayOf(Ws.isPoint)),signatures:Vs.maybe(Vs.arrayOf(r)),input:Vs.maybe(Vs.Buffer)},t);const n={network:t.network||qs.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=js.decompile(t),n.m=i[0]-$s,n.n=i[i.length-2]-$s,n.pubkeys=i.slice(1,-2))}if(Gs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return js.compile([].concat($s+t.m,t.pubkeys,$s+n.n,Ks.OP_CHECKMULTISIG))})),Gs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Gs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Gs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Gs.prop(n,"signatures",(()=>{if(t.input)return js.decompile(t.input).slice(1)})),Gs.prop(n,"input",(()=>{if(t.signatures)return js.compile([Ks.OP_0].concat(t.signatures))})),Gs.prop(n,"witness",(()=>{if(n.input)return[]})),Gs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Vs.Number(i[0]))throw new TypeError("Output is invalid");if(!Vs.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ks.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ws.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!zs(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ks.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!zs(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=as,Js=fs,Zs=Cs,Qs=Ho,tu=Js.OPS,eu=Ht.exports;Xs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Qs({network:Qs.maybe(Qs.Object),output:Qs.maybe(Qs.Buffer),pubkey:Qs.maybe(eu.isPoint),signature:Qs.maybe(Js.isCanonicalScriptSignature),input:Qs.maybe(Qs.Buffer)},t);const r=Zs.value((()=>Js.decompile(t.input))),n={name:"p2pk",network:t.network||Ys.bitcoin};if(Zs.prop(n,"output",(()=>{if(t.pubkey)return Js.compile([t.pubkey,tu.OP_CHECKSIG])})),Zs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Zs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Zs.prop(n,"input",(()=>{if(t.signature)return Js.compile([t.signature])})),Zs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==tu.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!eu.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Js.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var ru={},nu={};Object.defineProperty(nu,"__esModule",{value:!0});const iu=yt;function ou(t){try{return iu("rmd160").update(t).digest()}catch(e){return iu("ripemd160").update(t).digest()}}function su(t){return iu("sha256").update(t).digest()}nu.ripemd160=ou,nu.sha1=function(t){return iu("sha1").update(t).digest()},nu.sha256=su,nu.hash160=function(t){return ou(su(t))},nu.hash256=function(t){return su(su(t))},Object.defineProperty(ru,"__esModule",{value:!0});const uu=nu,au=as,hu=fs,cu=Cs,fu=Ho,lu=hu.OPS,pu=Ht.exports,du=Tt;ru.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),fu({network:fu.maybe(fu.Object),address:fu.maybe(fu.String),hash:fu.maybe(fu.BufferN(20)),output:fu.maybe(fu.BufferN(25)),pubkey:fu.maybe(pu.isPoint),signature:fu.maybe(hu.isCanonicalScriptSignature),input:fu.maybe(fu.Buffer)},t);const r=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=cu.value((()=>hu.decompile(t.input))),i=t.network||au.bitcoin,o={name:"p2pkh",network:i};if(cu.prop(o,"address",(()=>{if(!o.hash)return;const t=P.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),du.encode(t)})),cu.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?uu.hash160(t.pubkey||o.pubkey):void 0)),cu.prop(o,"output",(()=>{if(o.hash)return hu.compile([lu.OP_DUP,lu.OP_HASH160,o.hash,lu.OP_EQUALVERIFY,lu.OP_CHECKSIG])})),cu.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),cu.prop(o,"signature",(()=>{if(t.input)return n()[0]})),cu.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return hu.compile([t.signature,t.pubkey])})),cu.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=P.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==lu.OP_DUP||t.output[1]!==lu.OP_HASH160||20!==t.output[2]||t.output[23]!==lu.OP_EQUALVERIFY||t.output[24]!==lu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=uu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!hu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!pu.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=uu.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var gu={};Object.defineProperty(gu,"__esModule",{value:!0});const yu=nu,vu=as,mu=fs,wu=Cs,bu=Ho,Eu=mu.OPS,_u=Tt;gu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),bu({network:bu.maybe(bu.Object),address:bu.maybe(bu.String),hash:bu.maybe(bu.BufferN(20)),output:bu.maybe(bu.BufferN(23)),redeem:bu.maybe({network:bu.maybe(bu.Object),output:bu.maybe(bu.Buffer),input:bu.maybe(bu.Buffer),witness:bu.maybe(bu.arrayOf(bu.Buffer))}),input:bu.maybe(bu.Buffer),witness:bu.maybe(bu.arrayOf(bu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||vu.bitcoin);const n={network:r},i=wu.value((()=>{const e=_u.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=wu.value((()=>mu.decompile(t.input))),s=wu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:mu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(wu.prop(n,"address",(()=>{if(!n.hash)return;const t=P.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),_u.encode(t)})),wu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?yu.hash160(n.redeem.output):void 0)),wu.prop(n,"output",(()=>{if(n.hash)return mu.compile([Eu.OP_HASH160,n.hash,Eu.OP_EQUAL])})),wu.prop(n,"redeem",(()=>{if(t.input)return s()})),wu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return mu.compile([].concat(mu.decompile(t.redeem.input),t.redeem.output))})),wu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),wu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=P.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==Eu.OP_HASH160||20!==t.output[1]||t.output[22]!==Eu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=mu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=yu.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=mu.decompile(t.input);if(!mu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!ft(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var Su={},Iu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Tu={},Ou=0;Ou>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Mu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Mu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(f)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function xu(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Mu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=Pu(n)^s,i+=Iu.charAt(s)}for(o=0;o<6;++o)n=Pu(n);for(n^=1,o=0;o<6;++o){i+=Iu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=xu(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=xu(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=xu(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=xu(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(Su,"__esModule",{value:!0});const Ru=nu,Cu=as,Uu=fs,Lu=Cs,Du=Ho,Bu=Uu.OPS,Hu=Ht.exports,Fu=Nu,qu=P.alloc(0);Su.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Du({address:Du.maybe(Du.String),hash:Du.maybe(Du.BufferN(20)),input:Du.maybe(Du.BufferN(0)),network:Du.maybe(Du.Object),output:Du.maybe(Du.BufferN(22)),pubkey:Du.maybe(Hu.isPoint),signature:Du.maybe(Uu.isCanonicalScriptSignature),witness:Du.maybe(Du.arrayOf(Du.Buffer))},t);const r=Lu.value((()=>{const e=Fu.decode(t.address),r=e.words.shift(),n=Fu.fromWords(e.words);return{version:r,prefix:e.prefix,data:P.from(n)}})),n=t.network||Cu.bitcoin,i={name:"p2wpkh",network:n};if(Lu.prop(i,"address",(()=>{if(!i.hash)return;const t=Fu.toWords(i.hash);return t.unshift(0),Fu.encode(n.bech32,t)})),Lu.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Ru.hash160(t.pubkey||i.pubkey):void 0)),Lu.prop(i,"output",(()=>{if(i.hash)return Uu.compile([Bu.OP_0,i.hash])})),Lu.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),Lu.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),Lu.prop(i,"input",(()=>{if(i.witness)return qu})),Lu.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=P.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Bu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Ru.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!Hu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Uu.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!Hu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Ru.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var ju={};Object.defineProperty(ju,"__esModule",{value:!0});const Gu=nu,Ku=as,Vu=fs,Wu=Cs,$u=Ho,zu=Vu.OPS,Xu=Ht.exports,Yu=Nu,Ju=P.alloc(0);function Zu(t){return!(!ft(t)||65!==t.length||4!==t[0]||!Xu.isPoint(t))}ju.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),$u({network:$u.maybe($u.Object),address:$u.maybe($u.String),hash:$u.maybe($u.BufferN(32)),output:$u.maybe($u.BufferN(34)),redeem:$u.maybe({input:$u.maybe($u.Buffer),network:$u.maybe($u.Object),output:$u.maybe($u.Buffer),witness:$u.maybe($u.arrayOf($u.Buffer))}),input:$u.maybe($u.BufferN(0)),witness:$u.maybe($u.arrayOf($u.Buffer))},t);const r=Wu.value((()=>{const e=Yu.decode(t.address),r=e.words.shift(),n=Yu.fromWords(e.words);return{version:r,prefix:e.prefix,data:P.from(n)}})),n=Wu.value((()=>Vu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Ku.bitcoin);const o={network:i};if(Wu.prop(o,"address",(()=>{if(!o.hash)return;const t=Yu.toWords(o.hash);return t.unshift(0),Yu.encode(i.bech32,t)})),Wu.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Gu.sha256(o.redeem.output):void 0)),Wu.prop(o,"output",(()=>{if(o.hash)return Vu.compile([zu.OP_0,o.hash])})),Wu.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ju,witness:t.witness.slice(0,-1)}})),Wu.prop(o,"input",(()=>{if(o.witness)return Ju})),Wu.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Vu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Ju,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Wu.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=P.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==zu.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Vu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Gu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Vu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Zu)||t.redeem.output&&(Vu.decompile(t.redeem.output)||[]).some(Zu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Zu)||(Vu.decompile(e)||[]).some(Zu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(hs,"__esModule",{value:!0});const Qu=cs;hs.embed=Qu.p2data;const ta=Fs;hs.p2ms=ta.p2ms;const ea=Xs;hs.p2pk=ea.p2pk;const ra=ru;hs.p2pkh=ra.p2pkh;const na=gu;hs.p2sh=na.p2sh;const ia=Su;hs.p2wpkh=ia.p2wpkh;const oa=ju;hs.p2wsh=oa.p2wsh,Object.defineProperty(us,"__esModule",{value:!0});const sa=as,ua=hs,aa=fs,ha=ds,ca=Nu,fa=Tt,la=Ho;function pa(t){const e=fa.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function da(t){const e=ca.decode(t),r=ca.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:P.from(r)}}us.fromBase58Check=pa,us.fromBech32=da,us.toBase58Check=function(t,e){la(ha.tuple(ha.Hash160bit,ha.UInt8),arguments);const r=P.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),fa.encode(r)},us.toBech32=function(t,e,r){const n=ca.toWords(t);return n.unshift(e),ca.encode(r,n)},us.fromOutputScript=function(t,e){e=e||sa.bitcoin;try{return ua.p2pkh({output:t,network:e}).address}catch(t){}try{return ua.p2sh({output:t,network:e}).address}catch(t){}try{return ua.p2wpkh({output:t,network:e}).address}catch(t){}try{return ua.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(aa.toASM(t)+" has no matching Address")},us.toOutputScript=function(t,e){let r,n;e=e||sa.bitcoin;try{r=pa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return ua.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return ua.p2sh({hash:r.hash}).output}else{try{n=da(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return ua.p2wpkh({hash:n.data}).output;if(32===n.data.length)return ua.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ga={},ya=a.default.randomBytes;Object.defineProperty(ga,"__esModule",{value:!0});const va=as,ma=ds,wa=Ht.exports,ba=ya,Ea=Ho,_a=Go,Sa=Ea.maybe(Ea.compile({compressed:ma.maybe(ma.Boolean),network:ma.maybe(ma.Network)}));class Ia{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||va.bitcoin,void 0!==e&&(this.__Q=wa.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=wa.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return _a.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return wa.sign(t,this.__D);{let e=wa.sign(t,this.__D);const r=P.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=wa.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return wa.verify(t,this.publicKey,e)}}function Ta(t,e){if(Ea(ma.Buffer256bit,t),!wa.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return Ea(Sa,e),new Ia(t,void 0,e)}ga.fromPrivateKey=Ta,ga.fromPublicKey=function(t,e){return Ea(wa.isPoint,t),Ea(Sa,e),new Ia(void 0,t,e)},ga.fromWIF=function(t,e){const r=_a.decode(t),n=r.version;if(ma.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||va.bitcoin,n!==e.wif)throw new Error("Invalid network version");return Ta(r.privateKey,{compressed:r.compressed,network:e})},ga.makeRandom=function(t){Ea(Sa,t),void 0===t&&(t={});const e=t.rng||ba;let r;do{r=e(32),Ea(ma.Buffer256bit,r)}while(!wa.isPrivate(r));return Ta(r,t)};var Oa={},Aa={},Pa=vt.exports.Buffer;function Ma(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function ka(t){return Ma(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var xa={encode:function t(e,r,n){if(Ma(e),r||(r=Pa.allocUnsafe(ka(e))),!Pa.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Pa.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ma(o),o},encodingLength:ka};Object.defineProperty(Aa,"__esModule",{value:!0});const Na=ds,Ra=Ho,Ca=xa;function Ua(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function La(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Ua(n+r,9007199254740991),n+r}function Da(t,e,r){return Ua(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}Aa.readUInt64LE=La,Aa.writeUInt64LE=Da,Aa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};Aa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ra(Na.tuple(Na.Buffer,Na.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=La(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Ca.decode(this.buffer,this.offset);return this.offset+=Ca.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Va.encodingLength(this.ins.length)+Va.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Wa(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Wa(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Va.encodingLength(e)+t.reduce(((t,e)=>t+Wa(e)),0)}(e.witness)),0):0)}clone(){const t=new Qa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Ka(Ga.tuple(Ga.UInt32,Ga.Buffer,Ga.Number),arguments),t>=this.ins.length)return Ya;const n=qa.compile(qa.decompile(e).filter((t=>t!==ja.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Qa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Qa.SIGHASH_SINGLE){if(t>=this.outs.length)return Ya;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Qa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=$a})),i.ins[t].script=n);const o=P.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Fa.hash256(o)}hashForWitnessV0(t,e,r,n){Ka(Ga.tuple(Ga.UInt32,Ga.Buffer,Ga.Satoshi,Ga.UInt32),arguments);let i,o=P.from([]),s=Xa,u=Xa,a=Xa;if(n&Qa.SIGHASH_ANYONECANPAY||(o=P.allocUnsafe(36*this.ins.length),i=new Ha.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Fa.hash256(o)),n&Qa.SIGHASH_ANYONECANPAY||(31&n)===Qa.SIGHASH_SINGLE||(31&n)===Qa.SIGHASH_NONE||(o=P.allocUnsafe(4*this.ins.length),i=new Ha.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Fa.hash256(o)),(31&n)!==Qa.SIGHASH_SINGLE&&(31&n)!==Qa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Wa(e.script)),0);o=P.allocUnsafe(t),i=new Ha.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Fa.hash256(o)}else if((31&n)===Qa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Qa.DEFAULT_SEQUENCE=4294967295,Qa.SIGHASH_ALL=1,Qa.SIGHASH_NONE=2,Qa.SIGHASH_SINGLE=3,Qa.SIGHASH_ANYONECANPAY=128,Qa.ADVANCED_TRANSACTION_MARKER=0,Qa.ADVANCED_TRANSACTION_FLAG=1,Ba.Transaction=Qa;Object.defineProperty(Oa,"__esModule",{value:!0});const th=Aa,eh=nu,rh=Ba,nh=ds,ih=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=rh.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=P.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(oh([{getHash:nh.Function}],t),0===t.length)throw uh;if(e&&!ch(t))throw ah;const r=t.map((t=>t.getHash(e))),n=ih(r,eh.hash256);return e?eh.hash256(P.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ch(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(P.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof P&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof P&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+sh.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return eh.hash256(this.toBuffer(!0))}getId(){return th.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=P.allocUnsafe(this.byteLength(t)),r=new th.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(sh.encode(this.transactions.length,e,r.offset),r.offset+=sh.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=th.reverseBuffer(this.getHash()),e=hh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw uh;const t=hh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw uh;if(!this.hasWitnessCommit())throw ah;const t=hh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ch(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}Oa.Block=hh;var fh={},lh={},ph={},dh={},gh={},yh={},vh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(vh);var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=vh;mh.decode=function(t){if(t.key[0]!==wh.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},mh.encode=function(t){const e=P.from([wh.GlobalTypes.GLOBAL_XPUB]),r=P.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=P.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},mh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",mh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return ft(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&ft(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},mh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=vh;bh.encode=function(t){return{key:P.from([Eh.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=vh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},_h.encode=function(t){return{key:P.from([Sh.InputTypes.FINAL_SCRIPTSIG]),value:t}},_h.expected="Buffer",_h.check=function(t){return ft(t)},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=vh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},Ih.encode=function(t){return{key:P.from([Th.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},Ih.expected="Buffer",Ih.check=function(t){return ft(t)},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var Oh={};Object.defineProperty(Oh,"__esModule",{value:!0});const Ah=vh;Oh.decode=function(t){if(t.key[0]!==Ah.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},Oh.encode=function(t){return{key:P.from([Ah.InputTypes.NON_WITNESS_UTXO]),value:t}},Oh.expected="Buffer",Oh.check=function(t){return ft(t)},Oh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Ph={};Object.defineProperty(Ph,"__esModule",{value:!0});const Mh=vh;Ph.decode=function(t){if(t.key[0]!==Mh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Ph.encode=function(t){const e=P.from([Mh.InputTypes.PARTIAL_SIG]);return{key:P.concat([e,t.pubkey]),value:t.signature}},Ph.expected="{ pubkey: Buffer; signature: Buffer; }",Ph.check=function(t){return ft(t.pubkey)&&ft(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!ft(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Ph.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var kh={};Object.defineProperty(kh,"__esModule",{value:!0});const xh=vh;kh.decode=function(t){if(t.key[0]!==xh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},kh.encode=function(t){return{key:P.from([xh.InputTypes.POR_COMMITMENT]),value:P.from(t,"utf8")}},kh.expected="string",kh.check=function(t){return"string"==typeof t},kh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Nh={};Object.defineProperty(Nh,"__esModule",{value:!0});const Rh=vh;Nh.decode=function(t){if(t.key[0]!==Rh.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Nh.encode=function(t){const e=P.from([Rh.InputTypes.SIGHASH_TYPE]),r=P.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Nh.expected="number",Nh.check=function(t){return"number"==typeof t},Nh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ch={},Uh={},Lh={};Object.defineProperty(Lh,"__esModule",{value:!0});function Dh(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Bh(t){return Dh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}Lh.encode=function t(e,r,n){if(Dh(e),r||(r=P.allocUnsafe(Bh(e))),!ft(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},Lh.decode=function t(e,r){if(!ft(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Dh(i),i}},Lh.encodingLength=Bh,Object.defineProperty(Uh,"__esModule",{value:!0});const Hh=Lh;function Fh(t){const e=t.key.length,r=t.value.length,n=Hh.encodingLength(e),i=Hh.encodingLength(r),o=P.allocUnsafe(n+e+i+r);return Hh.encode(e,o,0),t.key.copy(o,n),Hh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function qh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Uh.range=t=>[...Array(t).keys()],Uh.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=P.from([t]),n=P.concat([r,e.pubkey]),i=e.path.split("/"),o=P.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return ft(t.pubkey)&&ft(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Wh={};Object.defineProperty(Wh,"__esModule",{value:!0}),Wh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var $h={};Object.defineProperty($h,"__esModule",{value:!0}),$h.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:P.from([t]),value:e}},check:function(t){return ft(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var zh={};Object.defineProperty(zh,"__esModule",{value:!0}),zh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:P.from([t]),value:e}},check:function(t){return ft(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(yh,"__esModule",{value:!0});const Xh=vh,Yh=_h,Jh=Ih,Zh=Oh,Qh=Ph,tc=kh,ec=Nh,rc=Ch,nc=Vh,ic=Wh,oc=$h,sc=zh,uc={unsignedTx:bh,globalXpub:mh,checkPubkey:ic.makeChecker([])};yh.globals=uc;const ac={nonWitnessUtxo:Zh,partialSig:Qh,sighashType:ec,finalScriptSig:Yh,finalScriptWitness:Jh,porCommitment:tc,witnessUtxo:rc,bip32Derivation:nc.makeConverter(Xh.InputTypes.BIP32_DERIVATION),redeemScript:oc.makeConverter(Xh.InputTypes.REDEEM_SCRIPT),witnessScript:sc.makeConverter(Xh.InputTypes.WITNESS_SCRIPT),checkPubkey:ic.makeChecker([Xh.InputTypes.PARTIAL_SIG,Xh.InputTypes.BIP32_DERIVATION])};yh.inputs=ac;const hc={bip32Derivation:nc.makeConverter(Xh.OutputTypes.BIP32_DERIVATION),redeemScript:oc.makeConverter(Xh.OutputTypes.REDEEM_SCRIPT),witnessScript:sc.makeConverter(Xh.OutputTypes.WITNESS_SCRIPT),checkPubkey:ic.makeChecker([Xh.OutputTypes.BIP32_DERIVATION])};yh.outputs=hc,Object.defineProperty(gh,"__esModule",{value:!0});const cc=yh,fc=Uh,lc=Lh,pc=vh;function dc(t,e,r){if(!e.equals(P.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function gc(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case pc.GlobalTypes.UNSIGNED_TX:if(dc("global",t.key,pc.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case pc.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(cc.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of fc.range(s)){const e={};for(const n of r[t])switch(cc.inputs.checkPubkey(n),n.key[0]){case pc.InputTypes.NON_WITNESS_UTXO:if(dc("input",n.key,pc.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=cc.inputs.nonWitnessUtxo.decode(n);break;case pc.InputTypes.WITNESS_UTXO:if(dc("input",n.key,pc.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=cc.inputs.witnessUtxo.decode(n);break;case pc.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(cc.inputs.partialSig.decode(n));break;case pc.InputTypes.SIGHASH_TYPE:if(dc("input",n.key,pc.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=cc.inputs.sighashType.decode(n);break;case pc.InputTypes.REDEEM_SCRIPT:if(dc("input",n.key,pc.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=cc.inputs.redeemScript.decode(n);break;case pc.InputTypes.WITNESS_SCRIPT:if(dc("input",n.key,pc.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=cc.inputs.witnessScript.decode(n);break;case pc.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(cc.inputs.bip32Derivation.decode(n));break;case pc.InputTypes.FINAL_SCRIPTSIG:dc("input",n.key,pc.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=cc.inputs.finalScriptSig.decode(n);break;case pc.InputTypes.FINAL_SCRIPTWITNESS:dc("input",n.key,pc.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=cc.inputs.finalScriptWitness.decode(n);break;case pc.InputTypes.POR_COMMITMENT:dc("input",n.key,pc.InputTypes.POR_COMMITMENT),e.porCommitment=cc.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of fc.range(u)){const e={};for(const r of n[t])switch(cc.outputs.checkPubkey(r),r.key[0]){case pc.OutputTypes.REDEEM_SCRIPT:if(dc("output",r.key,pc.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=cc.outputs.redeemScript.decode(r);break;case pc.OutputTypes.WITNESS_SCRIPT:if(dc("output",r.key,pc.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=cc.outputs.witnessScript.decode(r);break;case pc.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(cc.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}gh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=lc.decode(t,r);r+=lc.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===pc.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:c,outputCount:f}=h.getInputOutputCounts(),l=[],p=[];for(const t of fc.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of fc.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return gc(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},gh.checkKeyBuffer=dc,gh.psbtFromKeyVals=gc;var yc={};Object.defineProperty(yc,"__esModule",{value:!0});const vc=yh,mc=Uh;yc.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=Ec({globalMap:t,inputs:e,outputs:r}),s=mc.keyValsToBuffer(n),u=t=>0===t.length?[P.from([0])]:t.map(mc.keyValsToBuffer),a=u(i),h=u(o),c=P.allocUnsafe(5);return c.writeUIntBE(482972169471,0,5),P.concat([c,s].concat(a,h))};const wc=(t,e)=>t.key.compare(e.key);function bc(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(wc)}function Ec({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:bc(t,vc.globals),inputKeyVals:e.map((t=>bc(t,vc.inputs))),outputKeyVals:r.map((t=>bc(t,vc.outputs)))}}yc.psbtToKeyVals=Ec,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(gh),e(yc)}(dh),Object.defineProperty(ph,"__esModule",{value:!0});const _c=dh;function Sc(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function Ic(t){return t.globalMap.unsignedTx}function Tc(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}ph.combine=function(t){const e=t[0],r=_c.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=Ic(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=Tc(r.globalKeyVals),s=r.inputKeyVals.map(Tc),u=r.outputKeyVals.map(Tc);for(const t of n){const e=Ic(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=_c.psbtToKeyVals(t);Tc(n.globalKeyVals).forEach(Sc(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(Tc).forEach(((t,e)=>t.forEach(Sc(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(Tc).forEach(((t,e)=>t.forEach(Sc(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return _c.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var Oc={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=yh;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:c}=e[t+"s"][o]||{},f=!!a;if(h)if(f){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,c,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,c,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!ft(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!ft(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(Oc),Object.defineProperty(lh,"__esModule",{value:!0});const Ac=ph,Pc=dh,Mc=vh,kc=Oc;lh.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=P.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=P.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Pc.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Pc.psbtToBuffer(this)}updateGlobal(t){return kc.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=kc.checkForInput(this.inputs,t);return kc.updateInput(e,r),this}updateOutput(t,e){const r=kc.checkForOutput(this.outputs,t);return kc.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return kc.checkHasKey(t,this.globalMap.unknownKeyVals,kc.getEnumLength(Mc.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=kc.checkForInput(this.inputs,t);return kc.checkHasKey(e,r.unknownKeyVals,kc.getEnumLength(Mc.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=kc.checkForOutput(this.outputs,t);return kc.checkHasKey(e,r.unknownKeyVals,kc.getEnumLength(Mc.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),kc.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),kc.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=kc.checkForInput(this.inputs,t);kc.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=Ac.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(fh,"__esModule",{value:!0});const xc=lh,Nc=Lh,Rc=Oc,Cc=us,Uc=Aa,Lc=nu,Dc=ga,Bc=hs,Hc=fs,Fc=Ba,qc={network:as.bitcoin,maximumFeeRate:5e3};class jc{constructor(t={},e=new xc.Psbt(new Kc)){this.data=e,this.opts=Object.assign({},qc,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=P.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=P.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=xc.Psbt.fromBuffer(t,Gc),n=new jc(e,r);return function(t,e){t.ins.forEach((t=>{sf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:Uc.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Cc.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:Uc.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=jc.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){rf(t),this.opts.maximumFeeRate=t}setVersion(t){rf(t),nf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){rf(t),nf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){rf(e),nf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");nf(this.data.inputs,"addInput"),t.witnessScript&&Sf(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);sf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&vf(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");nf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Cc.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every($c))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return mf(this.data.inputs,r,e,!0),r}getFeeRate(){return cf("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return cf("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Rc.checkForInput(this.data.inputs,0),Of(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=ff){const r=Rc.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=wf(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Zc(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Hc.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Rc.checkForInput(this.data.inputs,t),r=_f(bf(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Hc.decompile(t);if(!e)return;const r=e[e.length-1];if(!ft(r)||Ef(r)||(n=r,Hc.isCanonicalScriptSignature(n)))return;var n;if(!Hc.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=gf(t),r=e[e.length-1];if(Ef(r))return;if(!Hc.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+Tf(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=bf(r,e,n),{meaningfulScript:o}=_f(i,r,"input",e.redeemScript,e.witnessScript);return If(t,o)}(e,Rc.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Rc.checkForInput(this.data.inputs,t),n=ef(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=_f(i,r,"output",e.redeemScript,e.witnessScript);return If(t,o)}(e,Rc.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Rc.checkForOutput(this.data.outputs,t),n=ef(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Rc.checkForInput(this.data.inputs,0);return Of(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Hc.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?pf(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,of(e.pubkey,h,"verify");const c=Dc.fromPublicKey(e.pubkey);o.push(c.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Fc.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of Of(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of Of(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Fc.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return df(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=df(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Fc.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of Of(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Fc.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=lf(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Hc.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Fc.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=lf(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Hc.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Vc(this.__CACHE),this.data.toBuffer()}toHex(){return Vc(this.__CACHE),this.data.toHex()}toBase64(){return Vc(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&Sf(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&vf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}fh.Psbt=jc;const Gc=t=>new Kc(t);class Kc{constructor(t=P.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Fc.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!ft(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?Uc.reverseBuffer(P.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!ft(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Vc(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Wc(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Dc.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function $c(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function zc(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Xc=zc(Bc.p2ms),Yc=zc(Bc.p2pk),Jc=zc(Bc.p2pkh),Zc=zc(Bc.p2wpkh),Qc=zc(Bc.p2wsh),tf=zc(Bc.p2sh);function ef(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function rf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function nf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Hc.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Hc.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>ft(t)&&Hc.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Hc.signature.decode(t.signature),i=[];n&Fc.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Fc.Transaction.SIGHASH_ALL:break;case Fc.Transaction.SIGHASH_SINGLE:case Fc.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function of(t,e,r){if(!If(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function sf(t,e){const r=Uc.reverseBuffer(P.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function uf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const af=uf(Bc.p2sh,"Redeem script"),hf=uf(Bc.p2wsh,"Witness script");function cf(t,e,r,n){if(!r.every($c))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),mf(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function ff(t,e,r,n,i,o){const s=Tf(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Wc(1,t.partialSig);case"multisig":const r=Bc.p2ms({output:e});return Wc(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return Bc.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=Bc.p2ms({output:t,signatures:e});break;case"pubkey":n=Bc.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=Bc.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=Bc.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?Bc.p2wsh({redeem:a}):null,c=i?Bc.p2sh({redeem:h||a}):null;n?(u=yf(h?h.witness:a.witness),c&&(s=c.input)):s=c?c.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function lf(t,e,r,n,i){const o=Rc.checkForInput(t,e),{hash:s,sighashType:u,script:a}=pf(e,o,n,!1,i);return of(r,a,"sign"),{hash:s,sighashType:u}}function pf(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Fc.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Fc.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Fc.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Fc.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Fc.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=wf(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:c}=_f(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(c)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Zc(h)){const e=Bc.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function df(t,e,r){const n=Rc.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function gf(t){let e=0;function r(){const r=Nc.decode(t,e);return e+=Nc.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=gf(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=wf(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function wf(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||vf(t,e,r),n[r]}function bf(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return wf(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function Ef(t){return 33===t.length&&Hc.isCanonicalPubKey(t)}function _f(t,e,r,n,i){const o=tf(t),s=o&&n&&Qc(n),u=Qc(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,af(e,t,n,r),hf(e,n,i,r),Sf(a)):u?(a=i,hf(e,t,i,r),Sf(a)):o?(a=n,af(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function Sf(t){if(Zc(t)||tf(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function If(t,e){const r=Lc.hash160(t),n=Hc.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function Tf(t){return Zc(t)?"witnesspubkeyhash":Jc(t)?"pubkeyhash":Xc(t)?"multisig":Yc(t)?"pubkey":"nonstandard"}function Of(t){return[...Array(t).keys()]}var Af={},Pf={},Mf={},kf={};Object.defineProperty(kf,"__esModule",{value:!0});const xf=fs,Nf=fs;function Rf(t){return t===Nf.OPS.OP_0||xf.isCanonicalScriptSignature(t)}function Cf(t,e){const r=xf.decompile(t);return!(r.length<2)&&(r[0]===Nf.OPS.OP_0&&(e?r.slice(1).every(Rf):r.slice(1).every(xf.isCanonicalScriptSignature)))}kf.check=Cf,Cf.toJSON=()=>"multisig input";var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0});const Lf=fs,Df=fs,Bf=ds,Hf=Df.OPS.OP_RESERVED;function Ff(t,e){const r=Lf.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Df.OPS.OP_CHECKMULTISIG)return!1;if(!Bf.Number(r[0]))return!1;if(!Bf.Number(r[r.length-2]))return!1;const n=r[0]-Hf,i=r[r.length-2]-Hf;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(Lf.isCanonicalPubKey)}Uf.check=Ff,Ff.toJSON=()=>"multi-sig output",Object.defineProperty(Mf,"__esModule",{value:!0});const qf=kf;Mf.input=qf;const jf=Uf;Mf.output=jf;var Gf={};Object.defineProperty(Gf,"__esModule",{value:!0});const Kf=fs,Vf=Kf.OPS;function Wf(t){const e=Kf.compile(t);return e.length>1&&e[0]===Vf.OP_RETURN}Gf.check=Wf,Wf.toJSON=()=>"null data output";const $f={check:Wf};Gf.output=$f;var zf={},Xf={};Object.defineProperty(Xf,"__esModule",{value:!0});const Yf=fs;function Jf(t){const e=Yf.decompile(t);return 1===e.length&&Yf.isCanonicalScriptSignature(e[0])}Xf.check=Jf,Jf.toJSON=()=>"pubKey input";var Zf={};Object.defineProperty(Zf,"__esModule",{value:!0});const Qf=fs,tl=fs;function el(t){const e=Qf.decompile(t);return 2===e.length&&Qf.isCanonicalPubKey(e[0])&&e[1]===tl.OPS.OP_CHECKSIG}Zf.check=el,el.toJSON=()=>"pubKey output",Object.defineProperty(zf,"__esModule",{value:!0});const rl=Xf;zf.input=rl;const nl=Zf;zf.output=nl;var il={},ol={};Object.defineProperty(ol,"__esModule",{value:!0});const sl=fs;function ul(t){const e=sl.decompile(t);return 2===e.length&&sl.isCanonicalScriptSignature(e[0])&&sl.isCanonicalPubKey(e[1])}ol.check=ul,ul.toJSON=()=>"pubKeyHash input";var al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=fs,cl=fs;function fl(t){const e=hl.compile(t);return 25===e.length&&e[0]===cl.OPS.OP_DUP&&e[1]===cl.OPS.OP_HASH160&&20===e[2]&&e[23]===cl.OPS.OP_EQUALVERIFY&&e[24]===cl.OPS.OP_CHECKSIG}al.check=fl,fl.toJSON=()=>"pubKeyHash output",Object.defineProperty(il,"__esModule",{value:!0});const ll=ol;il.input=ll;const pl=al;il.output=pl;var dl={},gl={},yl={};Object.defineProperty(yl,"__esModule",{value:!0});const vl=fs,ml=fs;function wl(t){const e=vl.compile(t);return 22===e.length&&e[0]===ml.OPS.OP_0&&20===e[1]}yl.check=wl,wl.toJSON=()=>"Witness pubKeyHash output";var bl={};Object.defineProperty(bl,"__esModule",{value:!0});const El=fs,_l=fs;function Sl(t){const e=El.compile(t);return 34===e.length&&e[0]===_l.OPS.OP_0&&32===e[1]}bl.check=Sl,Sl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(gl,"__esModule",{value:!0});const Il=fs,Tl=Mf,Ol=zf,Al=il,Pl=yl,Ml=bl;function kl(t,e){const r=Il.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!ft(n))return!1;const i=Il.decompile(Il.compile(r.slice(0,-1))),o=Il.decompile(n);return!!o&&(!!Il.isPushOnly(i)&&(1===r.length?Ml.check(o)||Pl.check(o):!(!Al.input.check(i)||!Al.output.check(o))||(!(!Tl.input.check(i,e)||!Tl.output.check(o))||!(!Ol.input.check(i)||!Ol.output.check(o)))))}gl.check=kl,kl.toJSON=()=>"scriptHash input";var xl={};Object.defineProperty(xl,"__esModule",{value:!0});const Nl=fs,Rl=fs;function Cl(t){const e=Nl.compile(t);return 23===e.length&&e[0]===Rl.OPS.OP_HASH160&&20===e[1]&&e[22]===Rl.OPS.OP_EQUAL}xl.check=Cl,Cl.toJSON=()=>"scriptHash output",Object.defineProperty(dl,"__esModule",{value:!0});const Ul=gl;dl.input=Ul;const Ll=xl;dl.output=Ll;var Dl={},Bl={};Object.defineProperty(Bl,"__esModule",{value:!0});const Hl=fs,Fl=fs,ql=ds,jl=Ho,Gl=P.from("aa21a9ed","hex");function Kl(t){const e=Hl.compile(t);return e.length>37&&e[0]===Fl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Gl)}Bl.check=Kl,Kl.toJSON=()=>"Witness commitment output",Bl.encode=function(t){jl(ql.Hash256bit,t);const e=P.allocUnsafe(36);return Gl.copy(e,0),t.copy(e,4),Hl.compile([Fl.OPS.OP_RETURN,e])},Bl.decode=function(t){return jl(Kl,t),Hl.decompile(t)[1].slice(4,36)},Object.defineProperty(Dl,"__esModule",{value:!0});const Vl=Bl;Dl.output=Vl;var Wl={},$l={};Object.defineProperty($l,"__esModule",{value:!0});const zl=fs;function Xl(t){const e=zl.decompile(t);return 2===e.length&&zl.isCanonicalScriptSignature(e[0])&&function(t){return zl.isCanonicalPubKey(t)&&33===t.length}(e[1])}$l.check=Xl,Xl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Wl,"__esModule",{value:!0});const Yl=$l;Wl.input=Yl;const Jl=yl;Wl.output=Jl;var Zl={},Ql={};Object.defineProperty(Ql,"__esModule",{value:!0});const tp=fs,ep=Ho,rp=Mf,np=zf,ip=il;function op(t,e){if(ep(ep.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!ft(r))return!1;const n=tp.decompile(r);if(!n||0===n.length)return!1;const i=tp.compile(t.slice(0,-1));return!(!ip.input.check(i)||!ip.output.check(n))||(!(!rp.input.check(i,e)||!rp.output.check(n))||!(!np.input.check(i)||!np.output.check(n)))}Ql.check=op,op.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Zl,"__esModule",{value:!0});const sp=Ql;Zl.input=sp;const up=bl;Zl.output=up,Object.defineProperty(Pf,"__esModule",{value:!0});const ap=fs,hp=Mf,cp=Gf,fp=zf,lp=il,pp=dl,dp=Dl,gp=Wl,yp=Zl,vp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Pf.types=vp,Pf.output=function(t){if(gp.output.check(t))return vp.P2WPKH;if(yp.output.check(t))return vp.P2WSH;if(lp.output.check(t))return vp.P2PKH;if(pp.output.check(t))return vp.P2SH;const e=ap.decompile(t);if(!e)throw new TypeError("Invalid script");return hp.output.check(e)?vp.P2MS:fp.output.check(e)?vp.P2PK:dp.output.check(e)?vp.WITNESS_COMMITMENT:cp.output.check(e)?vp.NULLDATA:vp.NONSTANDARD},Pf.input=function(t,e){const r=ap.decompile(t);if(!r)throw new TypeError("Invalid script");return lp.input.check(r)?vp.P2PKH:pp.input.check(r,e)?vp.P2SH:hp.input.check(r,e)?vp.P2MS:fp.input.check(r)?vp.P2PK:vp.NONSTANDARD},Pf.witness=function(t,e){const r=ap.decompile(t);if(!r)throw new TypeError("Invalid script");return gp.input.check(r)?vp.P2WPKH:yp.input.check(r,e)?vp.P2WSH:vp.NONSTANDARD},Object.defineProperty(Af,"__esModule",{value:!0});const mp=us,wp=Aa,bp=Pf,Ep=nu,_p=ga,Sp=as,Ip=hs,Tp=fs,Op=fs,Ap=Ba,Pp=ds,Mp=Ho,kp=bp.types,xp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Np(t,e,r){try{Mp(t,e)}catch(t){throw new Error(r)}}class Rp{constructor(t=Sp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new Ap.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Rp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==kp.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=_p.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=Tp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Mp(Mp.maybe(Mp.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Mp(Pp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Mp(Pp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=wp.reverseBuffer(P.from(t,"hex"));else if(function(t){return t instanceof Ap.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=mp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=Tp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,c){let f;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),f=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!xp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Np(Mp.Number,e.vin,"sign must include vin parameter as Number (input index)"),Np(Pp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Np(Mp.maybe(Mp.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.Buffer,e.witnessScript,`${n} requires witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.Buffer,e.witnessScript,`${n} requires witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires witnessScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:f,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[f])throw new Error("No input at index: "+f);if(u=u||Ap.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[f];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Dp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Mp(Pp.Satoshi,a),l.value=a}if(!Dp(l)){const t=function(t,e,r,n){if(r&&n){const i=Ip.p2wsh({redeem:{output:n}}),o=Ip.p2wsh({output:r}),s=Ip.p2sh({redeem:{output:r}}),u=Ip.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Up(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+Tp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===kp.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:kp.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:kp.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=Ip.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=Ip.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Up(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+Tp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===kp.P2WPKH&&(o=Ip.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:kp.P2SH,prevOutScript:n.output,hasWitness:i.type===kp.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=Ip.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=Ip.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Up(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+Tp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===kp.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:kp.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===kp.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===kp.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Up(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+Tp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===kp.P2WPKH&&(n=Ip.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===kp.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=Ip.p2pkh({pubkey:e}).output;return{prevOutType:kp.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:kp.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Dp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(f,l.signScript,l.value,u):n.hashForSignature(f,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!c}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(Ap.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Cp(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Up(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||bp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=Lp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===kp.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Bp(t)&Ap.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===Ap.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Bp(t)&Ap.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Bp(r);return n===Ap.Transaction.SIGHASH_NONE||n===Ap.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Cp(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=bp.input(t,!0),i=bp.witness(e,!0);n===kp.NONSTANDARD&&(n=void 0),i===kp.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case kp.P2WPKH:{const{output:t,pubkey:r,signature:n}=Ip.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:kp.P2WPKH,pubkeys:[r],signatures:[n]}}case kp.P2PKH:{const{output:e,pubkey:r,signature:n}=Ip.p2pkh({input:t});return{prevOutScript:e,prevOutType:kp.P2PKH,pubkeys:[r],signatures:[n]}}case kp.P2PK:{const{signature:e}=Ip.p2pk({input:t});return{prevOutType:kp.P2PK,pubkeys:[void 0],signatures:[e]}}case kp.P2MS:{const{m:e,pubkeys:r,signatures:i}=Ip.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:kp.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===kp.P2SH){const{output:r,redeem:n}=Ip.p2sh({input:t,witness:e}),i=bp.output(n.output),o=Cp(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:kp.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===kp.P2WSH){const{output:r,redeem:n}=Ip.p2wsh({input:t,witness:e}),i=bp.output(n.output);let o;return o=i===kp.P2WPKH?Cp(n.input,n.witness,i):Cp(Tp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:kp.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:kp.NONSTANDARD,prevOutScript:t}}function Up(t,e){Mp(Pp.Buffer,t);const r=bp.output(t);switch(r){case kp.P2PKH:{if(!e)return{type:r};const n=Ip.p2pkh({output:t}).hash,i=Ep.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case kp.P2WPKH:{if(!e)return{type:r};const n=Ip.p2wpkh({output:t}).hash,i=Ep.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case kp.P2PK:return{type:r,pubkeys:[Ip.p2pk({output:t}).pubkey],signatures:[void 0]};case kp.P2MS:{const e=Ip.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function Lp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case kp.P2PKH:if(0===n.length)break;if(0===i.length)break;return Ip.p2pkh({pubkey:n[0],signature:i[0]});case kp.P2WPKH:if(0===n.length)break;if(0===i.length)break;return Ip.p2wpkh({pubkey:n[0],signature:i[0]});case kp.P2PK:if(0===n.length)break;if(0===i.length)break;return Ip.p2pk({signature:i[0]});case kp.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||Op.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return Ip.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case kp.P2SH:{const t=Lp(e.redeemScriptType,e,r);if(!t)return;return Ip.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case kp.P2WSH:{const t=Lp(e.witnessScriptType,e,r);if(!t)return;return Ip.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Dp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Bp(t){return t.readUInt8(t.length-1)}Af.TransactionBuilder=Rp,Object.defineProperty(Nt,"__esModule",{value:!0});const Hp=Rt;Nt.bip32=Hp;const Fp=us;Nt.address=Fp;const qp=nu;var jp=Nt.crypto=qp;const Gp=ga;Nt.ECPair=Gp;const Kp=as;Nt.networks=Kp;const Vp=hs;Nt.payments=Vp;const Wp=fs;Nt.script=Wp;var $p=Oa;Nt.Block=$p.Block;var zp=fh;Nt.Psbt=zp.Psbt;var Xp=fs;Nt.opcodes=Xp.OPS;var Yp=Ba;Nt.Transaction=Yp.Transaction;var Jp=Af;Nt.TransactionBuilder=Jp.TransactionBuilder;var Zp={exports:{}};var Qp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};function td(){throw new Error("setTimeout has not been defined")}function ed(){throw new Error("clearTimeout has not been defined")}var rd=td,nd=ed;function id(t){if(rd===setTimeout)return setTimeout(t,0);if((rd===td||!rd)&&setTimeout)return rd=setTimeout,setTimeout(t,0);try{return rd(t,0)}catch(e){try{return rd.call(null,t,0)}catch(e){return rd.call(this,t,0)}}}"function"==typeof d.setTimeout&&(rd=setTimeout),"function"==typeof d.clearTimeout&&(nd=clearTimeout);var od,sd=[],ud=!1,ad=-1;function hd(){ud&&od&&(ud=!1,od.length?sd=od.concat(sd):ad=-1,sd.length&&cd())}function cd(){if(!ud){var t=id(hd);ud=!0;for(var e=sd.length;e;){for(od=sd,sd=[];++ad1)for(var r=1;rconsole.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Qp,n=Td,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Zp,Zp.exports);const Od=["includePrerelease","loose","rtl"];var Ad=t=>t?"object"!=typeof t?{loose:!0}:Od.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Pd=/^[0-9]+$/,Md=(t,e)=>{const r=Pd.test(t),n=Pd.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tMd(e,t)};const xd=Td,{MAX_LENGTH:Nd,MAX_SAFE_INTEGER:Rd}=Qp,{re:Cd,t:Ud}=Zp.exports,Ld=Ad,{compareIdentifiers:Dd}=kd;class Bd{constructor(t,e){if(e=Ld(e),t instanceof Bd){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Nd)throw new TypeError(`version is longer than ${Nd} characters`);xd("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?Cd[Ud.LOOSE]:Cd[Ud.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Rd||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rd||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rd||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var Hd=Bd;const{MAX_LENGTH:Fd}=Qp,{re:qd,t:jd}=Zp.exports,Gd=Hd,Kd=Ad;var Vd=(t,e)=>{if(e=Kd(e),t instanceof Gd)return t;if("string"!=typeof t)return null;if(t.length>Fd)return null;if(!(e.loose?qd[jd.LOOSE]:qd[jd.FULL]).test(t))return null;try{return new Gd(t,e)}catch(t){return null}};const Wd=Vd;var $d=(t,e)=>{const r=Wd(t,e);return r?r.version:null};const zd=Vd;var Xd=(t,e)=>{const r=zd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const Yd=Hd;var Jd=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new Yd(t,r).inc(e,n).version}catch(t){return null}};const Zd=Hd;var Qd=(t,e,r)=>new Zd(t,r).compare(new Zd(e,r));const tg=Qd;var eg=(t,e,r)=>0===tg(t,e,r);const rg=Vd,ng=eg;var ig=(t,e)=>{if(ng(t,e))return null;{const r=rg(t),n=rg(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const og=Hd;var sg=(t,e)=>new og(t,e).major;const ug=Hd;var ag=(t,e)=>new ug(t,e).minor;const hg=Hd;var cg=(t,e)=>new hg(t,e).patch;const fg=Vd;var lg=(t,e)=>{const r=fg(t,e);return r&&r.prerelease.length?r.prerelease:null};const pg=Qd;var dg=(t,e,r)=>pg(e,t,r);const gg=Qd;var yg=(t,e)=>gg(t,e,!0);const vg=Hd;var mg=(t,e,r)=>{const n=new vg(t,r),i=new vg(e,r);return n.compare(i)||n.compareBuild(i)};const wg=mg;var bg=(t,e)=>t.sort(((t,r)=>wg(t,r,e)));const Eg=mg;var _g=(t,e)=>t.sort(((t,r)=>Eg(r,t,e)));const Sg=Qd;var Ig=(t,e,r)=>Sg(t,e,r)>0;const Tg=Qd;var Og=(t,e,r)=>Tg(t,e,r)<0;const Ag=Qd;var Pg=(t,e,r)=>0!==Ag(t,e,r);const Mg=Qd;var kg=(t,e,r)=>Mg(t,e,r)>=0;const xg=Qd;var Ng=(t,e,r)=>xg(t,e,r)<=0;const Rg=eg,Cg=Pg,Ug=Ig,Lg=kg,Dg=Og,Bg=Ng;var Hg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return Rg(t,r,n);case"!=":return Cg(t,r,n);case">":return Ug(t,r,n);case">=":return Lg(t,r,n);case"<":return Dg(t,r,n);case"<=":return Bg(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const Fg=Hd,qg=Vd,{re:jg,t:Gg}=Zp.exports;var Kg=(t,e)=>{if(t instanceof Fg)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=jg[Gg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),jg[Gg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;jg[Gg.COERCERTL].lastIndex=-1}else r=t.match(jg[Gg.COERCE]);return null===r?null:qg(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},Vg=Wg;function Wg(t){var e=this;if(e instanceof Wg||(e=new Wg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},Wg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},Wg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},Wg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},Wg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new Wg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},Wg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const hy=(t,e,r)=>{const n=t[sy].get(e);if(n){const e=n.value;if(cy(t,e)){if(ly(t,n),!t[ey])return}else r&&(t[uy]&&(n.value.now=Date.now()),t[oy].unshiftNode(n));return e.value}},cy=(t,e)=>{if(!e||!e.maxAge&&!t[ry])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[ry]&&r>t[ry]},fy=t=>{if(t[Qg]>t[Zg])for(let e=t[oy].tail;t[Qg]>t[Zg]&&null!==e;){const r=e.prev;ly(t,e),e=r}},ly=(t,e)=>{if(e){const r=e.value;t[ny]&&t[ny](r.key,r.value),t[Qg]-=r.length,t[sy].delete(r.key),t[oy].removeNode(e)}};class py{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const dy=(t,e,r,n)=>{let i=r.value;cy(t,i)&&(ly(t,r),t[ey]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var gy=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[Zg]=t.max||1/0;const e=t.length||ay;if(this[ty]="function"!=typeof e?ay:e,this[ey]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[ry]=t.maxAge||0,this[ny]=t.dispose,this[iy]=t.noDisposeOnSet||!1,this[uy]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[Zg]=t||1/0,fy(this)}get max(){return this[Zg]}set allowStale(t){this[ey]=!!t}get allowStale(){return this[ey]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[ry]=t,fy(this)}get maxAge(){return this[ry]}set lengthCalculator(t){"function"!=typeof t&&(t=ay),t!==this[ty]&&(this[ty]=t,this[Qg]=0,this[oy].forEach((t=>{t.length=this[ty](t.value,t.key),this[Qg]+=t.length}))),fy(this)}get lengthCalculator(){return this[ty]}get length(){return this[Qg]}get itemCount(){return this[oy].length}rforEach(t,e){e=e||this;for(let r=this[oy].tail;null!==r;){const n=r.prev;dy(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[oy].head;null!==r;){const n=r.next;dy(this,t,r,e),r=n}}keys(){return this[oy].toArray().map((t=>t.key))}values(){return this[oy].toArray().map((t=>t.value))}reset(){this[ny]&&this[oy]&&this[oy].length&&this[oy].forEach((t=>this[ny](t.key,t.value))),this[sy]=new Map,this[oy]=new Jg,this[Qg]=0}dump(){return this[oy].map((t=>!cy(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[oy]}set(t,e,r){if((r=r||this[ry])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[ty](e,t);if(this[sy].has(t)){if(i>this[Zg])return ly(this,this[sy].get(t)),!1;const o=this[sy].get(t).value;return this[ny]&&(this[iy]||this[ny](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Qg]+=i-o.length,o.length=i,this.get(t),fy(this),!0}const o=new py(t,e,i,n,r);return o.length>this[Zg]?(this[ny]&&this[ny](t,e),!1):(this[Qg]+=o.length,this[oy].unshift(o),this[sy].set(t,this[oy].head),fy(this),!0)}has(t){if(!this[sy].has(t))return!1;const e=this[sy].get(t).value;return!cy(this,e)}get(t){return hy(this,t,!0)}peek(t){return hy(this,t,!1)}pop(){const t=this[oy].tail;return t?(ly(this,t),t.value):null}del(t){ly(this,this[sy].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[sy].forEach(((t,e)=>hy(this,e,!1)))}};class yy{constructor(t,e){if(e=wy(e),t instanceof yy)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new yy(t.raw,e);if(t instanceof by)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Py(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&My(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=my.get(e);if(r)return r;const n=this.options.loose,i=n?Sy[Iy.HYPHENRANGELOOSE]:Sy[Iy.HYPHENRANGE];t=t.replace(i,qy(this.options.includePrerelease)),Ey("hyphen replace",t),t=t.replace(Sy[Iy.COMPARATORTRIM],Ty),Ey("comparator trim",t,Sy[Iy.COMPARATORTRIM]),t=(t=(t=t.replace(Sy[Iy.TILDETRIM],Oy)).replace(Sy[Iy.CARETTRIM],Ay)).split(/\s+/).join(" ");const o=n?Sy[Iy.COMPARATORLOOSE]:Sy[Iy.COMPARATOR],s=t.split(" ").map((t=>xy(t,this.options))).join(" ").split(/\s+/).map((t=>Fy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new by(t,this.options)));s.length;const u=new Map;for(const t of s){if(Py(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return my.set(e,a),a}intersects(t,e){if(!(t instanceof yy))throw new TypeError("a Range is required");return this.set.some((r=>ky(r,e)&&t.set.some((t=>ky(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new _y(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,My=t=>""===t.value,ky=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},xy=(t,e)=>(Ey("comp",t,e),t=Uy(t,e),Ey("caret",t),t=Ry(t,e),Ey("tildes",t),t=Dy(t,e),Ey("xrange",t),t=Hy(t,e),Ey("stars",t),t),Ny=t=>!t||"x"===t.toLowerCase()||"*"===t,Ry=(t,e)=>t.trim().split(/\s+/).map((t=>Cy(t,e))).join(" "),Cy=(t,e)=>{const r=e.loose?Sy[Iy.TILDELOOSE]:Sy[Iy.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Ey("tilde",t,e,r,n,i,o),Ny(r)?s="":Ny(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Ny(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Ey("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Ey("tilde return",s),s}))},Uy=(t,e)=>t.trim().split(/\s+/).map((t=>Ly(t,e))).join(" "),Ly=(t,e)=>{Ey("caret",t,e);const r=e.loose?Sy[Iy.CARETLOOSE]:Sy[Iy.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Ey("caret",t,e,r,i,o,s),Ny(r)?u="":Ny(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Ny(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Ey("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Ey("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Ey("caret return",u),u}))},Dy=(t,e)=>(Ey("replaceXRanges",t,e),t.split(/\s+/).map((t=>By(t,e))).join(" ")),By=(t,e)=>{t=t.trim();const r=e.loose?Sy[Iy.XRANGELOOSE]:Sy[Iy.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Ey("xRange",t,r,n,i,o,s,u);const a=Ny(i),h=a||Ny(o),c=h||Ny(s),f=c;return"="===n&&f&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&f?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:c&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Ey("xRange return",r),r}))},Hy=(t,e)=>(Ey("replaceStars",t,e),t.trim().replace(Sy[Iy.STAR],"")),Fy=(t,e)=>(Ey("replaceGTE0",t,e),t.trim().replace(Sy[e.includePrerelease?Iy.GTE0PRE:Iy.GTE0],"")),qy=t=>(e,r,n,i,o,s,u,a,h,c,f,l,p)=>`${r=Ny(n)?"":Ny(i)?`>=${n}.0.0${t?"-0":""}`:Ny(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Ny(h)?"":Ny(c)?`<${+h+1}.0.0-0`:Ny(f)?`<${h}.${+c+1}.0-0`:l?`<=${h}.${c}.${f}-${l}`:t?`<${h}.${c}.${+f+1}-0`:`<=${a}`}`.trim(),jy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},Gy=Symbol("SemVer ANY");class Ky{static get ANY(){return Gy}constructor(t,e){if(e=Wy(e),t instanceof Ky){if(t.loose===!!e.loose)return t;t=t.value}Yy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===Gy?this.value="":this.value=this.operator+this.semver.version,Yy("comp",this)}parse(t){const e=this.options.loose?$y[zy.COMPARATORLOOSE]:$y[zy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new Jy(r[2],this.options.loose):this.semver=Gy}toString(){return this.value}test(t){if(Yy("Comparator.test",t,this.options.loose),this.semver===Gy||t===Gy)return!0;if("string"==typeof t)try{t=new Jy(t,this.options)}catch(t){return!1}return Xy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof Ky))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new Zy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new Zy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=Xy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=Xy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var Vy=Ky;const Wy=Ad,{re:$y,t:zy}=Zp.exports,Xy=Hg,Yy=Td,Jy=Hd,Zy=vy,Qy=vy;var tv=(t,e,r)=>{try{e=new Qy(e,r)}catch(t){return!1}return e.test(t)};const ev=vy;var rv=(t,e)=>new ev(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const nv=Hd,iv=vy;var ov=(t,e,r)=>{let n=null,i=null,o=null;try{o=new iv(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new nv(n,r)))})),n};const sv=Hd,uv=vy;var av=(t,e,r)=>{let n=null,i=null,o=null;try{o=new uv(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new sv(n,r)))})),n};const hv=Hd,cv=vy,fv=Ig;var lv=(t,e)=>{t=new cv(t,e);let r=new hv("0.0.0");if(t.test(r))return r;if(r=new hv("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new hv(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!fv(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!fv(r,i)||(r=i)}return r&&t.test(r)?r:null};const pv=vy;var dv=(t,e)=>{try{return new pv(t,e).range||"*"}catch(t){return null}};const gv=Hd,yv=Vy,{ANY:vv}=yv,mv=vy,wv=tv,bv=Ig,Ev=Og,_v=Ng,Sv=kg;var Iv=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new gv(t,n),e=new mv(e,n),r){case">":i=bv,o=_v,s=Ev,u=">",a=">=";break;case"<":i=Ev,o=Sv,s=bv,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(wv(t,e,n))return!1;for(let r=0;r{t.semver===vv&&(t=new yv(">=0.0.0")),c=c||t,f=f||t,i(t.semver,c.semver,n)?c=t:s(t.semver,f.semver,n)&&(f=t)})),c.operator===u||c.operator===a)return!1;if((!f.operator||f.operator===u)&&o(t,f.semver))return!1;if(f.operator===a&&s(t,f.semver))return!1}return!0};const Tv=Iv;var Ov=(t,e,r)=>Tv(t,e,">",r);const Av=Iv;var Pv=(t,e,r)=>Av(t,e,"<",r);const Mv=vy;var kv=(t,e,r)=>(t=new Mv(t,r),e=new Mv(e,r),t.intersects(e));const xv=tv,Nv=Qd;const Rv=vy,Cv=Vy,{ANY:Uv}=Cv,Lv=tv,Dv=Qd,Bv=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===Uv){if(1===e.length&&e[0].semver===Uv)return!0;t=r.includePrerelease?[new Cv(">=0.0.0-0")]:[new Cv(">=0.0.0")]}if(1===e.length&&e[0].semver===Uv){if(r.includePrerelease)return!0;e=[new Cv(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,c;for(const e of t)">"===e.operator||">="===e.operator?i=Hv(i,e,r):"<"===e.operator||"<="===e.operator?o=Fv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=Dv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!Lv(t,String(i),r))return null;if(o&&!Lv(t,String(o),r))return null;for(const n of e)if(!Lv(t,String(n),r))return!1;return!0}let f=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;f&&1===f.prerelease.length&&"<"===o.operator&&0===f.prerelease[0]&&(f=!1);for(const t of e){if(c=c||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=Hv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!Lv(i.semver,String(t),r))return!1;if(o)if(f&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===f.major&&t.semver.minor===f.minor&&t.semver.patch===f.patch&&(f=!1),"<"===t.operator||"<="===t.operator){if(a=Fv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!Lv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&c&&!i&&0!==s)&&(!l&&!f))},Hv=(t,e,r)=>{if(!t)return e;const n=Dv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},Fv=(t,e,r)=>{if(!t)return e;const n=Dv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var qv=(t,e,r={})=>{if(t===e)return!0;t=new Rv(t,r),e=new Rv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=Bv(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const jv=Zp.exports;var Gv={re:jv.re,src:jv.src,tokens:jv.t,SEMVER_SPEC_VERSION:Qp.SEMVER_SPEC_VERSION,SemVer:Hd,compareIdentifiers:kd.compareIdentifiers,rcompareIdentifiers:kd.rcompareIdentifiers,parse:Vd,valid:$d,clean:Xd,inc:Jd,diff:ig,major:sg,minor:ag,patch:cg,prerelease:lg,compare:Qd,rcompare:dg,compareLoose:yg,compareBuild:mg,sort:bg,rsort:_g,gt:Ig,lt:Og,eq:eg,neq:Pg,gte:kg,lte:Ng,cmp:Hg,coerce:Kg,Comparator:Vy,Range:vy,satisfies:tv,toComparators:rv,maxSatisfying:ov,minSatisfying:av,minVersion:lv,validRange:dv,outside:Iv,gtr:Ov,ltr:Pv,intersects:kv,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Nv(t,e,r)));for(const t of s){xv(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Qv.alloc(0);for(var e=Qv.allocUnsafe(t>>>0),r=this.head,n=0;r;)rm(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Qv.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:em,value:function(t,e){return tm(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}cm("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),cm("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${fm(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${fm(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),cm("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),cm("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),cm("ERR_STREAM_PREMATURE_CLOSE","Premature close"),cm("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),cm("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),cm("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),cm("ERR_STREAM_WRITE_AFTER_END","write after end"),cm("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),cm("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),cm("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),am.codes=hm;var lm=am.codes.ERR_INVALID_OPT_VALUE;var pm,dm={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new lm(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},gm=l.default.deprecate,ym=Dm;function vm(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}Dm.WritableState=Lm;var mm={deprecate:gm},wm=Xv,bm=h.default.Buffer,Em=p.Uint8Array||function(){};var _m,Sm=um,Im=dm.getHighWaterMark,Tm=am.codes,Om=Tm.ERR_INVALID_ARG_TYPE,Am=Tm.ERR_METHOD_NOT_IMPLEMENTED,Pm=Tm.ERR_MULTIPLE_CALLBACK,Mm=Tm.ERR_STREAM_CANNOT_PIPE,km=Tm.ERR_STREAM_DESTROYED,xm=Tm.ERR_STREAM_NULL_VALUES,Nm=Tm.ERR_STREAM_WRITE_AFTER_END,Rm=Tm.ERR_UNKNOWN_ENCODING,Cm=Sm.errorOrDestroy;function Um(){}function Lm(t,e,r){pm=pm||Vm,t=t||{},"boolean"!=typeof r&&(r=e instanceof pm),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=Im(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Pm;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(fd(i,n),fd(Gm,t,e),t._writableState.errorEmitted=!0,Cm(t,n)):(i(n),t._writableState.errorEmitted=!0,Cm(t,n),Gm(t,e))}(t,r,n,e,i);else{var o=qm(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||Fm(t,r),n?fd(Hm,t,r,o,i):Hm(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new vm(this)}function Dm(t){var e=this instanceof(pm=pm||Vm);if(!e&&!_m.call(Dm,this))return new Dm(t);this._writableState=new Lm(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),wm.call(this)}function Bm(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new km("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function Hm(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),Gm(t,e)}function Fm(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,Bm(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new vm(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,c=r.callback;if(Bm(t,e,!1,e.objectMode?1:a.length,a,h,c),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function qm(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function jm(t,e){t._final((function(r){e.pendingcb--,r&&Cm(t,r),e.prefinished=!0,t.emit("prefinish"),Gm(t,e)}))}function Gm(t,e){var r=qm(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,fd(jm,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}se.exports(Dm,wm),Lm.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(Lm.prototype,"buffer",{get:mm.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_m=Function.prototype[Symbol.hasInstance],Object.defineProperty(Dm,Symbol.hasInstance,{value:function(t){return!!_m.call(this,t)||this===Dm&&(t&&t._writableState instanceof Lm)}})):_m=function(t){return t instanceof this},Dm.prototype.pipe=function(){Cm(this,new Mm)},Dm.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,bm.isBuffer(n)||n instanceof Em);return s&&!bm.isBuffer(t)&&(t=function(t){return bm.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=Um),i.ending?function(t,e){var r=new Nm;Cm(t,r),fd(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new xm:"string"==typeof r||e.objectMode||(i=new Om("chunk",["string","Buffer"],r)),!i||(Cm(t,i),fd(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=bm.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new Rm(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(Dm.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Dm.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Dm.prototype._write=function(t,e,r){r(new Am("_write()"))},Dm.prototype._writev=null,Dm.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,Gm(t,e),r&&(e.finished?fd(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(Dm.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Dm.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),Dm.prototype.destroy=Sm.destroy,Dm.prototype._undestroy=Sm.undestroy,Dm.prototype._destroy=function(t,e){e(t)};var Km=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},Vm=Jm,Wm=Bw,$m=ym;se.exports(Jm,Wm);for(var zm=Km($m.prototype),Xm=0;Xm>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function ow(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function sw(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function uw(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function aw(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function hw(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function cw(t){return t.toString(this.encoding)}function fw(t){return t&&t.length?this.write(t):""}tw.StringDecoder=nw,nw.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},nw.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var lw=am.codes.ERR_STREAM_PREMATURE_CLOSE;function pw(){}var dw,gw=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===qw.prototype||(e=function(t){return qw.from(t)}(e)),n)s.endEmitted?rb(t,new eb):ub(t,s,e,!0);else if(s.ended)rb(t,new Qw);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?ub(t,s,e,!1):lb(t,s)):ub(t,s,e,!1)}else n||(s.reading=!1,lb(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=ab?t=ab:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function cb(t){var e=t._readableState;Gw("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Gw("emitReadable",e.flowing),e.emittedReadable=!0,fd(fb,t))}function fb(t){var e=t._readableState;Gw("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,vb(t)}function lb(t,e){e.readingMore||(e.readingMore=!0,fd(pb,t,e))}function pb(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function gb(t){Gw("readable nexttick read 0"),t.read(0)}function yb(t,e){Gw("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),vb(t),e.flowing&&!e.reading&&t.read(0)}function vb(t){var e=t._readableState;for(Gw("flow",e.flowing);e.flowing&&null!==t.read(););}function mb(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function wb(t){var e=t._readableState;Gw("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,fd(bb,e,t))}function bb(t,e){if(Gw("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function Eb(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return Gw("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?wb(this):cb(this),null;if(0===(t=hb(t,e))&&e.ended)return 0===e.length&&wb(this),null;var n,i=e.needReadable;return Gw("need readable",i),(0===e.length||e.length-t0?mb(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&wb(this)),null!==n&&this.emit("data",n),n},ob.prototype._read=function(t){rb(this,new tb("_read()"))},ob.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Gw("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==Id.stdout&&t!==Id.stderr?s:p;function o(e,i){Gw("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,Gw("cleanup"),t.removeListener("close",f),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",c),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){Gw("onend"),t.end()}n.endEmitted?fd(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Gw("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&Hw(t,"data")&&(e.flowing=!0,vb(t))}}(r);t.on("drain",u);var a=!1;function h(e){Gw("ondata");var i=t.write(e);Gw("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Eb(n.pipes,t))&&!a&&(Gw("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function c(e){Gw("onerror",e),p(),t.removeListener("error",c),0===Hw(t,"error")&&rb(t,e)}function f(){t.removeListener("finish",l),p()}function l(){Gw("onfinish"),t.removeListener("close",f),p()}function p(){Gw("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",c),t.once("close",f),t.once("finish",l),t.emit("pipe",r),n.flowing||(Gw("pipe resume"),r.resume()),t},ob.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Gw("on readable",n.length,n.reading),n.length?cb(this):n.reading||fd(gb,this))),r},ob.prototype.addListener=ob.prototype.on,ob.prototype.removeListener=function(t,e){var r=Fw.prototype.removeListener.call(this,t,e);return"readable"===t&&fd(db,this),r},ob.prototype.removeAllListeners=function(t){var e=Fw.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||fd(db,this),e},ob.prototype.resume=function(){var t=this._readableState;return t.flowing||(Gw("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,fd(yb,t,e))}(this,t)),t.paused=!1,this},ob.prototype.pause=function(){return Gw("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Gw("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},ob.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(Gw("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(Gw("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(jb),s||(o.forEach(jb),i(n))}))}));return e.reduce(Gb)};!function(t,e){var r=c.default;(e=t.exports=Bw).Stream=r||e,e.Readable=e,e.Writable=ym,e.Duplex=Vm,e.Transform=_b,e.PassThrough=Cb,e.finished=gw,e.pipeline=Vb}(zv,zv.exports);var Wb=vt.exports.Buffer,$b=zv.exports.Transform;function zb(t){$b.call(this),this._block=Wb.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,se.exports)(zb,$b),zb.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},zb.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},zb.prototype.update=function(t,e){if(function(t,e){if(!Wb.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");Wb.isBuffer(t)||(t=Wb.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},zb.prototype._update=function(){throw new Error("_update is not implemented")},zb.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},zb.prototype._digest=function(){throw new Error("_digest is not implemented")};var Xb=zb,Yb=h.default.Buffer,Jb=se.exports,Zb=Xb,Qb=new Array(16),tE=[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],eE=[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],rE=[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],nE=[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],iE=[0,1518500249,1859775393,2400959708,2840853838],oE=[1352829926,1548603684,1836072691,2053994217,0];function sE(){Zb.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function uE(t,e){return t<>>32-e}function aE(t,e,r,n,i,o,s,u){return uE(t+(e^r^n)+o+s|0,u)+i|0}function hE(t,e,r,n,i,o,s,u){return uE(t+(e&r|~e&n)+o+s|0,u)+i|0}function cE(t,e,r,n,i,o,s,u){return uE(t+((e|~r)^n)+o+s|0,u)+i|0}function fE(t,e,r,n,i,o,s,u){return uE(t+(e&n|r&~n)+o+s|0,u)+i|0}function lE(t,e,r,n,i,o,s,u){return uE(t+(e^(r|~n))+o+s|0,u)+i|0}Jb(sE,Zb),sE.prototype._update=function(){for(var t=Qb,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,c=0|this._d,f=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=aE(r,n,i,o,s,t[tE[l]],iE[0],rE[l]),d=lE(u,a,h,c,f,t[eE[l]],oE[0],nE[l])):l<32?(p=hE(r,n,i,o,s,t[tE[l]],iE[1],rE[l]),d=fE(u,a,h,c,f,t[eE[l]],oE[1],nE[l])):l<48?(p=cE(r,n,i,o,s,t[tE[l]],iE[2],rE[l]),d=cE(u,a,h,c,f,t[eE[l]],oE[2],nE[l])):l<64?(p=fE(r,n,i,o,s,t[tE[l]],iE[3],rE[l]),d=hE(u,a,h,c,f,t[eE[l]],oE[3],nE[l])):(p=lE(r,n,i,o,s,t[tE[l]],iE[4],rE[l]),d=aE(u,a,h,c,f,t[eE[l]],oE[4],nE[l])),r=s,s=o,o=uE(i,10),i=n,n=p,u=f,f=c,c=uE(h,10),h=a,a=d}var g=this._b+i+c|0;this._b=this._c+o+f|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},sE.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=Yb.alloc?Yb.alloc(20):new Yb(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var pE=sE,dE={exports:{}},gE=vt.exports.Buffer;function yE(t,e){this._block=gE.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}yE.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=gE.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},yE.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var vE=yE,mE=se.exports,wE=vE,bE=vt.exports.Buffer,EE=[1518500249,1859775393,-1894007588,-899497514],_E=new Array(80);function SE(){this.init(),this._w=_E,wE.call(this,64,56)}function IE(t){return t<<30|t>>>2}function TE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}mE(SE,wE),SE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},SE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var c=~~(h/20),f=0|((e=n)<<5|e>>>27)+TE(c,i,o,s)+u+r[h]+EE[c];u=s,s=o,o=IE(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},SE.prototype._hash=function(){var t=bE.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var OE=SE,AE=se.exports,PE=vE,ME=vt.exports.Buffer,kE=[1518500249,1859775393,-1894007588,-899497514],xE=new Array(80);function NE(){this.init(),this._w=xE,PE.call(this,64,56)}function RE(t){return t<<5|t>>>27}function CE(t){return t<<30|t>>>2}function UE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}AE(NE,PE),NE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},NE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var c=~~(h/20),f=RE(n)+UE(c,i,o,s)+u+r[h]+kE[c]|0;u=s,s=o,o=CE(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},NE.prototype._hash=function(){var t=ME.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var LE=NE,DE=se.exports,BE=vE,HE=vt.exports.Buffer,FE=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],qE=new Array(64);function jE(){this.init(),this._w=qE,BE.call(this,64,56)}function GE(t,e,r){return r^t&(e^r)}function KE(t,e,r){return t&e|r&(t|e)}function VE(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function WE(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function $E(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function zE(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}DE(jE,BE),jE.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},jE.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,c=0;c<16;++c)e[c]=t.readInt32BE(4*c);for(;c<64;++c)e[c]=zE(e[c-2])+e[c-7]+$E(e[c-15])+e[c-16]|0;for(var f=0;f<64;++f){var l=h+WE(s)+GE(s,u,a)+FE[f]+e[f]|0,p=VE(r)+KE(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},jE.prototype._hash=function(){var t=HE.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var XE=jE,YE=se.exports,JE=XE,ZE=vE,QE=vt.exports.Buffer,t_=new Array(64);function e_(){this.init(),this._w=t_,ZE.call(this,64,56)}YE(e_,JE),e_.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},e_.prototype._hash=function(){var t=QE.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var r_=e_,n_=se.exports,i_=vE,o_=vt.exports.Buffer,s_=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],u_=new Array(160);function a_(){this.init(),this._w=u_,i_.call(this,128,112)}function h_(t,e,r){return r^t&(e^r)}function c_(t,e,r){return t&e|r&(t|e)}function f_(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function l_(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function p_(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function d_(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function g_(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function y_(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function v_(t,e){return t>>>0>>0?1:0}n_(a_,i_),a_.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},a_.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,c=0|this._al,f=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=p_(w,b),_=d_(b,w),S=g_(w=e[m-4],b=e[m-4+1]),I=y_(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],P=e[m-32+1],M=_+O|0,k=E+T+v_(M,_)|0;k=(k=k+S+v_(M=M+I|0,I)|0)+A+v_(M=M+P|0,P)|0,e[m]=k,e[m+1]=M}for(var x=0;x<160;x+=2){k=e[x],M=e[x+1];var N=c_(r,n,i),R=c_(c,f,l),C=f_(r,c),U=f_(c,r),L=l_(s,d),D=l_(d,s),B=s_[x],H=s_[x+1],F=h_(s,u,a),q=h_(d,g,y),j=v+D|0,G=h+L+v_(j,v)|0;G=(G=(G=G+F+v_(j=j+q|0,q)|0)+B+v_(j=j+H|0,H)|0)+k+v_(j=j+M|0,M)|0;var K=U+R|0,V=C+N+v_(K,U)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+G+v_(d=p+j|0,p)|0,o=i,p=l,i=n,l=f,n=r,f=c,r=G+V+v_(c=j+K|0,j)|0}this._al=this._al+c|0,this._bl=this._bl+f|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+v_(this._al,c)|0,this._bh=this._bh+n+v_(this._bl,f)|0,this._ch=this._ch+i+v_(this._cl,l)|0,this._dh=this._dh+o+v_(this._dl,p)|0,this._eh=this._eh+s+v_(this._el,d)|0,this._fh=this._fh+u+v_(this._fl,g)|0,this._gh=this._gh+a+v_(this._gl,y)|0,this._hh=this._hh+h+v_(this._hl,v)|0},a_.prototype._hash=function(){var t=o_.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var m_=a_,w_=se.exports,b_=m_,E_=vE,__=vt.exports.Buffer,S_=new Array(160);function I_(){this.init(),this._w=S_,E_.call(this,128,112)}w_(I_,b_),I_.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},I_.prototype._hash=function(){var t=__.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var T_=I_,O_=dE.exports=function(t){t=t.toLowerCase();var e=O_[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};O_.sha=OE,O_.sha1=LE,O_.sha224=r_,O_.sha256=XE,O_.sha384=T_,O_.sha512=m_;var A_=dE.exports;function P_(t){return(new pE).update(A_("sha256").update(t).digest()).digest()}var M_,k_=(M_=function(t,e){return M_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},M_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}M_(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),x_=function(t,e){this.psbt=t,this.masterFp=e},N_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(x_),R_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=P_(t);return e.writeSlice(P.from([118,169,20])),e.writeSlice(r),e.writeSlice(P.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(N_),C_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new Kv,n=this.getTaprootOutputKey(e);return r.writeSlice(P.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=jp.sha256(P.from("TapTweak","utf-8"));return jp.sha256(P.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=P.concat([P.from([2]),t]),r=this.hashTapTweak(t);return P.from(Ht.exports.pointAddScalar(e,r)).slice(1)},e}(N_),U_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=this.createRedeemScript(t),n=P_(r);return e.writeSlice(P.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=P_(t);return P.concat([P.from("0014","hex"),e])},e}(N_),L_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=P_(t);return e.writeSlice(P.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(N_),D_=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},B_=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return j_(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new q_(void 0,void 0,P.alloc(32,0)),leaves:[]};if(1==e){var r=new q_(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=P.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function pS(t){var e=t.outputs,r=P.alloc(0);return void 0!==e&&(r=P.concat([r,lS(e.length)]),e.forEach((function(t){r=P.concat([r,t.amount,lS(t.script.length),t.script])}))),r}function dS(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=P.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?P.concat([s,t.prevout,P.from([0]),t.sequence]):P.concat([s,t.prevout,lS(t.script.length),t.script,t.sequence])}));var a=pS(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=P.concat([a,u&&t.witness||P.alloc(0),t.locktime,t.nExpiryHeight||P.alloc(0),t.extraData||P.alloc(0)])),P.concat([t.version,r||P.alloc(0),t.nVersionGroupId||P.alloc(0),u?P.from("0001","hex"):P.alloc(0),lS(t.inputs.length),s,a])}var gS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},yS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new G_(e,K_(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,P.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return gS(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I;return yS(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new Z_,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new C_(e,r):t.additionals.includes("bech32")?new L_(e,r):t.segwit?new U_(e,r):new R_(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(c=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((f=new Kv).writeVarInt(2),f.writeVarInt(c.length),f.writeSlice(c),f.writeVarInt(n[0].length),f.writeSlice(n[0]),t.setInputFinalScriptwitness(r,f.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new Kv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new Kv;cS(h,c),cS(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var c,f;if(!(c=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=c.length&&65!=c.length)throw Error("Unexpected length of schnorr signature.");(f=new Kv).writeVarInt(1),f.writeVarSlice(c),t.setInputFinalScriptwitness(r,f.buffer())}hS(t,r)}}(r),I=function(t){var e,r,n=new Kv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(P.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new Kv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function NS(t,e,r){return MS(this,void 0,void 0,(function(){var n,i,o,s;return kS(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=P.alloc(4)).writeUInt32BE(r,0),n=P.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function RS(t,e,r,n){return void 0===n&&(n=[]),MS(this,void 0,void 0,(function(){var i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R=this;return kS(this,(function(C){switch(C.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return c=n.includes("decred"),f=n.includes("stealthcoin"),l=function(e,r){return MS(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,c,f,l,p;return kS(this,(function(d){switch(d.label){case 0:for(n=r||P.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>Wv?Wv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(P.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=xS(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(c=h.value,[4,NS(t,c)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return f=d.sent(),l={error:f},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return NS(t,e)},[4,NS(t,P.concat([r.version,r.timestamp||P.alloc(0),r.nVersionGroupId||P.alloc(0),lS(o.length)]),e)];case 1:C.sent(),C.label=2;case 2:C.trys.push([2,8,9,10]),d=xS(o),g=d.next(),C.label=3;case 3:return g.done?[3,7]:(y=g.value,v=f&&0===P.compare(i,P.from([2,0,0,0])),m=c?y.tree||P.from([0]):P.alloc(0),O=P.concat([y.prevout,m,v?P.from([0]):lS(y.script.length)]),[4,NS(t,O)]);case 4:return C.sent(),[4,c?p(P.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:C.sent(),C.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=C.sent(),M={error:w},[3,10];case 9:try{g&&!g.done&&(k=d.return)&&k.call(d)}finally{if(M)throw M.error}return[7];case 10:return[4,NS(t,lS(s.length))];case 11:C.sent(),C.label=12;case 12:C.trys.push([12,17,18,19]),b=xS(s),E=b.next(),C.label=13;case 13:return E.done?[3,16]:(_=E.value,O=P.concat([_.amount,c?P.from([0,0]):P.alloc(0),lS(_.script.length),_.script]),[4,NS(t,O)]);case 14:C.sent(),C.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=C.sent(),x={error:S},[3,19];case 18:try{E&&!E.done&&(N=b.return)&&N.call(b)}finally{if(x)throw x.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=P.concat(I),T=c?O:P.concat([lS(O.length),O])),[4,l(P.concat([u,T||P.alloc(0)]))];case 20:return A=C.sent(),PS(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var CS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},US=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function DS(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function BS(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),CS(this,void 0,void 0,(function(){var a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return US(this,(function(M){switch(M.label){case 0:return a=P.concat([r.version,r.timestamp||P.alloc(0),r.nVersionGroupId||P.alloc(0),lS(r.inputs.length)]),[4,DS(t,e,!0,a,i,o,s)];case 1:M.sent(),h=0,c=s.includes("decred"),M.label=2;case 2:M.trys.push([2,15,16,17]),f=LS(r.inputs),l=f.next(),M.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?P.from([1,g.length]):P.from([2]):n[h].trustedInput?P.from([1,n[h].value.length]):P.from([0]),a=P.concat([d,g,c?P.from([0]):P.alloc(0),lS(p.script.length)]),[4,DS(t,e,!1,a,i,o,s)]);case 4:if(M.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>Wv?Wv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(P.concat([p.script.slice(v,v+m),p.sequence])),v+=m;M.label=5;case 5:M.trys.push([5,10,11,12]),O=void 0,w=LS(y),b=w.next(),M.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,DS(t,e,!1,E,i,o,s)]);case 7:M.sent(),M.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=M.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,M.label=13;case 13:return l=f.next(),[3,3];case 14:return[3,17];case 15:return S=M.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=f.return)&&T.call(f)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function HS(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=A_("sha256").update(A_("sha256").update(dS(r,!0)).digest()).digest(),o=P.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=P.concat([i,o,s[e].amount])).toString("hex")}function FS(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=At(e),a=P.alloc(4);a.writeUInt32BE(r,0);var h=s?P.concat([u,a,i||P.from([0,0,0,0]),P.from([n])]):P.concat([u,P.from([0]),a,P.from([n])]);return i&&!s&&(h=P.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var qS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:Wv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var VS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},WS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ZS={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function QS(t,e){return XS(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R,C,U,L,D,B,H,F,q,j,G,K,V,W,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at,ht;return YS(this,(function(ct){switch(ct.label){case 0:if(r=zS(zS({},ZS),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,c=r.initialTimestamp,f=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ct.label=1;case 1:return ct.trys.push([1,3,,4]),[4,$S(t)];case 2:return v=ct.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||Gv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ct.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=f.includes("decred"),E=f.includes("stealthcoin"),_=Date.now(),S=f.includes("sapling"),I=h&&f.includes("bech32"),T=h||!!f&&(f.includes("abc")||f.includes("gold")||f.includes("bip143"))||!!l&&!b,O=P.alloc(0),A=P.alloc(0),M=P.alloc(4),l&&!b?M.writeUInt32LE(S?2147483652:2147483651,0):E?M.writeUInt32LE(2,0):M.writeUInt32LE(1,0),k=[],x=[],N=[],R=[],C=!0,U=!1,L={inputs:[],version:M,timestamp:P.alloc(0)},D=T&&!y?HS:RS,B=P.from(s,"hex"),w(0,0),ct.label=5;case 5:ct.trys.push([5,11,12,13]),H=JS(n),F=H.next(),ct.label=6;case 6:return F.done?[3,10]:(z=F.value,U?[3,8]:[4,D(t,z[1],z[0],f)]);case 7:q=ct.sent(),_S("hw","got trustedInput="+q),(j=P.alloc(4)).writeUInt32LE(z.length>=4&&"number"==typeof z[3]?z[3]:$v,0),k.push({trustedInput:!0,value:P.from(q,"hex"),sequence:j}),ct.label=8;case 8:G=z[0].outputs,K=z[1],G&&K<=G.length-1&&x.push(G[K]),l&&!b?(L.nVersionGroupId=P.from(S?[133,32,47,137]:[112,130,196,3]),L.nExpiryHeight=l,L.extraData=P.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(L.nExpiryHeight=l),ct.label=9;case 9:return F=H.next(),[3,6];case 10:return[3,13];case 11:return V=ct.sent(),at={error:V},[3,13];case 12:try{F&&!F.done&&(ht=H.return)&&ht.call(H)}finally{if(at)throw at.error}return[7];case 13:if(L.inputs=n.map((function(t){var e=P.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:$v,0),{script:O,prevout:A,sequence:e}})),U)return[3,18];W=[],ot=0,ct.label=14;case 14:return ot=3&&"string"==typeof z[2]?P.from(z[2],"hex"):h?P.concat([P.from([118,169,20]),P_(R[ot]),P.from([136,172])]):x[ot].script,Y=Object.assign({},L),J=T?[k[ot]]:k,T?Y.inputs=[zS(zS({},Y.inputs[ot]),{script:X})]:Y.inputs[ot].script=X,[4,BS(t,!T&&C,Y,J,T,!!l&&!b,f,y)]):[3,34];case 27:return ct.sent(),T?[3,31]:U||!o?[3,29]:[4,GS(t,o)];case 28:ct.sent(),ct.label=29;case 29:return[4,KS(t,B,f)];case 30:ct.sent(),ct.label=31;case 31:return C&&(d(),w(1,0)),[4,FS(t,i[ot],u,a,l,f)];case 32:Z=ct.sent(),w(1,ot+1),N.push(Z),L.inputs[ot].script=O,C&&(C=!1),ct.label=33;case 33:return ot++,[3,26];case 34:for(ot=0;ot0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},sI={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function uI(t,e){return nI(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R,C,U,L;return iI(this,(function(D){switch(D.label){case 0:r=rI(rI({},sI),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,c=P.alloc(0),f=P.alloc(0),(l=P.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?HS:RS,b=P.from(o,"hex"),D.label=1;case 1:D.trys.push([1,7,8,9]),E=oI(n),_=E.next(),D.label=2;case 2:return _.done?[3,6]:(k=_.value,v?[3,4]:[4,w(t,k[1],k[0])]);case 3:S=D.sent(),(A=P.alloc(4)).writeUInt32LE(k.length>=4&&"number"==typeof k[3]?k[3]:$v,0),p.push({trustedInput:!1,value:a?P.from(S,"hex"):P.from(S,"hex").slice(4,40),sequence:A}),D.label=4;case 4:I=k[0].outputs,T=k[1],I&&T<=I.length-1&&d.push(I[T]),D.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=D.sent(),U={error:O},[3,9];case 8:try{_&&!_.done&&(L=E.return)&&L.call(E)}finally{if(U)throw U.error}return[7];case 9:for(M=0;M=4&&"number"==typeof n[M][3]?n[M][3]:$v,0),m.inputs.push({script:c,prevout:f,sequence:A});return a?[4,BS(t,!0,m,p,!0)]:[3,12];case 10:return D.sent(),[4,KS(t,b)];case 11:D.sent(),D.label=12;case 12:M=0,D.label=13;case 13:return M=3&&"string"==typeof k[2]?P.from(k[2],"hex"):d[M].script,N=Object.assign({},m),R=a?[p[M]]:p,a?N.inputs=[rI(rI({},N.inputs[M]),{script:x})]:N.inputs[M].script=x,[4,BS(t,!a&&y,N,R,a)]):[3,19];case 14:return D.sent(),a?[3,16]:[4,KS(t,b)];case 15:D.sent(),D.label=16;case 16:return[4,FS(t,i[M],s,u)];case 17:C=D.sent(),g.push(a?C.toString("hex"):C.slice(0,C.length-1).toString("hex")),m.inputs[M].script=c,y&&(y=!1),D.label=18;case 18:return M++,[3,13];case 19:return[2,g]}}))}))}var aI=function(){return aI=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=P.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},f.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return f.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,P.from([0]))];case 4:return u=f.sent(),a=u[0]-48,0===(h=u.slice(4,4+u[3]))[0]&&(h=h.slice(1)),h=h.toString("hex"),o=4+u[3]+2,0===(c=u.slice(o,o+u[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:a,r:h,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),QS(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),uI(this.transport,t)},t}();function lI(t){var e=P.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var pI=function(t){return P.concat([P.from([2+(1&t[64])]),t.slice(1,33)])};function dI(t){return A_("sha256").update(t).digest()}var gI,yI=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H_(t.map((function(t){return F_(t)}))),this.values=e,this.valuesTree=new H_(e.map((function(t){return F_(t)})))}return t.prototype.commitment=function(){return P.concat([lS(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),vI=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),mI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},wI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},SI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(gI||(gI={}));var TI,OI,AI=function(){},PI=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=gI.YIELD,n.results=e,n}return EI(e,t),e.prototype.execute=function(t){return this.results.push(P.from(t.subarray(1))),this.progressCallback(),P.from("")},e}(AI),MI=function(t){function e(e,r){var n=t.call(this)||this;return n.code=gI.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return EI(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=P.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=lS(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),c=a.length-h;return c>0&&(e=this.queue).push.apply(e,SI([],_I(a.slice(-c)),!1)),P.concat(SI([u.getLeafHash(i),P.from([a.length]),P.from([h])],_I(a.slice(0,h)),!1))},e}(AI),xI=function(t){function e(e){var r=t.call(this)||this;return r.code=gI.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return EI(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=P.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=P.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(TI||(TI={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(OI||(OI={}));var DI=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return CI(this,void 0,void 0,(function(){var n,i,o;return UI(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,OI.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return CI(this,void 0,void 0,(function(){return UI(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(TI.GET_PUBKEY,P.concat([P.from(t?[1]:[0]),Ot(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return CI(this,void 0,void 0,(function(){var o,s;return UI(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new RI((function(){}))).addKnownList(t.keys.map((function(t){return P.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=P.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(TI.GET_WALLET_ADDRESS,P.concat([P.from(i?[1]:[0]),t.getWalletId(),e||P.alloc(32,0),P.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return CI(this,void 0,void 0,(function(){var i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S;return UI(this,(function(I){switch(I.label){case 0:if(i=new bI(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new RI(n)).addKnownList(e.keys.map((function(t){return P.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=LI(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())c=u.value,o.addKnownMapping(c)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=LI(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())c=h.value,o.addKnownMapping(c)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),f=new H_(i.inputMapCommitments.map((function(t){return F_(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new H_(i.outputMapCommitments.map((function(t){return F_(t)}))).getRoot(),[4,this.makeRequest(TI.SIGN_PSBT,P.concat([i.getGlobalKeysValuesRoot(),lS(i.getGlobalInputCount()),f,lS(i.getGlobalOutputCount()),l,e.getWalletId(),r||P.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=LI(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return CI(this,void 0,void 0,(function(){return UI(this,(function(t){return[2,this.makeRequest(TI.GET_MASTER_FINGERPRINT,P.from([]))]}))}))},t}();var BI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},HI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof mS&&"bech32m"!=r.format)||r.verify&&0!=r.verify||qI(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=P.alloc(0),c=P.alloc(0),f=P.alloc(0),l=P.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=P.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(P.from([3,0,0,128]))||y.equals(P.from([4,0,0,128])),m=y.equals(P.from([1,0,0,0]))||y.equals(P.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(f=g.slice(a,4+a),a+=4);var w=fS(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new fI(this.transport)},t.prototype.new=function(){return new mS(new DI(this.transport))},t}();function qI(t){var e=2147483648,r=Mt(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var jI=Object.freeze({__proto__:null,default:FI}),GI={},KI={},VI={},WI={};Object.defineProperty(WI,"__esModule",{value:!0});var $I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zI={},XI={};WI.addCustomErrorDeserializer=function(t,e){XI[t]=e};var YI=WI.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,zI[t]=e,e};function JI(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":$I(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=JI(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}WI.deserializeError=function t(e){if("object"===(void 0===e?"undefined":$I(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=XI[i];if(o)n=o(e);else{var s="Error"===i?Error:zI[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=YI(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},WI.serializeError=function(t){return t?"object"===(void 0===t?"undefined":$I(t))?JI(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(VI,"__esModule",{value:!0}),VI.StatusCodes=VI.DBNotReset=VI.DBWrongPassword=VI.NoDBPathGiven=VI.FirmwareOrAppUpdateRequired=VI.LedgerAPI5xx=VI.LedgerAPI4xx=VI.GenuineCheckFailed=VI.PairingFailed=VI.SyncError=VI.FeeTooHigh=VI.FeeRequired=VI.FeeNotLoaded=VI.CantScanQRCode=VI.ETHAddressNonEIP=VI.WrongAppForCurrency=VI.WrongDeviceForAccount=VI.WebsocketConnectionFailed=VI.WebsocketConnectionError=VI.DeviceShouldStayInApp=VI.TransportWebUSBGestureRequired=VI.TransportInterfaceNotAvailable=VI.TransportOpenUserCancelled=VI.UserRefusedOnDevice=VI.UserRefusedAllowManager=VI.UserRefusedFirmwareUpdate=VI.UserRefusedAddress=VI.UserRefusedDeviceNameChange=VI.UpdateYourApp=VI.UnavailableTezosOriginatedAccountSend=VI.UnavailableTezosOriginatedAccountReceive=VI.RecipientRequired=VI.MCUNotGenuineToDashboard=VI.UnexpectedBootloader=VI.TimeoutTagged=VI.RecommendUndelegation=VI.RecommendSubAccountsToEmpty=VI.PasswordIncorrectError=VI.PasswordsDontMatchError=VI.GasLessThanEstimate=VI.NotSupportedLegacyAddress=VI.NotEnoughGas=VI.NoAccessToCamera=VI.NotEnoughBalanceBecauseDestinationNotCreated=VI.NotEnoughSpendableBalance=VI.NotEnoughBalanceInParentAccount=VI.NotEnoughBalanceToDelegate=VI.NotEnoughBalance=VI.NoAddressesFound=VI.NetworkDown=VI.ManagerUninstallBTCDep=VI.ManagerNotEnoughSpaceError=VI.ManagerFirmwareNotEnoughSpaceError=VI.ManagerDeviceLockedError=VI.ManagerAppDepUninstallRequired=VI.ManagerAppDepInstallRequired=VI.ManagerAppRelyOnBTCError=VI.ManagerAppAlreadyInstalledError=VI.LedgerAPINotAvailable=VI.LedgerAPIErrorWithMessage=VI.LedgerAPIError=VI.UnknownMCU=VI.LatestMCUInstalledError=VI.InvalidAddressBecauseDestinationIsAlsoSource=VI.InvalidAddress=VI.InvalidXRPTag=VI.HardResetFail=VI.FeeEstimationFailed=VI.EthAppPleaseEnableContractData=VI.EnpointConfigError=VI.DisconnectedDeviceDuringOperation=VI.DisconnectedDevice=VI.DeviceSocketNoBulkStatus=VI.DeviceSocketFail=VI.DeviceNameInvalid=VI.DeviceHalted=VI.DeviceInOSUExpected=VI.DeviceOnDashboardUnexpected=VI.DeviceOnDashboardExpected=VI.DeviceNotGenuineError=VI.DeviceGenuineSocketEarlyClose=VI.DeviceAppVerifyNotSupported=VI.CurrencyNotSupported=VI.CashAddrNotSupported=VI.CantOpenDevice=VI.BtcUnmatchedApp=VI.BluetoothRequired=VI.AmountRequired=VI.AccountNotSupported=VI.AccountNameRequiredError=VI.addCustomErrorDeserializer=VI.createCustomErrorClass=VI.deserializeError=VI.serializeError=void 0,VI.TransportError=QI,VI.getAltStatusMessage=eT,VI.TransportStatusError=rT;var ZI=WI;function QI(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}VI.serializeError=ZI.serializeError,VI.deserializeError=ZI.deserializeError,VI.createCustomErrorClass=ZI.createCustomErrorClass,VI.addCustomErrorDeserializer=ZI.addCustomErrorDeserializer,VI.AccountNameRequiredError=(0,ZI.createCustomErrorClass)("AccountNameRequired"),VI.AccountNotSupported=(0,ZI.createCustomErrorClass)("AccountNotSupported"),VI.AmountRequired=(0,ZI.createCustomErrorClass)("AmountRequired"),VI.BluetoothRequired=(0,ZI.createCustomErrorClass)("BluetoothRequired"),VI.BtcUnmatchedApp=(0,ZI.createCustomErrorClass)("BtcUnmatchedApp"),VI.CantOpenDevice=(0,ZI.createCustomErrorClass)("CantOpenDevice"),VI.CashAddrNotSupported=(0,ZI.createCustomErrorClass)("CashAddrNotSupported"),VI.CurrencyNotSupported=(0,ZI.createCustomErrorClass)("CurrencyNotSupported"),VI.DeviceAppVerifyNotSupported=(0,ZI.createCustomErrorClass)("DeviceAppVerifyNotSupported"),VI.DeviceGenuineSocketEarlyClose=(0,ZI.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),VI.DeviceNotGenuineError=(0,ZI.createCustomErrorClass)("DeviceNotGenuine"),VI.DeviceOnDashboardExpected=(0,ZI.createCustomErrorClass)("DeviceOnDashboardExpected"),VI.DeviceOnDashboardUnexpected=(0,ZI.createCustomErrorClass)("DeviceOnDashboardUnexpected"),VI.DeviceInOSUExpected=(0,ZI.createCustomErrorClass)("DeviceInOSUExpected"),VI.DeviceHalted=(0,ZI.createCustomErrorClass)("DeviceHalted"),VI.DeviceNameInvalid=(0,ZI.createCustomErrorClass)("DeviceNameInvalid"),VI.DeviceSocketFail=(0,ZI.createCustomErrorClass)("DeviceSocketFail"),VI.DeviceSocketNoBulkStatus=(0,ZI.createCustomErrorClass)("DeviceSocketNoBulkStatus"),VI.DisconnectedDevice=(0,ZI.createCustomErrorClass)("DisconnectedDevice"),VI.DisconnectedDeviceDuringOperation=(0,ZI.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),VI.EnpointConfigError=(0,ZI.createCustomErrorClass)("EnpointConfig"),VI.EthAppPleaseEnableContractData=(0,ZI.createCustomErrorClass)("EthAppPleaseEnableContractData"),VI.FeeEstimationFailed=(0,ZI.createCustomErrorClass)("FeeEstimationFailed"),VI.HardResetFail=(0,ZI.createCustomErrorClass)("HardResetFail"),VI.InvalidXRPTag=(0,ZI.createCustomErrorClass)("InvalidXRPTag"),VI.InvalidAddress=(0,ZI.createCustomErrorClass)("InvalidAddress"),VI.InvalidAddressBecauseDestinationIsAlsoSource=(0,ZI.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),VI.LatestMCUInstalledError=(0,ZI.createCustomErrorClass)("LatestMCUInstalledError"),VI.UnknownMCU=(0,ZI.createCustomErrorClass)("UnknownMCU"),VI.LedgerAPIError=(0,ZI.createCustomErrorClass)("LedgerAPIError"),VI.LedgerAPIErrorWithMessage=(0,ZI.createCustomErrorClass)("LedgerAPIErrorWithMessage"),VI.LedgerAPINotAvailable=(0,ZI.createCustomErrorClass)("LedgerAPINotAvailable"),VI.ManagerAppAlreadyInstalledError=(0,ZI.createCustomErrorClass)("ManagerAppAlreadyInstalled"),VI.ManagerAppRelyOnBTCError=(0,ZI.createCustomErrorClass)("ManagerAppRelyOnBTC"),VI.ManagerAppDepInstallRequired=(0,ZI.createCustomErrorClass)("ManagerAppDepInstallRequired"),VI.ManagerAppDepUninstallRequired=(0,ZI.createCustomErrorClass)("ManagerAppDepUninstallRequired"),VI.ManagerDeviceLockedError=(0,ZI.createCustomErrorClass)("ManagerDeviceLocked"),VI.ManagerFirmwareNotEnoughSpaceError=(0,ZI.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),VI.ManagerNotEnoughSpaceError=(0,ZI.createCustomErrorClass)("ManagerNotEnoughSpace"),VI.ManagerUninstallBTCDep=(0,ZI.createCustomErrorClass)("ManagerUninstallBTCDep"),VI.NetworkDown=(0,ZI.createCustomErrorClass)("NetworkDown"),VI.NoAddressesFound=(0,ZI.createCustomErrorClass)("NoAddressesFound"),VI.NotEnoughBalance=(0,ZI.createCustomErrorClass)("NotEnoughBalance"),VI.NotEnoughBalanceToDelegate=(0,ZI.createCustomErrorClass)("NotEnoughBalanceToDelegate"),VI.NotEnoughBalanceInParentAccount=(0,ZI.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),VI.NotEnoughSpendableBalance=(0,ZI.createCustomErrorClass)("NotEnoughSpendableBalance"),VI.NotEnoughBalanceBecauseDestinationNotCreated=(0,ZI.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),VI.NoAccessToCamera=(0,ZI.createCustomErrorClass)("NoAccessToCamera"),VI.NotEnoughGas=(0,ZI.createCustomErrorClass)("NotEnoughGas"),VI.NotSupportedLegacyAddress=(0,ZI.createCustomErrorClass)("NotSupportedLegacyAddress"),VI.GasLessThanEstimate=(0,ZI.createCustomErrorClass)("GasLessThanEstimate"),VI.PasswordsDontMatchError=(0,ZI.createCustomErrorClass)("PasswordsDontMatch"),VI.PasswordIncorrectError=(0,ZI.createCustomErrorClass)("PasswordIncorrect"),VI.RecommendSubAccountsToEmpty=(0,ZI.createCustomErrorClass)("RecommendSubAccountsToEmpty"),VI.RecommendUndelegation=(0,ZI.createCustomErrorClass)("RecommendUndelegation"),VI.TimeoutTagged=(0,ZI.createCustomErrorClass)("TimeoutTagged"),VI.UnexpectedBootloader=(0,ZI.createCustomErrorClass)("UnexpectedBootloader"),VI.MCUNotGenuineToDashboard=(0,ZI.createCustomErrorClass)("MCUNotGenuineToDashboard"),VI.RecipientRequired=(0,ZI.createCustomErrorClass)("RecipientRequired"),VI.UnavailableTezosOriginatedAccountReceive=(0,ZI.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),VI.UnavailableTezosOriginatedAccountSend=(0,ZI.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),VI.UpdateYourApp=(0,ZI.createCustomErrorClass)("UpdateYourApp"),VI.UserRefusedDeviceNameChange=(0,ZI.createCustomErrorClass)("UserRefusedDeviceNameChange"),VI.UserRefusedAddress=(0,ZI.createCustomErrorClass)("UserRefusedAddress"),VI.UserRefusedFirmwareUpdate=(0,ZI.createCustomErrorClass)("UserRefusedFirmwareUpdate"),VI.UserRefusedAllowManager=(0,ZI.createCustomErrorClass)("UserRefusedAllowManager"),VI.UserRefusedOnDevice=(0,ZI.createCustomErrorClass)("UserRefusedOnDevice"),VI.TransportOpenUserCancelled=(0,ZI.createCustomErrorClass)("TransportOpenUserCancelled"),VI.TransportInterfaceNotAvailable=(0,ZI.createCustomErrorClass)("TransportInterfaceNotAvailable"),VI.TransportWebUSBGestureRequired=(0,ZI.createCustomErrorClass)("TransportWebUSBGestureRequired"),VI.DeviceShouldStayInApp=(0,ZI.createCustomErrorClass)("DeviceShouldStayInApp"),VI.WebsocketConnectionError=(0,ZI.createCustomErrorClass)("WebsocketConnectionError"),VI.WebsocketConnectionFailed=(0,ZI.createCustomErrorClass)("WebsocketConnectionFailed"),VI.WrongDeviceForAccount=(0,ZI.createCustomErrorClass)("WrongDeviceForAccount"),VI.WrongAppForCurrency=(0,ZI.createCustomErrorClass)("WrongAppForCurrency"),VI.ETHAddressNonEIP=(0,ZI.createCustomErrorClass)("ETHAddressNonEIP"),VI.CantScanQRCode=(0,ZI.createCustomErrorClass)("CantScanQRCode"),VI.FeeNotLoaded=(0,ZI.createCustomErrorClass)("FeeNotLoaded"),VI.FeeRequired=(0,ZI.createCustomErrorClass)("FeeRequired"),VI.FeeTooHigh=(0,ZI.createCustomErrorClass)("FeeTooHigh"),VI.SyncError=(0,ZI.createCustomErrorClass)("SyncError"),VI.PairingFailed=(0,ZI.createCustomErrorClass)("PairingFailed"),VI.GenuineCheckFailed=(0,ZI.createCustomErrorClass)("GenuineCheckFailed"),VI.LedgerAPI4xx=(0,ZI.createCustomErrorClass)("LedgerAPI4xx"),VI.LedgerAPI5xx=(0,ZI.createCustomErrorClass)("LedgerAPI5xx"),VI.FirmwareOrAppUpdateRequired=(0,ZI.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),VI.NoDBPathGiven=(0,ZI.createCustomErrorClass)("NoDBPathGiven"),VI.DBWrongPassword=(0,ZI.createCustomErrorClass)("DBWrongPassword"),VI.DBNotReset=(0,ZI.createCustomErrorClass)("DBNotReset"),QI.prototype=new Error,(0,ZI.addCustomErrorDeserializer)("TransportError",(function(t){return new QI(t.message,t.id)}));var tT=VI.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function eT(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function rT(t){this.name="TransportStatusError";var e=Object.keys(tT).find((function(e){return tT[e]===t}))||"UNKNOWN_ERROR",r=eT(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}rT.prototype=new Error,(0,ZI.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new rT(t.statusCode)})),Object.defineProperty(KI,"__esModule",{value:!0}),KI.getAltStatusMessage=KI.StatusCodes=KI.TransportStatusError=KI.TransportError=void 0;var nT,iT=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:P.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[uT.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new uT.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(P.concat([P.from([e,r,i,o]),P.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new uT.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=hT(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new uT.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return iT(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new uT.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new uT.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();cT.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",cT.ErrorMessage_NoDeviceFound="No Ledger device found",KI.default=cT;var fT={};Object.defineProperty(fT,"__esModule",{value:!0});var lT=VI;function pT(t){var e=P.alloc(2);return e.writeUInt16BE(t,0),e}var dT={data:P.alloc(0),dataLength:0,sequence:0};fT.default=function(t,e){return{makeBlocks:function(r){var n=P.concat([pT(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=P.concat([n,P.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var gT={};Object.defineProperty(gT,"__esModule",{value:!0});var yT=Object.assign||function(t){for(var e=1;e>8;return wT.find((function(t){return t.productIdMM===r}))},gT.identifyProductName=function(t){var e=mT[t];return wT.find((function(t){return t.id===e}))};var bT=[],ET={};for(var _T in vT){var ST=vT[_T],IT=ST.bluetoothSpec;if(IT)for(var TT=0;TT0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",UT());case 6:case"end":return t.stop()}}),t,this)}))),function(){return CT.apply(this,arguments)});var DT=gT;function BT(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var HT=[{vendorId:DT.ledgerUSBVendorId}];xT.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(GI,"__esModule",{value:!0});var FT=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,jT.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:c=r.sent,f=P.from(c.data.buffer),(0,KT.log)("hid-frame","<= "+f.toString("hex")),h=o.reduceResponse(h,f),r.next=14;break;case 23:return(0,KT.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new VT.DisconnectedDeviceDuringOperation(e.message);throw e}))}},JT=GI.default=XT,ZT=Object.freeze(u({__proto__:null,default:JT},[GI]));t.Btc=jI,t.TransportWebUSB=ZT,Object.defineProperty(t,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From f7befcfd74d8260361384ebb381459ac8dd26283 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 16:32:50 +1100 Subject: [PATCH 14/78] ... --- js/ledger.js | 33833 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 33827 insertions(+), 6 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 27a3d3b7..86334648 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1,10 +1,33831 @@ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).buffer=t()}}(function(){return function(){return function t(r,e,n){function i(f,u){if(!e[f]){if(!r[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var h=new Error("Cannot find module '"+f+"'");throw h.code="MODULE_NOT_FOUND",h}var a=e[f]={exports:{}};r[f][0].call(a.exports,function(t){return i(r[f][1][t]||t)},a,a.exports,t,r,e,n)}return e[f].exports}for(var o="function"==typeof require&&require,f=0;fo)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=r.prototype,e}function r(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return u(t,r,e)}function u(t,e,n){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!r.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var n=0|c(t,e),i=f(n),o=i.write(t,e);o!==n&&(i=i.slice(0,o));return i}(t,e);if(ArrayBuffer.isView(t))return a(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(z(t,ArrayBuffer)||t&&z(t.buffer,ArrayBuffer))return function(t,e,n){if(e<0||t.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function c(t,e){if(r.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||z(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var n=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var o=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return P(t).length;default:if(o)return i?-1:N(t).length;e=(""+e).toLowerCase(),o=!0}}function l(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function y(t,e,n,i,o){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),D(n=+n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof e&&(e=r.from(e,i)),r.isBuffer(e))return 0===e.length?-1:g(t,e,n,i,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):g(t,[e],n,i,o);throw new TypeError("val must be string, number or Buffer")}function g(t,r,e,n,i){var o,f=1,u=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;f=2,u/=2,s/=2,e/=2}function h(t,r){return 1===f?t[r]:t.readUInt16BE(r*f)}if(i){var a=-1;for(o=e;ou&&(e=u-s),o=e;o>=0;o--){for(var p=!0,c=0;ci&&(n=i):n=i;var o=r.length;n>o/2&&(n=o/2);for(var f=0;f>8,i=e%256,o.push(i),o.push(n);return o}(r,t.length-e),t,e,n)}function A(t,r,e){return 0===r&&e===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(r,e))}function B(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i239?4:h>223?3:h>191?2:1;if(i+p<=e)switch(p){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],f=t[i+2],128==(192&o)&&128==(192&f)&&(s=(15&h)<<12|(63&o)<<6|63&f)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],f=t[i+2],u=t[i+3],128==(192&o)&&128==(192&f)&&128==(192&u)&&(s=(15&h)<<18|(63&o)<<12|(63&f)<<6|63&u)>65535&&s<1114112&&(a=s)}null===a?(a=65533,p=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=p}return function(t){var r=t.length;if(r<=U)return String.fromCharCode.apply(String,t);var e="",n=0;for(;nthis.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,r,e);case"utf8":case"utf-8":return B(this,r,e);case"ascii":return _(this,r,e);case"latin1":case"binary":return T(this,r,e);case"base64":return A(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},r.prototype.toLocaleString=r.prototype.toString,r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),""},r.prototype.compare=function(t,e,n,i,o){if(z(t,Uint8Array)&&(t=r.from(t,t.offset,t.byteLength)),!r.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),e<0||n>t.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&e>=n)return 0;if(i>=o)return-1;if(e>=n)return 1;if(this===t)return 0;for(var f=(o>>>=0)-(i>>>=0),u=(n>>>=0)-(e>>>=0),s=Math.min(f,u),h=this.slice(i,o),a=t.slice(e,n),p=0;p>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return w(this,t,r,e);case"utf8":case"utf-8":return d(this,t,r,e);case"ascii":return v(this,t,r,e);case"latin1":case"binary":return b(this,t,r,e);case"base64":return m(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var U=4096;function _(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;in)&&(e=n);for(var i="",o=r;oe)throw new RangeError("Trying to access beyond buffer length")}function L(t,e,n,i,o,f){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function R(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function x(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,4),i.write(t,r,e,n,23,4),e+4}function M(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,8),i.write(t,r,e,n,52,8),e+8}r.prototype.slice=function(t,e){var n=this.length;(t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},r.prototype.readUInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*r)),n},r.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},r.prototype.readInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt16BE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r>>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},r.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,255,0),this[r]=255&t,r+1},r.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},r.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=0,f=1,u=0;for(this[r]=255&t;++o>0)-u&255;return r+e},r.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=e-1,f=1,u=0;for(this[r+o]=255&t;--o>=0&&(f*=256);)t<0&&0===u&&0!==this[r+o+1]&&(u=1),this[r+o]=(t/f>>0)-u&255;return r+e},r.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},r.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},r.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeFloatLE=function(t,r,e){return x(this,t,r,!0,e)},r.prototype.writeFloatBE=function(t,r,e){return x(this,t,r,!1,e)},r.prototype.writeDoubleLE=function(t,r,e){return M(this,t,r,!0,e)},r.prototype.writeDoubleBE=function(t,r,e){return M(this,t,r,!1,e)},r.prototype.copy=function(t,e,n,i){if(!r.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--f)t[f+e]=this[f+n];else Uint8Array.prototype.set.call(t,this.subarray(n,i),e);return o},r.prototype.fill=function(t,e,n,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!r.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var o=t.charCodeAt(0);("utf8"===i&&o<128||"latin1"===i)&&(t=o)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(f=e;f55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(f+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function P(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function j(t,r,e,n){for(var i=0;i=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function z(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function D(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":2,buffer:5,ieee754:3}],2:[function(t,r,e){"use strict";e.byteLength=function(t){var r=h(t),e=r[0],n=r[1];return 3*(e+n)/4-n},e.toByteArray=function(t){for(var r,e=h(t),n=e[0],f=e[1],u=new o(function(t,r,e){return 3*(r+e)/4-e}(0,n,f)),s=0,a=f>0?n-4:n,p=0;p>16&255,u[s++]=r>>8&255,u[s++]=255&r;2===f&&(r=i[t.charCodeAt(p)]<<2|i[t.charCodeAt(p+1)]>>4,u[s++]=255&r);1===f&&(r=i[t.charCodeAt(p)]<<10|i[t.charCodeAt(p+1)]<<4|i[t.charCodeAt(p+2)]>>2,u[s++]=r>>8&255,u[s++]=255&r);return u},e.fromByteArray=function(t){for(var r,e=t.length,i=e%3,o=[],f=0,u=e-i;fu?u:f+16383));1===i?(r=t[e-1],o.push(n[r>>2]+n[r<<4&63]+"==")):2===i&&(r=(t[e-2]<<8)+t[e-1],o.push(n[r>>10]+n[r>>4&63]+n[r<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,s=f.length;u0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function a(t,r,e){for(var i,o,f=[],u=r;u>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return f.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],3:[function(t,r,e){e.read=function(t,r,e,n,i){var o,f,u=8*i-n-1,s=(1<>1,a=-7,p=e?i-1:0,c=e?-1:1,l=t[r+p];for(p+=c,o=l&(1<<-a)-1,l>>=-a,a+=u;a>0;o=256*o+t[r+p],p+=c,a-=8);for(f=o&(1<<-a)-1,o>>=-a,a+=n;a>0;f=256*f+t[r+p],p+=c,a-=8);if(0===o)o=1-h;else{if(o===s)return f?NaN:1/0*(l?-1:1);f+=Math.pow(2,n),o-=h}return(l?-1:1)*f*Math.pow(2,o-n)},e.write=function(t,r,e,n,i,o){var f,u,s,h=8*o-i-1,a=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:o-1,y=n?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,f=a):(f=Math.floor(Math.log(r)/Math.LN2),r*(s=Math.pow(2,-f))<1&&(f--,s*=2),(r+=f+p>=1?c/s:c*Math.pow(2,1-p))*s>=2&&(f++,s/=2),f+p>=a?(u=0,f=a):f+p>=1?(u=(r*s-1)*Math.pow(2,i),f+=p):(u=r*Math.pow(2,p-1)*Math.pow(2,i),f=0));i>=8;t[e+l]=255&u,l+=y,u/=256,i-=8);for(f=f<0;t[e+l]=255&f,l+=y,f/=256,h-=8);t[e+l-y]|=128*g}},{}],4:[function(t,r,e){arguments[4][2][0].apply(e,arguments)},{dup:2}],5:[function(t,r,e){arguments[4][1][0].apply(e,arguments)},{"base64-js":4,buffer:5,dup:1,ieee754:6}],6:[function(t,r,e){arguments[4][3][0].apply(e,arguments)},{dup:3}]},{},[1])(1)}); -window.global = window; -window.Buffer = buffer.Buffer; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util')) : + typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$1, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.require$$1)); +})(this, (function (exports, require$$0$1, require$$0$2, require$$0$3, require$$0$4, require$$1) { 'use strict'; -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("crypto"),require("buffer"),require("stream"),require("events"),require("util")):"function"==typeof define&&define.amd?define(["exports","crypto","buffer","stream","events","util"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={},t.require$$0$1,t.require$$0$2,t.require$$0$3,t.require$$0$4,t.require$$1)}(this,(function(t,e,r,n,i,o){"use strict";function s(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function u(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var a=s(e),h=s(r),c=s(n),f=s(i),l=s(o),p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof y?e:y,o=Object.create(i.prototype),s=new P(n||[]);return o._invoke=function(t,e,r){var n=f;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return k()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=T(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===f)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=c(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function c(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var f="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function y(){}function v(){}function m(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,E=b&&b(b(M([])));E&&E!==r&&n.call(E,o)&&(w=E);var _=m.prototype=y.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=c(t[i],t,o);if("throw"!==a.type){var h=a.arg,f=h.value;return f&&"object"==typeof f&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(f).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function T(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,T(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=c(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function O(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function A(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function M(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),A(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;A(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:M(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});var d="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},g=[],y=[],v="undefined"!=typeof Uint8Array?Uint8Array:Array,m=!1;function w(){m=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+g[i>>12&63]+g[i>>6&63]+g[63&i]);return o.join("")}function E(t){var e;m||w();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=g[e>>2],i+=g[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=g[e>>10],i+=g[e>>4&63],i+=g[e<<2&63],i+="="),o.push(i),o.join("")}function _(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,c=-7,f=r?i-1:0,l=r?-1:1,p=t[e+f];for(f+=l,o=p&(1<<-c)-1,p>>=-c,c+=u;c>0;o=256*o+t[e+f],f+=l,c-=8);for(s=o&(1<<-c)-1,o>>=-c,c+=n;c>0;s=256*s+t[e+f],f+=l,c-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function S(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,c=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=c):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+f>=1?l/a:l*Math.pow(2,1-f))*a>=2&&(s++,a/=2),s+f>=c?(u=0,s=c):s+f>=1?(u=(e*a-1)*Math.pow(2,i),s+=f):(u=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var I={}.toString,T=Array.isArray||function(t){return"[object Array]"==I.call(t)};function O(){return P.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function A(t,e){if(O()=O())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+O().toString(16)+" bytes");return 0|t}function C(t){return!(null==t||!t._isBuffer)}function U(t,e){if(C(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return at(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ht(t).length;default:if(n)return at(t).length;e=(""+e).toLowerCase(),n=!0}}function L(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return J(this,e,r);case"utf8":case"utf-8":return $(this,e,r);case"ascii":return X(this,e,r);case"latin1":case"binary":return Y(this,e,r);case"base64":return W(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function D(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function B(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=P.from(e,n)),C(e))return 0===e.length?-1:H(t,e,r,n,i);if("number"==typeof e)return e&=255,P.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):H(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function H(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var c=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var f=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function W(t,e,r){return 0===e&&r===t.length?E(t):E(t.slice(e,r))}function $(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+f<=r)switch(f){case 1:h<128&&(c=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(c=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(c=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(c=a)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=f}return function(t){var e=t.length;if(e<=z)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},P.prototype.compare=function(t,e,r,n,i){if(!C(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),c=0;ci)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return F(this,t,e,r);case"utf8":case"utf-8":return q(this,t,e,r);case"ascii":return j(this,t,e,r);case"latin1":case"binary":return G(this,t,e,r);case"base64":return K(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},P.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var z=4096;function X(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function tt(t,e,r,n,i,o){if(!C(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function et(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function rt(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function nt(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function it(t,e,r,n,i){return i||nt(t,0,r,4),S(t,e,r,n,23,4),r+4}function ot(t,e,r,n,i){return i||nt(t,0,r,8),S(t,e,r,n,52,8),r+8}P.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},P.prototype.readUInt8=function(t,e){return e||Q(t,1,this.length),this[t]},P.prototype.readUInt16LE=function(t,e){return e||Q(t,2,this.length),this[t]|this[t+1]<<8},P.prototype.readUInt16BE=function(t,e){return e||Q(t,2,this.length),this[t]<<8|this[t+1]},P.prototype.readUInt32LE=function(t,e){return e||Q(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},P.prototype.readUInt32BE=function(t,e){return e||Q(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},P.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Q(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},P.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Q(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},P.prototype.readInt8=function(t,e){return e||Q(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},P.prototype.readInt16LE=function(t,e){e||Q(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},P.prototype.readInt16BE=function(t,e){e||Q(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},P.prototype.readInt32LE=function(t,e){return e||Q(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},P.prototype.readInt32BE=function(t,e){return e||Q(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},P.prototype.readFloatLE=function(t,e){return e||Q(t,4,this.length),_(this,t,!0,23,4)},P.prototype.readFloatBE=function(t,e){return e||Q(t,4,this.length),_(this,t,!1,23,4)},P.prototype.readDoubleLE=function(t,e){return e||Q(t,8,this.length),_(this,t,!0,52,8)},P.prototype.readDoubleBE=function(t,e){return e||Q(t,8,this.length),_(this,t,!1,52,8)},P.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||tt(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},P.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,1,255,0),P.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},P.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,65535,0),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):et(this,t,e,!0),e+2},P.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,65535,0),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):et(this,t,e,!1),e+2},P.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,4294967295,0),P.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):rt(this,t,e,!0),e+4},P.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,4294967295,0),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):rt(this,t,e,!1),e+4},P.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);tt(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},P.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);tt(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},P.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,1,127,-128),P.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},P.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,32767,-32768),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):et(this,t,e,!0),e+2},P.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,2,32767,-32768),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):et(this,t,e,!1),e+2},P.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,2147483647,-2147483648),P.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):rt(this,t,e,!0),e+4},P.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||tt(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),P.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):rt(this,t,e,!1),e+4},P.prototype.writeFloatLE=function(t,e,r){return it(this,t,e,!0,r)},P.prototype.writeFloatBE=function(t,e,r){return it(this,t,e,!1,r)},P.prototype.writeDoubleLE=function(t,e,r){return ot(this,t,e,!0,r)},P.prototype.writeDoubleBE=function(t,e,r){return ot(this,t,e,!1,r)},P.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!P.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ht(t){return function(t){var e,r,n,i,o,s;m||w();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new v(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=y[t.charCodeAt(e)]<<2|y[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=y[t.charCodeAt(e)]<<10|y[t.charCodeAt(e+1)]<<4|y[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(st,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ct(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ft(t){return null!=t&&(!!t._isBuffer||lt(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&<(t.slice(0,0))}(t))}function lt(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}const pt=2147483648;var dt=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=pt)throw new Error("Invalid child index");if("h"===o[2]||"H"===o[2]||"'"===o[2])n[i]+=pt;else if(0!=o[2].length)throw new Error("Invalid modifier")}return new dt(n)},dt.prototype.toPathArray=function(){return this.path},dt.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var gt=dt,yt=a.default.createHash,vt={exports:{}}; -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -!function(t,e){var r=h.default,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(vt,vt.exports);var mt=vt.exports.Buffer;var wt=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var c=e[t.charCodeAt(r)];if(255===c)return;for(var f=0,l=o-1;(0!==c||f>>0,h[l]=c%256>>>0,c=c/256>>>0;if(0!==c)throw new Error("Non-zero carry");i=f,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=mt.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=mt.from(e)),!mt.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,c=new Uint8Array(a);i!==o;){for(var f=e[i],l=0,p=a-1;(0!==f||l>>0,c[p]=f%s>>>0,f=f/s>>>0;if(0!==f)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===c[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],c=[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],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,f=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;c+=(s=(i=0|t.words[d])*(o=0|e.words[p])+f)/67108864|0,f=67108863&s}r.words[h]=0|f,a=0|c}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=c[t],p=f[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),c=this.clone();if(a){for(u=0;!c.isZero();u++)s=c.andln(255),c.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,y=0|s[2],v=8191&y,m=y>>>13,w=0|s[3],b=8191&w,E=w>>>13,_=0|s[4],S=8191&_,I=_>>>13,T=0|s[5],O=8191&T,A=T>>>13,P=0|s[6],M=8191&P,k=P>>>13,x=0|s[7],N=8191&x,R=x>>>13,C=0|s[8],U=8191&C,L=C>>>13,D=0|s[9],B=8191&D,H=D>>>13,F=0|u[0],q=8191&F,j=F>>>13,G=0|u[1],K=8191&G,V=G>>>13,W=0|u[2],$=8191&W,z=W>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ct=0|u[8],ft=8191&ct,lt=ct>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var yt=(h+(n=Math.imul(f,q))|0)+((8191&(i=(i=Math.imul(f,j))+Math.imul(l,q)|0))<<13)|0;h=((o=Math.imul(l,j))+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(d,q),i=(i=Math.imul(d,j))+Math.imul(g,q)|0,o=Math.imul(g,j);var vt=(h+(n=n+Math.imul(f,K)|0)|0)+((8191&(i=(i=i+Math.imul(f,V)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(v,q),i=(i=Math.imul(v,j))+Math.imul(m,q)|0,o=Math.imul(m,j),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,V)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,V)|0;var mt=(h+(n=n+Math.imul(f,$)|0)|0)+((8191&(i=(i=i+Math.imul(f,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(b,q),i=(i=Math.imul(b,j))+Math.imul(E,q)|0,o=Math.imul(E,j),n=n+Math.imul(v,K)|0,i=(i=i+Math.imul(v,V)|0)+Math.imul(m,K)|0,o=o+Math.imul(m,V)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(f,Y)|0)|0)+((8191&(i=(i=i+Math.imul(f,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,j))+Math.imul(I,q)|0,o=Math.imul(I,j),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,V)|0)+Math.imul(E,K)|0,o=o+Math.imul(E,V)|0,n=n+Math.imul(v,$)|0,i=(i=i+Math.imul(v,z)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(f,Q)|0)|0)+((8191&(i=(i=i+Math.imul(f,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,j))+Math.imul(A,q)|0,o=Math.imul(A,j),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,V)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,z)|0,n=n+Math.imul(v,Y)|0,i=(i=i+Math.imul(v,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var Et=(h+(n=n+Math.imul(f,rt)|0)|0)+((8191&(i=(i=i+Math.imul(f,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(M,q),i=(i=Math.imul(M,j))+Math.imul(k,q)|0,o=Math.imul(k,j),n=n+Math.imul(O,K)|0,i=(i=i+Math.imul(O,V)|0)+Math.imul(A,K)|0,o=o+Math.imul(A,V)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(v,Q)|0,i=(i=i+Math.imul(v,tt)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var _t=(h+(n=n+Math.imul(f,ot)|0)|0)+((8191&(i=(i=i+Math.imul(f,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,j))+Math.imul(R,q)|0,o=Math.imul(R,j),n=n+Math.imul(M,K)|0,i=(i=i+Math.imul(M,V)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,V)|0,n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,z)|0)+Math.imul(A,$)|0,o=o+Math.imul(A,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,tt)|0,n=n+Math.imul(v,rt)|0,i=(i=i+Math.imul(v,nt)|0)+Math.imul(m,rt)|0,o=o+Math.imul(m,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(f,at)|0)|0)+((8191&(i=(i=i+Math.imul(f,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(U,q),i=(i=Math.imul(U,j))+Math.imul(L,q)|0,o=Math.imul(L,j),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(M,$)|0,i=(i=i+Math.imul(M,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,J)|0)+Math.imul(A,Y)|0,o=o+Math.imul(A,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(E,rt)|0,o=o+Math.imul(E,nt)|0,n=n+Math.imul(v,ot)|0,i=(i=i+Math.imul(v,st)|0)+Math.imul(m,ot)|0,o=o+Math.imul(m,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(f,ft)|0)|0)+((8191&(i=(i=i+Math.imul(f,lt)|0)+Math.imul(l,ft)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,j))+Math.imul(H,q)|0,o=Math.imul(H,j),n=n+Math.imul(U,K)|0,i=(i=i+Math.imul(U,V)|0)+Math.imul(L,K)|0,o=o+Math.imul(L,V)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(R,$)|0,o=o+Math.imul(R,z)|0,n=n+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(E,ot)|0,o=o+Math.imul(E,st)|0,n=n+Math.imul(v,at)|0,i=(i=i+Math.imul(v,ht)|0)+Math.imul(m,at)|0,o=o+Math.imul(m,ht)|0,n=n+Math.imul(d,ft)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ft)|0,o=o+Math.imul(g,lt)|0;var Tt=(h+(n=n+Math.imul(f,dt)|0)|0)+((8191&(i=(i=i+Math.imul(f,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(B,K),i=(i=Math.imul(B,V))+Math.imul(H,K)|0,o=Math.imul(H,V),n=n+Math.imul(U,$)|0,i=(i=i+Math.imul(U,z)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Y)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(A,rt)|0,o=o+Math.imul(A,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(E,at)|0,o=o+Math.imul(E,ht)|0,n=n+Math.imul(v,ft)|0,i=(i=i+Math.imul(v,lt)|0)+Math.imul(m,ft)|0,o=o+Math.imul(m,lt)|0;var Ot=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(B,$),i=(i=Math.imul(B,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(U,Y)|0,i=(i=i+Math.imul(U,J)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(O,ot)|0,i=(i=i+Math.imul(O,st)|0)+Math.imul(A,ot)|0,o=o+Math.imul(A,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ft)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(E,ft)|0,o=o+Math.imul(E,lt)|0;var At=(h+(n=n+Math.imul(v,dt)|0)|0)+((8191&(i=(i=i+Math.imul(v,gt)|0)+Math.imul(m,dt)|0))<<13)|0;h=((o=o+Math.imul(m,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(B,Y),i=(i=Math.imul(B,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(U,Q)|0,i=(i=i+Math.imul(U,tt)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(R,rt)|0,o=o+Math.imul(R,nt)|0,n=n+Math.imul(M,ot)|0,i=(i=i+Math.imul(M,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ht)|0)+Math.imul(A,at)|0,o=o+Math.imul(A,ht)|0,n=n+Math.imul(S,ft)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ft)|0,o=o+Math.imul(I,lt)|0;var Pt=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(E,dt)|0))<<13)|0;h=((o=o+Math.imul(E,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(B,Q),i=(i=Math.imul(B,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(U,rt)|0,i=(i=i+Math.imul(U,nt)|0)+Math.imul(L,rt)|0,o=o+Math.imul(L,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(R,ot)|0,o=o+Math.imul(R,st)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(O,ft)|0,i=(i=i+Math.imul(O,lt)|0)+Math.imul(A,ft)|0,o=o+Math.imul(A,lt)|0;var Mt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(B,rt),i=(i=Math.imul(B,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(U,ot)|0,i=(i=i+Math.imul(U,st)|0)+Math.imul(L,ot)|0,o=o+Math.imul(L,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(R,at)|0,o=o+Math.imul(R,ht)|0,n=n+Math.imul(M,ft)|0,i=(i=i+Math.imul(M,lt)|0)+Math.imul(k,ft)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(A,dt)|0))<<13)|0;h=((o=o+Math.imul(A,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(B,ot),i=(i=Math.imul(B,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(U,at)|0,i=(i=i+Math.imul(U,ht)|0)+Math.imul(L,at)|0,o=o+Math.imul(L,ht)|0,n=n+Math.imul(N,ft)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(R,ft)|0,o=o+Math.imul(R,lt)|0;var xt=(h+(n=n+Math.imul(M,dt)|0)|0)+((8191&(i=(i=i+Math.imul(M,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(B,at),i=(i=Math.imul(B,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(U,ft)|0,i=(i=i+Math.imul(U,lt)|0)+Math.imul(L,ft)|0,o=o+Math.imul(L,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(R,dt)|0))<<13)|0;h=((o=o+Math.imul(R,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(B,ft),i=(i=Math.imul(B,lt))+Math.imul(H,ft)|0,o=Math.imul(H,lt);var Rt=(h+(n=n+Math.imul(U,dt)|0)|0)+((8191&(i=(i=i+Math.imul(U,gt)|0)+Math.imul(L,dt)|0))<<13)|0;h=((o=o+Math.imul(L,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863;var Ct=(h+(n=Math.imul(B,dt))|0)+((8191&(i=(i=Math.imul(B,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,a[0]=yt,a[1]=vt,a[2]=mt,a[3]=wt,a[4]=bt,a[5]=Et,a[6]=_t,a[7]=St,a[8]=It,a[9]=Tt,a[10]=Ot,a[11]=At,a[12]=Pt,a[13]=Mt,a[14]=kt,a[15]=xt,a[16]=Nt,a[17]=Rt,a[18]=Ct,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==c||h>=i);h--){var f=0|this.words[h];this.words[h]=c<<26-o|f>>>o,c=f&u}return a&&0!==c&&(a.words[a.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;f--){var l=67108864*(0|n.words[o.length+f])+(0|n.words[o.length+f-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,f);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,f),n.isZero()||(n.negative^=1);u&&(u.words[f]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var c=n.clone(),f=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(c),s.isub(f)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(c),a.isub(f)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,c=1;0==(e.words[0]&c)&&h<26;++h,c<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var f=0,l=1;0==(n.words[0]&l)&&f<26;++f,l<<=1);if(f>0)for(n.iushrn(f);f-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var y={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(y[t])return y[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new E}return y[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,h).cmp(a);)c.redIAdd(a);for(var f=this.pow(c,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,y=0;0!==g.cmp(u);y++)g=g.redSqr();r(y=0;n--){for(var h=e.words[n],c=a-1;c>=0;c--){var f=h>>c&1;o!==r[0]&&(o=this.sqr(o)),0!==f||0!==s?(s<<=1,s|=f,(4===++u||0===n&&0===c)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,_),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,p)}(Ft);var qt={},jt="6.5.4",Gt={},Kt=Vt;function Vt(t,e){if(!t)throw new Error(e||"Assertion failed")}Vt.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Wt={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Wt),function(t){var e=t,r=Ft.exports,n=Kt,i=Wt;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Gt);var $t,zt={exports:{}};function Xt(t){this.rand=t}if(zt.exports=function(t){return $t||($t=new Xt(null)),$t.generate(t)},zt.exports.Rand=Xt,Xt.prototype.generate=function(t){return this._rand(t)},Xt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var ie=ne;function oe(t,e){this.curve=t,this.type=e,this.precomputed=null}ne.prototype.point=function(){throw new Error("Not implemented")},ne.prototype.validate=function(){throw new Error("Not implemented")},ne.prototype._fixedNafMul=function(t,e){re(t.precomputed);var r=t._getDoubles(),n=te(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),c=this.jpoint(null,null,null),f=i;f>0;f--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];re(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},ne.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,c=this._wnafT3,f=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],v=ee(r[p],r[d]);for(f=Math.max(v[0].length,f),c[p]=new Array(f),c[d]=new Array(f),s=0;s=0;o--){for(var _=0;o>=0;){var S=!0;for(s=0;s=0&&_++,b=b.dblp(_),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},oe.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},de.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},de.prototype.pointFromX=function(t,e){(t=new ce(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},de.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},de.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},ye.prototype.isInfinity=function(){return this.inf},ye.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},ye.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},ye.prototype.getX=function(){return this.x.fromRed()},ye.prototype.getY=function(){return this.y.fromRed()},ye.prototype.mul=function(t){return t=new ce(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},ye.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},ye.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},ye.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},ye.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},ye.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},fe(ve,le.BasePoint),de.prototype.jpoint=function(t,e,r){return new ve(this,t,e,r)},ve.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},ve.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},ve.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),c=h.redMul(u),f=n.redMul(h),l=a.redSqr().redIAdd(c).redISub(f).redISub(f),p=a.redMul(f.redISub(l)).redISub(o.redMul(c)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},ve.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),c=r.redMul(a),f=u.redSqr().redIAdd(h).redISub(c).redISub(c),l=u.redMul(c.redISub(f)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(f,l,p)},ve.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},ve.prototype.inspect=function(){return this.isInfinity()?"":""},ve.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var me=Ft.exports,we=se.exports,be=ie,Ee=Gt;function _e(t){be.call(this,"mont",t),this.a=new me(t.a,16).toRed(this.red),this.b=new me(t.b,16).toRed(this.red),this.i4=new me(4).toRed(this.red).redInvm(),this.two=new me(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}we(_e,be);var Se=_e;function Ie(t,e,r){be.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new me(e,16),this.z=new me(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}_e.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},we(Ie,be.BasePoint),_e.prototype.decodePoint=function(t,e){return this.point(Ee.toArray(t,e),1)},_e.prototype.point=function(t,e){return new Ie(this,t,e)},_e.prototype.pointFromJSON=function(t){return Ie.fromJSON(this,t)},Ie.prototype.precompute=function(){},Ie.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Ie.fromJSON=function(t,e){return new Ie(t,e[0],e[1]||t.one)},Ie.prototype.inspect=function(){return this.isInfinity()?"":""},Ie.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Ie.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},Ie.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},Ie.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},Ie.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Ie.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},Ie.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Ie.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var Te=Gt,Oe=Ft.exports,Ae=se.exports,Pe=ie,Me=Te.assert;function ke(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,Pe.call(this,"edwards",t),this.a=new Oe(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new Oe(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new Oe(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Me(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}Ae(ke,Pe);var xe=ke;function Ne(t,e,r,n,i){Pe.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new Oe(e,16),this.y=new Oe(r,16),this.z=n?new Oe(n,16):this.curve.one,this.t=i&&new Oe(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}ke.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},ke.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},ke.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},ke.prototype.pointFromX=function(t,e){(t=new Oe(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},ke.prototype.pointFromY=function(t,e){(t=new Oe(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},ke.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},Ae(Ne,Pe.BasePoint),ke.prototype.pointFromJSON=function(t){return Ne.fromJSON(this,t)},ke.prototype.point=function(t,e,r,n){return new Ne(this,t,e,r,n)},Ne.fromJSON=function(t,e){return new Ne(t,e[0],e[1],e[2])},Ne.prototype.inspect=function(){return this.isInfinity()?"":""},Ne.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Ne.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),c=i.redMul(u),f=s.redMul(o);return this.curve.point(a,h,f,c)},Ne.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Ne.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Ne.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),c=u.redMul(a),f=o.redMul(a),l=s.redMul(u);return this.curve.point(h,c,l,f)},Ne.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),c=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),f=n.redMul(a).redMul(c);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(f,e,r)},Ne.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Ne.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Ne.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Ne.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Ne.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Ne.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Ne.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Ne.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Ne.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Ne.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Ne.prototype.toP=Ne.prototype.normalize,Ne.prototype.mixedAdd=Ne.prototype.add,function(t){var e=t;e.base=ie,e.short=ge,e.mont=Se,e.edwards=xe}(Jt);var Re={},Ce={},Ue={},Le=Kt,De=se.exports;function Be(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function He(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Fe(t){return 1===t.length?"0"+t:t}function qe(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Ue.inherits=De,Ue.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Be(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Ue.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Ue.rotr32=function(t,e){return t>>>e|t<<32-e},Ue.rotl32=function(t,e){return t<>>32-e},Ue.sum32=function(t,e){return t+e>>>0},Ue.sum32_3=function(t,e,r){return t+e+r>>>0},Ue.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Ue.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Ue.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Ue.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Ue.sum64_lo=function(t,e,r,n){return e+n>>>0},Ue.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Ue.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Ue.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var c=0,f=e;return c+=(f=f+n>>>0)>>0)>>0)>>0)>>0},Ue.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Ue.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Ue.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Ue.shr64_hi=function(t,e,r){return t>>>r},Ue.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var je={},Ge=Ue,Ke=Kt;function Ve(){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}je.BlockHash=Ve,Ve.prototype.update=function(t,e){if(t=Ge.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ge.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},$e.g1_256=function(t){return ze(t,17)^ze(t,19)^t>>>10};var Ze=Ue,Qe=je,tr=$e,er=Ze.rotl32,rr=Ze.sum32,nr=Ze.sum32_5,ir=tr.ft_1,or=Qe.BlockHash,sr=[1518500249,1859775393,2400959708,3395469782];function ur(){if(!(this instanceof ur))return new ur;or.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ze.inherits(ur,or);var ar=ur;ur.blockSize=512,ur.outSize=160,ur.hmacStrength=80,ur.padLength=64,ur.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),Pn(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Un=Cn;Cn.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},Cn.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Nn.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Fn=Ft.exports,qn=Gt,jn=qn.assert;function Gn(t,e){if(t instanceof Gn)return t;this._importDER(t,e)||(jn(t.r&&t.s,"Signature without r or s"),this.r=new Fn(t.r,16),this.s=new Fn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Kn=Gn;function Vn(){this.place=0}function Wn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function $n(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Gn.prototype._importDER=function(t,e){t=qn.toArray(t,e);var r=new Vn;if(48!==t[r.place++])return!1;var n=Wn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Wn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Wn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Fn(o),this.s=new Fn(u),this.recoveryParam=null,!0},Gn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=$n(e),r=$n(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];zn(n,e.length),(n=n.concat(e)).push(2),zn(n,r.length);var i=n.concat(r),o=[48];return zn(o,i.length),o=o.concat(i),qn.encode(o,t)};var Xn=Ft.exports,Yn=Un,Jn=Gt,Zn=Re,Qn=zt.exports,ti=Jn.assert,ei=Hn,ri=Kn;function ni(t){if(!(this instanceof ni))return new ni(t);"string"==typeof t&&(ti(Object.prototype.hasOwnProperty.call(Zn,t),"Unknown curve "+t),t=Zn[t]),t instanceof Zn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var ii=ni;ni.prototype.keyPair=function(t){return new ei(this,t)},ni.prototype.keyFromPrivate=function(t,e){return ei.fromPrivate(this,t,e)},ni.prototype.keyFromPublic=function(t,e){return ei.fromPublic(this,t,e)},ni.prototype.genKeyPair=function(t){t||(t={});for(var e=new Yn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||Qn(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Xn(2));;){var i=new Xn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},ni.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},ni.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Xn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Yn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Xn(1)),h=0;;h++){var c=n.k?n.k(h):new Xn(u.generate(this.n.byteLength()));if(!((c=this._truncateToN(c,!0)).cmpn(1)<=0||c.cmp(a)>=0)){var f=this.g.mul(c);if(!f.isInfinity()){var l=f.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=c.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(f.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new ri({r:p,s:d,recoveryParam:g})}}}}}},ni.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Xn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new ri(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},ni.prototype.recoverPubKey=function(t,e,r,n){ti((3&r)===r,"The recovery param is more than two bits"),e=new ri(e,n);var i=this.n,o=new Xn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var c=e.r.invm(i),f=i.sub(o).mul(c).umod(i),l=u.mul(c).umod(i);return this.g.mulAdd(f,s,l)},ni.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new ri(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var oi=Gt,si=oi.assert,ui=oi.parseBytes,ai=oi.cachedProperty;function hi(t,e){this.eddsa=t,this._secret=ui(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=ui(e.pub)}hi.fromPublic=function(t,e){return e instanceof hi?e:new hi(t,{pub:e})},hi.fromSecret=function(t,e){return e instanceof hi?e:new hi(t,{secret:e})},hi.prototype.secret=function(){return this._secret},ai(hi,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ai(hi,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ai(hi,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ai(hi,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ai(hi,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ai(hi,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),hi.prototype.sign=function(t){return si(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},hi.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},hi.prototype.getSecret=function(t){return si(this._secret,"KeyPair is public only"),oi.encode(this.secret(),t)},hi.prototype.getPublic=function(t){return oi.encode(this.pubBytes(),t)};var ci=hi,fi=Ft.exports,li=Gt,pi=li.assert,di=li.cachedProperty,gi=li.parseBytes;function yi(t,e){this.eddsa=t,"object"!=typeof e&&(e=gi(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),pi(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof fi&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}di(yi,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),di(yi,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),di(yi,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),di(yi,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),yi.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},yi.prototype.toHex=function(){return li.encode(this.toBytes(),"hex").toUpperCase()};var vi=yi,mi=Ce,wi=Re,bi=Gt,Ei=bi.assert,_i=bi.parseBytes,Si=ci,Ii=vi;function Ti(t){if(Ei("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof Ti))return new Ti(t);t=wi[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=mi.sha512}var Oi=Ti;Ti.prototype.sign=function(t,e){t=_i(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},Ti.prototype.verify=function(t,e,r){t=_i(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},Ti.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Zi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Ci)&&(!(n.compare(Li)>=0)&&(4===e&&65===t.length))}function $i(t){return 4!==t[0]}function zi(t){return!!Ki(t)&&(t.compare(Ci)>0&&t.compare(Ui)<0)}function Xi(t,e){return void 0===t&&void 0!==e?$i(e):void 0===t||t}function Yi(t){return new xi(t)}function Ji(t){return t.toArrayLike(P,"be",32)}function Zi(t){return Ni.curve.decodePoint(t)}function Qi(t,e){return P.from(t._encode(e))}function to(t,e,r){if(!Ki(t))throw new TypeError(Gi);if(!zi(e))throw new TypeError(Fi);if(void 0!==r&&!Ki(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Yi(e),i=Yi(t);let o,s;Ri(t,e,(function(t){const e=Yi(t),r=Hi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Di),0!==o.isZero()&&(s=e.invm(Di).mul(i.add(n.mul(o))).umod(Di),0!==s.isZero()))}),zi,r),s.cmp(Bi)>0&&(s=Di.sub(s));const u=P.allocUnsafe(64);return Ji(o).copy(u,0),Ji(s).copy(u,32),u}var eo={isPoint:Wi,isPointCompressed:function(t){return!!Wi(t)&&$i(t)},isPrivate:zi,pointAdd:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Wi(e))throw new TypeError(qi);const n=Zi(t),i=Zi(e),o=n.add(i);return o.isInfinity()?null:Qi(o,Xi(r,t))},pointAddScalar:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Vi(e))throw new TypeError(ji);const n=Xi(r,t),i=Zi(t);if(0===e.compare(Ci))return Qi(i,n);const o=Yi(e),s=Hi.mul(o),u=i.add(s);return u.isInfinity()?null:Qi(u,n)},pointCompress:function(t,e){if(!Wi(t))throw new TypeError(qi);const r=Zi(t);if(r.isInfinity())throw new TypeError(qi);return Qi(r,Xi(e,t))},pointFromScalar:function(t,e){if(!zi(t))throw new TypeError(Fi);const r=Yi(t),n=Hi.mul(r);return n.isInfinity()?null:Qi(n,Xi(e))},pointMultiply:function(t,e,r){if(!Wi(t))throw new TypeError(qi);if(!Vi(e))throw new TypeError(ji);const n=Xi(r,t),i=Zi(t),o=Yi(e),s=i.mul(o);return s.isInfinity()?null:Qi(s,n)},privateAdd:function(t,e){if(!zi(t))throw new TypeError(Fi);if(!Vi(e))throw new TypeError(ji);const r=Yi(t),n=Yi(e),i=Ji(r.add(n).umod(Di));return zi(i)?i:null},privateSub:function(t,e){if(!zi(t))throw new TypeError(Fi);if(!Vi(e))throw new TypeError(ji);const r=Yi(t),n=Yi(e),i=Ji(r.sub(n).umod(Di));return zi(i)?i:null},sign:function(t,e){return to(t,e)},signWithEntropy:function(t,e,r){return to(t,e,r)},verify:function(t,e,r,n){if(!Ki(t))throw new TypeError(Gi);if(!Wi(e))throw new TypeError(qi);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return ft(t)&&64===t.length&&e.compare(Ui)<0&&r.compare(Ui)<0}(r))throw new TypeError("Expected Signature");const i=Zi(e),o=Yi(r.slice(0,32)),s=Yi(r.slice(32,64));if(n&&s.cmp(Bi)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Yi(t),a=s.invm(Di),h=u.mul(a).umod(Di),c=o.mul(a).umod(Di),f=Hi.mulAdd(h,i,c);return!f.isInfinity()&&f.x.umod(Di).eq(o)}};try{Ht.exports=require("./native")}catch(t){Ht.exports=eo}var ro={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var no in ro.Null=ro.Nil,ro)ro[no].toJSON=function(t){return t}.bind(null,no);var io=ro,oo=io;function so(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function uo(t){return oo.Nil(t)?"":so(t.constructor)}function ao(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function ho(t){return oo.Function(t)?t.toJSON?t.toJSON():so(t):oo.Array(t)?"Array":t&&oo.Object(t)?"Object":void 0!==t?t:""}function co(t,e,r){var n=function(t){return oo.Function(t)?"":oo.String(t)?JSON.stringify(t):t&&oo.Object(t)?"":t}(e);return"Expected "+ho(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function fo(t,e,r){r=r||uo(e),this.message=co(t,e,r),ao(this,fo),this.__type=t,this.__value=e,this.__valueTypeName=r}function lo(t,e,r,n,i){t?(i=i||uo(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),co('property "'+ho(r)+o+ho(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',ao(this,fo),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}fo.prototype=Object.create(Error.prototype),fo.prototype.constructor=fo,lo.prototype=Object.create(Error.prototype),lo.prototype.constructor=fo;var po={TfTypeError:fo,TfPropertyTypeError:lo,tfCustomError:function(t,e){return new fo(t,{},e)},tfSubError:function(t,e,r){return t instanceof lo?(e=e+"."+t.__property,t=new lo(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof fo&&(t=new lo(t.__type,e,r,t.__value,t.__valueTypeName)),ao(t),t},tfJSON:ho,getValueTypeName:uo},go=io,yo=po;function vo(t){return ft(t)}function mo(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function wo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw yo.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var bo=wo.bind(null,go.Array),Eo=wo.bind(null,vo),_o=wo.bind(null,mo),So=wo.bind(null,go.String);var Io=Math.pow(2,53)-1;var To={ArrayN:bo,Buffer:vo,BufferN:Eo,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:mo,HexN:_o,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-Io&&t<=Io&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=Io&&Math.floor(t)===t}};for(var Oo in To)To[Oo].toJSON=function(t){return t}.bind(null,Oo);var Ao=To,Po=io,Mo=po.tfJSON,ko=po.TfTypeError,xo=po.TfPropertyTypeError,No=po.tfSubError,Ro=po.getValueTypeName,Co={arrayOf:function(t,e){function r(r,n){return!!Po.Array(r)&&(!Po.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return Lo(t,e,n)}catch(t){throw No(t,r)}}))))))}return t=Uo(t),e=e||{},r.toJSON=function(){var r="["+Mo(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return Po.Nil(r)||e(r,n,t)}return e=Uo(e),r.toJSON=function(){return"?"+Mo(e)},r},map:function(t,e){function r(r,n){if(!Po.Object(r))return!1;if(Po.Nil(r))return!1;for(var i in r){try{e&&Lo(e,i,n)}catch(t){throw No(t,i,"key")}try{var o=r[i];Lo(t,o,n)}catch(t){throw No(t,i)}}return!0}return t=Uo(t),e&&(e=Uo(e)),r.toJSON=e?function(){return"{"+Mo(e)+": "+Mo(t)+"}"}:function(){return"{"+Mo(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Uo(t[r]);function n(t,r){if(!Po.Object(t))return!1;if(Po.Nil(t))return!1;var n;try{for(n in e){Lo(e[n],t[n],r)}}catch(t){throw No(t,n)}if(r)for(n in t)if(!e[n])throw new xo(void 0,n);return!0}return n.toJSON=function(){return Mo(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return t.some((function(t){try{return Lo(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Mo).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return t.every((function(t){try{return Lo(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(Mo).join(" & ")},e},quacksLike:function(t){function e(e){return t===Ro(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Uo);function e(e,r){return!Po.Nil(e)&&(!Po.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return Lo(t,e[n],r)}catch(t){throw No(t,n)}}))))}return e.toJSON=function(){return"("+t.map(Mo).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Uo(t){if(Po.String(t))return"?"===t[0]?Co.maybe(t.slice(1)):Po[t]||Co.quacksLike(t);if(t&&Po.Object(t)){if(Po.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Co.arrayOf(t[0])}return Co.object(t)}return Po.Function(t)?t:Co.value(t)}function Lo(t,e,r,n){if(Po.Function(t)){if(t(e,r))return!0;throw new ko(n||t,e)}return Lo(Uo(t),e,r)}for(var Do in Co.oneOf=Co.anyOf,Po)Lo[Do]=Po[Do];for(Do in Co)Lo[Do]=Co[Do];var Bo=Ao;for(Do in Bo)Lo[Do]=Bo[Do];Lo.compile=Uo,Lo.TfTypeError=ko,Lo.TfPropertyTypeError=xo;var Ho=Lo,Fo=Tt;function qo(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function jo(t,e,r){var n=new P(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Go={decode:function(t,e){return qo(Fo.decode(t),e)},decodeRaw:qo,encode:function(t,e,r){return"number"==typeof t?Fo.encode(jo(t,e,r)):Fo.encode(jo(t.version,t.privateKey,t.compressed))},encodeRaw:jo};Object.defineProperty(Ct,"__esModule",{value:!0});const Ko=Ut,Vo=Tt,Wo=Ht.exports,$o=Ho,zo=Go,Xo=$o.BufferN(32),Yo=$o.compile({wif:$o.UInt8,bip32:{public:$o.UInt32,private:$o.UInt32}}),Jo={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Zo=2147483648,Qo=Math.pow(2,31)-1;function ts(t){return $o.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function es(t){return $o.UInt32(t)&&t<=Qo}class rs{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,$o(Yo,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Wo.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Ko.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return os(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=P.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Vo.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return zo.encode(this.network.wif,this.privateKey,!0)}derive(t){$o($o.UInt32,t);const e=t>=Zo,r=P.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Ko.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Wo.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Wo.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=os(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Wo.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=is(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return $o(es,t),this.derive(t+Zo)}derivePath(t){$o(ts,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Wo.sign(t,this.privateKey);{let e=Wo.sign(t,this.privateKey);const r=P.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Wo.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Wo.verify(t,this.publicKey,e)}}function ns(t,e,r){return is(t,e,r)}function is(t,e,r,n,i,o){if($o({privateKey:Xo,chainCode:Xo},{privateKey:t,chainCode:e}),r=r||Jo,!Wo.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new rs(t,void 0,e,r,n,i,o)}function os(t,e,r,n,i,o){if($o({publicKey:$o.BufferN(33),chainCode:Xo},{publicKey:t,chainCode:e}),r=r||Jo,!Wo.isPoint(t))throw new TypeError("Point is not on the curve");return new rs(void 0,t,e,r,n,i,o)}Ct.fromBase58=function(t,e){const r=Vo.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Jo;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=is(r.slice(46,78),u,e,i,s,o)}else{a=os(r.slice(45,78),u,e,i,s,o)}return a},Ct.fromPrivateKey=ns,Ct.fromPublicKey=function(t,e,r){return os(t,e,r)},Ct.fromSeed=function(t,e){if($o($o.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Jo;const r=Ko.hmacSHA512(P.from("Bitcoin seed","utf8"),t);return ns(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Rt,"__esModule",{value:!0});var ss=Ct;Rt.fromSeed=ss.fromSeed,Rt.fromBase58=ss.fromBase58,Rt.fromPublicKey=ss.fromPublicKey,Rt.fromPrivateKey=ss.fromPrivateKey;var us={},as={};Object.defineProperty(as,"__esModule",{value:!0}),as.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},as.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},as.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var hs={},cs={},fs={},ls={};Object.defineProperty(ls,"__esModule",{value:!0}),ls.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=P.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var ps={},ds={};Object.defineProperty(ds,"__esModule",{value:!0});const gs=Ho,ys=Math.pow(2,31)-1;function vs(t){return gs.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}ds.UInt31=function(t){return gs.UInt32(t)&&t<=ys},ds.BIP32Path=vs,vs.toJSON=()=>"BIP32 derivation path",ds.Signer=function(t){return(gs.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};ds.Satoshi=function(t){return gs.UInt53(t)&&t<=21e14},ds.ECPoint=gs.quacksLike("Point"),ds.Network=gs.compile({messagePrefix:gs.oneOf(gs.Buffer,gs.String),bip32:{public:gs.UInt32,private:gs.UInt32},pubKeyHash:gs.UInt8,scriptHash:gs.UInt8,wif:gs.UInt8}),ds.Buffer256bit=gs.BufferN(32),ds.Hash160bit=gs.BufferN(20),ds.Hash256bit=gs.BufferN(32),ds.Number=gs.Number,ds.Array=gs.Array,ds.Boolean=gs.Boolean,ds.String=gs.String,ds.Buffer=gs.Buffer,ds.Hex=gs.Hex,ds.maybe=gs.maybe,ds.tuple=gs.tuple,ds.UInt8=gs.UInt8,ds.UInt32=gs.UInt32,ds.Function=gs.Function,ds.BufferN=gs.BufferN,ds.Null=gs.Null,ds.oneOf=gs.oneOf;var ms=vt.exports.Buffer;var ws={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=ms.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(ps,"__esModule",{value:!0});const bs=ds,Es=ws,_s=Ho,Ss=P.alloc(1,0);function Is(t){let e=0;for(;0===t[e];)++e;return e===t.length?Ss:128&(t=t.slice(e))[0]?P.concat([Ss,t],1+t.length):t}function Ts(t){0===t[0]&&(t=t.slice(1));const e=P.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}ps.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Es.decode(t.slice(0,-1)),i=Ts(n.r),o=Ts(n.s);return{signature:P.concat([i,o],64),hashType:e}},ps.encode=function(t,e){_s({signature:bs.BufferN(64),hashType:bs.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=P.allocUnsafe(1);n.writeUInt8(e,0);const i=Is(t.slice(0,32)),o=Is(t.slice(32,64));return P.concat([Es.encode(i,o),n])};var Os={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},As=Os;function Ps(t){return tt.length)return null;r=t.readUInt8(e+1),n=2}else if(i===As.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==As.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},ks=Os,xs={};for(var Ns in ks){xs[ks[Ns]]=Ns}var Rs=xs;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ls,r=ps,n=ds,i=ws,o=Ht.exports,s=Ms,u=Ho;t.OPS=Os;const a=Rs,h=t.OPS.OP_RESERVED;function c(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function f(t){return n.Array(t)&&t.every(c)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return ft(t)}function d(t){return ft(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=P.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function y(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function v(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=f,t.compile=g,t.decompile=y,t.toASM=function(t){return p(t)&&(t=y(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),P.from(e,"hex")))))},t.toStack=function(r){return r=y(r),u(f,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?P.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=v,t.isCanonicalScriptSignature=function(t){return!!ft(t)&&(!!v(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(fs);var Cs={};Object.defineProperty(Cs,"__esModule",{value:!0}),Cs.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},Cs.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(cs,"__esModule",{value:!0});const Us=as,Ls=fs,Ds=Cs,Bs=Ho,Hs=Ls.OPS;cs.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Bs({network:Bs.maybe(Bs.Object),output:Bs.maybe(Bs.Buffer),data:Bs.maybe(Bs.arrayOf(Bs.Buffer))},t);const r={name:"embed",network:t.network||Us.bitcoin};if(Ds.prop(r,"output",(()=>{if(t.data)return Ls.compile([Hs.OP_RETURN].concat(t.data))})),Ds.prop(r,"data",(()=>{if(t.output)return Ls.decompile(t.output).slice(1)})),e.validate&&t.output){const e=Ls.decompile(t.output);if(e[0]!==Hs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Bs.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Fs={};Object.defineProperty(Fs,"__esModule",{value:!0});const qs=as,js=fs,Gs=Cs,Ks=js.OPS,Vs=Ho,Ws=Ht.exports,$s=Ks.OP_RESERVED;function zs(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Fs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return js.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ks.OP_0)}e=Object.assign({validate:!0},e||{}),Vs({network:Vs.maybe(Vs.Object),m:Vs.maybe(Vs.Number),n:Vs.maybe(Vs.Number),output:Vs.maybe(Vs.Buffer),pubkeys:Vs.maybe(Vs.arrayOf(Ws.isPoint)),signatures:Vs.maybe(Vs.arrayOf(r)),input:Vs.maybe(Vs.Buffer)},t);const n={network:t.network||qs.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=js.decompile(t),n.m=i[0]-$s,n.n=i[i.length-2]-$s,n.pubkeys=i.slice(1,-2))}if(Gs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return js.compile([].concat($s+t.m,t.pubkeys,$s+n.n,Ks.OP_CHECKMULTISIG))})),Gs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Gs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Gs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Gs.prop(n,"signatures",(()=>{if(t.input)return js.decompile(t.input).slice(1)})),Gs.prop(n,"input",(()=>{if(t.signatures)return js.compile([Ks.OP_0].concat(t.signatures))})),Gs.prop(n,"witness",(()=>{if(n.input)return[]})),Gs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Vs.Number(i[0]))throw new TypeError("Output is invalid");if(!Vs.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ks.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Ws.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!zs(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ks.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!zs(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});const Ys=as,Js=fs,Zs=Cs,Qs=Ho,tu=Js.OPS,eu=Ht.exports;Xs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Qs({network:Qs.maybe(Qs.Object),output:Qs.maybe(Qs.Buffer),pubkey:Qs.maybe(eu.isPoint),signature:Qs.maybe(Js.isCanonicalScriptSignature),input:Qs.maybe(Qs.Buffer)},t);const r=Zs.value((()=>Js.decompile(t.input))),n={name:"p2pk",network:t.network||Ys.bitcoin};if(Zs.prop(n,"output",(()=>{if(t.pubkey)return Js.compile([t.pubkey,tu.OP_CHECKSIG])})),Zs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Zs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Zs.prop(n,"input",(()=>{if(t.signature)return Js.compile([t.signature])})),Zs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==tu.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!eu.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Js.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var ru={},nu={};Object.defineProperty(nu,"__esModule",{value:!0});const iu=yt;function ou(t){try{return iu("rmd160").update(t).digest()}catch(e){return iu("ripemd160").update(t).digest()}}function su(t){return iu("sha256").update(t).digest()}nu.ripemd160=ou,nu.sha1=function(t){return iu("sha1").update(t).digest()},nu.sha256=su,nu.hash160=function(t){return ou(su(t))},nu.hash256=function(t){return su(su(t))},Object.defineProperty(ru,"__esModule",{value:!0});const uu=nu,au=as,hu=fs,cu=Cs,fu=Ho,lu=hu.OPS,pu=Ht.exports,du=Tt;ru.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),fu({network:fu.maybe(fu.Object),address:fu.maybe(fu.String),hash:fu.maybe(fu.BufferN(20)),output:fu.maybe(fu.BufferN(25)),pubkey:fu.maybe(pu.isPoint),signature:fu.maybe(hu.isCanonicalScriptSignature),input:fu.maybe(fu.Buffer)},t);const r=cu.value((()=>{const e=du.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=cu.value((()=>hu.decompile(t.input))),i=t.network||au.bitcoin,o={name:"p2pkh",network:i};if(cu.prop(o,"address",(()=>{if(!o.hash)return;const t=P.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),du.encode(t)})),cu.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?uu.hash160(t.pubkey||o.pubkey):void 0)),cu.prop(o,"output",(()=>{if(o.hash)return hu.compile([lu.OP_DUP,lu.OP_HASH160,o.hash,lu.OP_EQUALVERIFY,lu.OP_CHECKSIG])})),cu.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),cu.prop(o,"signature",(()=>{if(t.input)return n()[0]})),cu.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return hu.compile([t.signature,t.pubkey])})),cu.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=P.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==lu.OP_DUP||t.output[1]!==lu.OP_HASH160||20!==t.output[2]||t.output[23]!==lu.OP_EQUALVERIFY||t.output[24]!==lu.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=uu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!hu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!pu.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=uu.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var gu={};Object.defineProperty(gu,"__esModule",{value:!0});const yu=nu,vu=as,mu=fs,wu=Cs,bu=Ho,Eu=mu.OPS,_u=Tt;gu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),bu({network:bu.maybe(bu.Object),address:bu.maybe(bu.String),hash:bu.maybe(bu.BufferN(20)),output:bu.maybe(bu.BufferN(23)),redeem:bu.maybe({network:bu.maybe(bu.Object),output:bu.maybe(bu.Buffer),input:bu.maybe(bu.Buffer),witness:bu.maybe(bu.arrayOf(bu.Buffer))}),input:bu.maybe(bu.Buffer),witness:bu.maybe(bu.arrayOf(bu.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||vu.bitcoin);const n={network:r},i=wu.value((()=>{const e=_u.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=wu.value((()=>mu.decompile(t.input))),s=wu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:mu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(wu.prop(n,"address",(()=>{if(!n.hash)return;const t=P.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),_u.encode(t)})),wu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?yu.hash160(n.redeem.output):void 0)),wu.prop(n,"output",(()=>{if(n.hash)return mu.compile([Eu.OP_HASH160,n.hash,Eu.OP_EQUAL])})),wu.prop(n,"redeem",(()=>{if(t.input)return s()})),wu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return mu.compile([].concat(mu.decompile(t.redeem.input),t.redeem.output))})),wu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),wu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=P.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==Eu.OP_HASH160||20!==t.output[1]||t.output[22]!==Eu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=mu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=yu.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=mu.decompile(t.input);if(!mu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!ft(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var Su={},Iu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Tu={},Ou=0;Ou>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Mu(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Pu(e)^n>>5}for(e=Pu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Mu(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(f)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function xu(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Mu(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=Pu(n)^s,i+=Iu.charAt(s)}for(o=0;o<6;++o)n=Pu(n);for(n^=1,o=0;o<6;++o){i+=Iu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=xu(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=xu(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=xu(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=xu(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(Su,"__esModule",{value:!0});const Ru=nu,Cu=as,Uu=fs,Lu=Cs,Du=Ho,Bu=Uu.OPS,Hu=Ht.exports,Fu=Nu,qu=P.alloc(0);Su.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Du({address:Du.maybe(Du.String),hash:Du.maybe(Du.BufferN(20)),input:Du.maybe(Du.BufferN(0)),network:Du.maybe(Du.Object),output:Du.maybe(Du.BufferN(22)),pubkey:Du.maybe(Hu.isPoint),signature:Du.maybe(Uu.isCanonicalScriptSignature),witness:Du.maybe(Du.arrayOf(Du.Buffer))},t);const r=Lu.value((()=>{const e=Fu.decode(t.address),r=e.words.shift(),n=Fu.fromWords(e.words);return{version:r,prefix:e.prefix,data:P.from(n)}})),n=t.network||Cu.bitcoin,i={name:"p2wpkh",network:n};if(Lu.prop(i,"address",(()=>{if(!i.hash)return;const t=Fu.toWords(i.hash);return t.unshift(0),Fu.encode(n.bech32,t)})),Lu.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Ru.hash160(t.pubkey||i.pubkey):void 0)),Lu.prop(i,"output",(()=>{if(i.hash)return Uu.compile([Bu.OP_0,i.hash])})),Lu.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),Lu.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),Lu.prop(i,"input",(()=>{if(i.witness)return qu})),Lu.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=P.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Bu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Ru.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!Hu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Uu.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!Hu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Ru.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var ju={};Object.defineProperty(ju,"__esModule",{value:!0});const Gu=nu,Ku=as,Vu=fs,Wu=Cs,$u=Ho,zu=Vu.OPS,Xu=Ht.exports,Yu=Nu,Ju=P.alloc(0);function Zu(t){return!(!ft(t)||65!==t.length||4!==t[0]||!Xu.isPoint(t))}ju.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),$u({network:$u.maybe($u.Object),address:$u.maybe($u.String),hash:$u.maybe($u.BufferN(32)),output:$u.maybe($u.BufferN(34)),redeem:$u.maybe({input:$u.maybe($u.Buffer),network:$u.maybe($u.Object),output:$u.maybe($u.Buffer),witness:$u.maybe($u.arrayOf($u.Buffer))}),input:$u.maybe($u.BufferN(0)),witness:$u.maybe($u.arrayOf($u.Buffer))},t);const r=Wu.value((()=>{const e=Yu.decode(t.address),r=e.words.shift(),n=Yu.fromWords(e.words);return{version:r,prefix:e.prefix,data:P.from(n)}})),n=Wu.value((()=>Vu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Ku.bitcoin);const o={network:i};if(Wu.prop(o,"address",(()=>{if(!o.hash)return;const t=Yu.toWords(o.hash);return t.unshift(0),Yu.encode(i.bech32,t)})),Wu.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Gu.sha256(o.redeem.output):void 0)),Wu.prop(o,"output",(()=>{if(o.hash)return Vu.compile([zu.OP_0,o.hash])})),Wu.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Ju,witness:t.witness.slice(0,-1)}})),Wu.prop(o,"input",(()=>{if(o.witness)return Ju})),Wu.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Vu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Ju,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Wu.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=P.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==zu.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Vu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Gu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Vu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Zu)||t.redeem.output&&(Vu.decompile(t.redeem.output)||[]).some(Zu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Zu)||(Vu.decompile(e)||[]).some(Zu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(hs,"__esModule",{value:!0});const Qu=cs;hs.embed=Qu.p2data;const ta=Fs;hs.p2ms=ta.p2ms;const ea=Xs;hs.p2pk=ea.p2pk;const ra=ru;hs.p2pkh=ra.p2pkh;const na=gu;hs.p2sh=na.p2sh;const ia=Su;hs.p2wpkh=ia.p2wpkh;const oa=ju;hs.p2wsh=oa.p2wsh,Object.defineProperty(us,"__esModule",{value:!0});const sa=as,ua=hs,aa=fs,ha=ds,ca=Nu,fa=Tt,la=Ho;function pa(t){const e=fa.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function da(t){const e=ca.decode(t),r=ca.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:P.from(r)}}us.fromBase58Check=pa,us.fromBech32=da,us.toBase58Check=function(t,e){la(ha.tuple(ha.Hash160bit,ha.UInt8),arguments);const r=P.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),fa.encode(r)},us.toBech32=function(t,e,r){const n=ca.toWords(t);return n.unshift(e),ca.encode(r,n)},us.fromOutputScript=function(t,e){e=e||sa.bitcoin;try{return ua.p2pkh({output:t,network:e}).address}catch(t){}try{return ua.p2sh({output:t,network:e}).address}catch(t){}try{return ua.p2wpkh({output:t,network:e}).address}catch(t){}try{return ua.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(aa.toASM(t)+" has no matching Address")},us.toOutputScript=function(t,e){let r,n;e=e||sa.bitcoin;try{r=pa(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return ua.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return ua.p2sh({hash:r.hash}).output}else{try{n=da(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return ua.p2wpkh({hash:n.data}).output;if(32===n.data.length)return ua.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ga={},ya=a.default.randomBytes;Object.defineProperty(ga,"__esModule",{value:!0});const va=as,ma=ds,wa=Ht.exports,ba=ya,Ea=Ho,_a=Go,Sa=Ea.maybe(Ea.compile({compressed:ma.maybe(ma.Boolean),network:ma.maybe(ma.Network)}));class Ia{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||va.bitcoin,void 0!==e&&(this.__Q=wa.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=wa.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return _a.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return wa.sign(t,this.__D);{let e=wa.sign(t,this.__D);const r=P.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=wa.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return wa.verify(t,this.publicKey,e)}}function Ta(t,e){if(Ea(ma.Buffer256bit,t),!wa.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return Ea(Sa,e),new Ia(t,void 0,e)}ga.fromPrivateKey=Ta,ga.fromPublicKey=function(t,e){return Ea(wa.isPoint,t),Ea(Sa,e),new Ia(void 0,t,e)},ga.fromWIF=function(t,e){const r=_a.decode(t),n=r.version;if(ma.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||va.bitcoin,n!==e.wif)throw new Error("Invalid network version");return Ta(r.privateKey,{compressed:r.compressed,network:e})},ga.makeRandom=function(t){Ea(Sa,t),void 0===t&&(t={});const e=t.rng||ba;let r;do{r=e(32),Ea(ma.Buffer256bit,r)}while(!wa.isPrivate(r));return Ta(r,t)};var Oa={},Aa={},Pa=vt.exports.Buffer;function Ma(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function ka(t){return Ma(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var xa={encode:function t(e,r,n){if(Ma(e),r||(r=Pa.allocUnsafe(ka(e))),!Pa.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Pa.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Ma(o),o},encodingLength:ka};Object.defineProperty(Aa,"__esModule",{value:!0});const Na=ds,Ra=Ho,Ca=xa;function Ua(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function La(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Ua(n+r,9007199254740991),n+r}function Da(t,e,r){return Ua(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}Aa.readUInt64LE=La,Aa.writeUInt64LE=Da,Aa.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};Aa.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Ra(Na.tuple(Na.Buffer,Na.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=La(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Ca.decode(this.buffer,this.offset);return this.offset+=Ca.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Va.encodingLength(this.ins.length)+Va.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Wa(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Wa(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Va.encodingLength(e)+t.reduce(((t,e)=>t+Wa(e)),0)}(e.witness)),0):0)}clone(){const t=new Qa;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Ka(Ga.tuple(Ga.UInt32,Ga.Buffer,Ga.Number),arguments),t>=this.ins.length)return Ya;const n=qa.compile(qa.decompile(e).filter((t=>t!==ja.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===Qa.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===Qa.SIGHASH_SINGLE){if(t>=this.outs.length)return Ya;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&Qa.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=$a})),i.ins[t].script=n);const o=P.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Fa.hash256(o)}hashForWitnessV0(t,e,r,n){Ka(Ga.tuple(Ga.UInt32,Ga.Buffer,Ga.Satoshi,Ga.UInt32),arguments);let i,o=P.from([]),s=Xa,u=Xa,a=Xa;if(n&Qa.SIGHASH_ANYONECANPAY||(o=P.allocUnsafe(36*this.ins.length),i=new Ha.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Fa.hash256(o)),n&Qa.SIGHASH_ANYONECANPAY||(31&n)===Qa.SIGHASH_SINGLE||(31&n)===Qa.SIGHASH_NONE||(o=P.allocUnsafe(4*this.ins.length),i=new Ha.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Fa.hash256(o)),(31&n)!==Qa.SIGHASH_SINGLE&&(31&n)!==Qa.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Wa(e.script)),0);o=P.allocUnsafe(t),i=new Ha.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Fa.hash256(o)}else if((31&n)===Qa.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}Qa.DEFAULT_SEQUENCE=4294967295,Qa.SIGHASH_ALL=1,Qa.SIGHASH_NONE=2,Qa.SIGHASH_SINGLE=3,Qa.SIGHASH_ANYONECANPAY=128,Qa.ADVANCED_TRANSACTION_MARKER=0,Qa.ADVANCED_TRANSACTION_FLAG=1,Ba.Transaction=Qa;Object.defineProperty(Oa,"__esModule",{value:!0});const th=Aa,eh=nu,rh=Ba,nh=ds,ih=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=rh.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=P.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(oh([{getHash:nh.Function}],t),0===t.length)throw uh;if(e&&!ch(t))throw ah;const r=t.map((t=>t.getHash(e))),n=ih(r,eh.hash256);return e?eh.hash256(P.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ch(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(P.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof P&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof P&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+sh.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return eh.hash256(this.toBuffer(!0))}getId(){return th.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=P.allocUnsafe(this.byteLength(t)),r=new th.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(sh.encode(this.transactions.length,e,r.offset),r.offset+=sh.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=th.reverseBuffer(this.getHash()),e=hh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw uh;const t=hh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw uh;if(!this.hasWitnessCommit())throw ah;const t=hh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ch(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}Oa.Block=hh;var fh={},lh={},ph={},dh={},gh={},yh={},vh={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(vh);var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const wh=vh;mh.decode=function(t){if(t.key[0]!==wh.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},mh.encode=function(t){const e=P.from([wh.GlobalTypes.GLOBAL_XPUB]),r=P.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=P.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},mh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",mh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return ft(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&ft(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},mh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const Eh=vh;bh.encode=function(t){return{key:P.from([Eh.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var _h={};Object.defineProperty(_h,"__esModule",{value:!0});const Sh=vh;_h.decode=function(t){if(t.key[0]!==Sh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},_h.encode=function(t){return{key:P.from([Sh.InputTypes.FINAL_SCRIPTSIG]),value:t}},_h.expected="Buffer",_h.check=function(t){return ft(t)},_h.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Th=vh;Ih.decode=function(t){if(t.key[0]!==Th.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},Ih.encode=function(t){return{key:P.from([Th.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},Ih.expected="Buffer",Ih.check=function(t){return ft(t)},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var Oh={};Object.defineProperty(Oh,"__esModule",{value:!0});const Ah=vh;Oh.decode=function(t){if(t.key[0]!==Ah.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},Oh.encode=function(t){return{key:P.from([Ah.InputTypes.NON_WITNESS_UTXO]),value:t}},Oh.expected="Buffer",Oh.check=function(t){return ft(t)},Oh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Ph={};Object.defineProperty(Ph,"__esModule",{value:!0});const Mh=vh;Ph.decode=function(t){if(t.key[0]!==Mh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Ph.encode=function(t){const e=P.from([Mh.InputTypes.PARTIAL_SIG]);return{key:P.concat([e,t.pubkey]),value:t.signature}},Ph.expected="{ pubkey: Buffer; signature: Buffer; }",Ph.check=function(t){return ft(t.pubkey)&&ft(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!ft(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Ph.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var kh={};Object.defineProperty(kh,"__esModule",{value:!0});const xh=vh;kh.decode=function(t){if(t.key[0]!==xh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},kh.encode=function(t){return{key:P.from([xh.InputTypes.POR_COMMITMENT]),value:P.from(t,"utf8")}},kh.expected="string",kh.check=function(t){return"string"==typeof t},kh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Nh={};Object.defineProperty(Nh,"__esModule",{value:!0});const Rh=vh;Nh.decode=function(t){if(t.key[0]!==Rh.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Nh.encode=function(t){const e=P.from([Rh.InputTypes.SIGHASH_TYPE]),r=P.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Nh.expected="number",Nh.check=function(t){return"number"==typeof t},Nh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ch={},Uh={},Lh={};Object.defineProperty(Lh,"__esModule",{value:!0});function Dh(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Bh(t){return Dh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}Lh.encode=function t(e,r,n){if(Dh(e),r||(r=P.allocUnsafe(Bh(e))),!ft(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},Lh.decode=function t(e,r){if(!ft(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Dh(i),i}},Lh.encodingLength=Bh,Object.defineProperty(Uh,"__esModule",{value:!0});const Hh=Lh;function Fh(t){const e=t.key.length,r=t.value.length,n=Hh.encodingLength(e),i=Hh.encodingLength(r),o=P.allocUnsafe(n+e+i+r);return Hh.encode(e,o,0),t.key.copy(o,n),Hh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function qh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Uh.range=t=>[...Array(t).keys()],Uh.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=P.from([t]),n=P.concat([r,e.pubkey]),i=e.path.split("/"),o=P.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return ft(t.pubkey)&&ft(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Wh={};Object.defineProperty(Wh,"__esModule",{value:!0}),Wh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var $h={};Object.defineProperty($h,"__esModule",{value:!0}),$h.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:P.from([t]),value:e}},check:function(t){return ft(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var zh={};Object.defineProperty(zh,"__esModule",{value:!0}),zh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:P.from([t]),value:e}},check:function(t){return ft(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(yh,"__esModule",{value:!0});const Xh=vh,Yh=_h,Jh=Ih,Zh=Oh,Qh=Ph,tc=kh,ec=Nh,rc=Ch,nc=Vh,ic=Wh,oc=$h,sc=zh,uc={unsignedTx:bh,globalXpub:mh,checkPubkey:ic.makeChecker([])};yh.globals=uc;const ac={nonWitnessUtxo:Zh,partialSig:Qh,sighashType:ec,finalScriptSig:Yh,finalScriptWitness:Jh,porCommitment:tc,witnessUtxo:rc,bip32Derivation:nc.makeConverter(Xh.InputTypes.BIP32_DERIVATION),redeemScript:oc.makeConverter(Xh.InputTypes.REDEEM_SCRIPT),witnessScript:sc.makeConverter(Xh.InputTypes.WITNESS_SCRIPT),checkPubkey:ic.makeChecker([Xh.InputTypes.PARTIAL_SIG,Xh.InputTypes.BIP32_DERIVATION])};yh.inputs=ac;const hc={bip32Derivation:nc.makeConverter(Xh.OutputTypes.BIP32_DERIVATION),redeemScript:oc.makeConverter(Xh.OutputTypes.REDEEM_SCRIPT),witnessScript:sc.makeConverter(Xh.OutputTypes.WITNESS_SCRIPT),checkPubkey:ic.makeChecker([Xh.OutputTypes.BIP32_DERIVATION])};yh.outputs=hc,Object.defineProperty(gh,"__esModule",{value:!0});const cc=yh,fc=Uh,lc=Lh,pc=vh;function dc(t,e,r){if(!e.equals(P.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function gc(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case pc.GlobalTypes.UNSIGNED_TX:if(dc("global",t.key,pc.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case pc.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(cc.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of fc.range(s)){const e={};for(const n of r[t])switch(cc.inputs.checkPubkey(n),n.key[0]){case pc.InputTypes.NON_WITNESS_UTXO:if(dc("input",n.key,pc.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=cc.inputs.nonWitnessUtxo.decode(n);break;case pc.InputTypes.WITNESS_UTXO:if(dc("input",n.key,pc.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=cc.inputs.witnessUtxo.decode(n);break;case pc.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(cc.inputs.partialSig.decode(n));break;case pc.InputTypes.SIGHASH_TYPE:if(dc("input",n.key,pc.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=cc.inputs.sighashType.decode(n);break;case pc.InputTypes.REDEEM_SCRIPT:if(dc("input",n.key,pc.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=cc.inputs.redeemScript.decode(n);break;case pc.InputTypes.WITNESS_SCRIPT:if(dc("input",n.key,pc.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=cc.inputs.witnessScript.decode(n);break;case pc.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(cc.inputs.bip32Derivation.decode(n));break;case pc.InputTypes.FINAL_SCRIPTSIG:dc("input",n.key,pc.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=cc.inputs.finalScriptSig.decode(n);break;case pc.InputTypes.FINAL_SCRIPTWITNESS:dc("input",n.key,pc.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=cc.inputs.finalScriptWitness.decode(n);break;case pc.InputTypes.POR_COMMITMENT:dc("input",n.key,pc.InputTypes.POR_COMMITMENT),e.porCommitment=cc.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of fc.range(u)){const e={};for(const r of n[t])switch(cc.outputs.checkPubkey(r),r.key[0]){case pc.OutputTypes.REDEEM_SCRIPT:if(dc("output",r.key,pc.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=cc.outputs.redeemScript.decode(r);break;case pc.OutputTypes.WITNESS_SCRIPT:if(dc("output",r.key,pc.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=cc.outputs.witnessScript.decode(r);break;case pc.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(cc.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}gh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=lc.decode(t,r);r+=lc.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===pc.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:c,outputCount:f}=h.getInputOutputCounts(),l=[],p=[];for(const t of fc.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of fc.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return gc(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},gh.checkKeyBuffer=dc,gh.psbtFromKeyVals=gc;var yc={};Object.defineProperty(yc,"__esModule",{value:!0});const vc=yh,mc=Uh;yc.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=Ec({globalMap:t,inputs:e,outputs:r}),s=mc.keyValsToBuffer(n),u=t=>0===t.length?[P.from([0])]:t.map(mc.keyValsToBuffer),a=u(i),h=u(o),c=P.allocUnsafe(5);return c.writeUIntBE(482972169471,0,5),P.concat([c,s].concat(a,h))};const wc=(t,e)=>t.key.compare(e.key);function bc(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(wc)}function Ec({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:bc(t,vc.globals),inputKeyVals:e.map((t=>bc(t,vc.inputs))),outputKeyVals:r.map((t=>bc(t,vc.outputs)))}}yc.psbtToKeyVals=Ec,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(gh),e(yc)}(dh),Object.defineProperty(ph,"__esModule",{value:!0});const _c=dh;function Sc(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function Ic(t){return t.globalMap.unsignedTx}function Tc(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}ph.combine=function(t){const e=t[0],r=_c.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=Ic(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=Tc(r.globalKeyVals),s=r.inputKeyVals.map(Tc),u=r.outputKeyVals.map(Tc);for(const t of n){const e=Ic(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=_c.psbtToKeyVals(t);Tc(n.globalKeyVals).forEach(Sc(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(Tc).forEach(((t,e)=>t.forEach(Sc(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(Tc).forEach(((t,e)=>t.forEach(Sc(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return _c.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var Oc={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=yh;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:c}=e[t+"s"][o]||{},f=!!a;if(h)if(f){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,c,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,c,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!ft(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!ft(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(Oc),Object.defineProperty(lh,"__esModule",{value:!0});const Ac=ph,Pc=dh,Mc=vh,kc=Oc;lh.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=P.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=P.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Pc.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Pc.psbtToBuffer(this)}updateGlobal(t){return kc.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=kc.checkForInput(this.inputs,t);return kc.updateInput(e,r),this}updateOutput(t,e){const r=kc.checkForOutput(this.outputs,t);return kc.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return kc.checkHasKey(t,this.globalMap.unknownKeyVals,kc.getEnumLength(Mc.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=kc.checkForInput(this.inputs,t);return kc.checkHasKey(e,r.unknownKeyVals,kc.getEnumLength(Mc.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=kc.checkForOutput(this.outputs,t);return kc.checkHasKey(e,r.unknownKeyVals,kc.getEnumLength(Mc.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),kc.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),kc.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=kc.checkForInput(this.inputs,t);kc.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=Ac.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(fh,"__esModule",{value:!0});const xc=lh,Nc=Lh,Rc=Oc,Cc=us,Uc=Aa,Lc=nu,Dc=ga,Bc=hs,Hc=fs,Fc=Ba,qc={network:as.bitcoin,maximumFeeRate:5e3};class jc{constructor(t={},e=new xc.Psbt(new Kc)){this.data=e,this.opts=Object.assign({},qc,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=P.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=P.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=xc.Psbt.fromBuffer(t,Gc),n=new jc(e,r);return function(t,e){t.ins.forEach((t=>{sf(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:Uc.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Cc.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:Uc.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=jc.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){rf(t),this.opts.maximumFeeRate=t}setVersion(t){rf(t),nf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){rf(t),nf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){rf(e),nf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");nf(this.data.inputs,"addInput"),t.witnessScript&&Sf(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);sf(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&vf(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");nf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Cc.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every($c))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return mf(this.data.inputs,r,e,!0),r}getFeeRate(){return cf("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return cf("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Rc.checkForInput(this.data.inputs,0),Of(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=ff){const r=Rc.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=wf(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||Zc(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Hc.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Rc.checkForInput(this.data.inputs,t),r=_f(bf(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Hc.decompile(t);if(!e)return;const r=e[e.length-1];if(!ft(r)||Ef(r)||(n=r,Hc.isCanonicalScriptSignature(n)))return;var n;if(!Hc.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=gf(t),r=e[e.length-1];if(Ef(r))return;if(!Hc.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+Tf(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=bf(r,e,n),{meaningfulScript:o}=_f(i,r,"input",e.redeemScript,e.witnessScript);return If(t,o)}(e,Rc.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Rc.checkForInput(this.data.inputs,t),n=ef(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=_f(i,r,"output",e.redeemScript,e.witnessScript);return If(t,o)}(e,Rc.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Rc.checkForOutput(this.data.outputs,t),n=ef(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Rc.checkForInput(this.data.inputs,0);return Of(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Hc.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?pf(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,of(e.pubkey,h,"verify");const c=Dc.fromPublicKey(e.pubkey);o.push(c.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Fc.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of Of(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of Of(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Fc.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return df(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=df(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Fc.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of Of(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Fc.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Fc.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=lf(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Hc.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Fc.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=lf(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Hc.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Vc(this.__CACHE),this.data.toBuffer()}toHex(){return Vc(this.__CACHE),this.data.toHex()}toBase64(){return Vc(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&Sf(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&vf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}fh.Psbt=jc;const Gc=t=>new Kc(t);class Kc{constructor(t=P.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Fc.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!ft(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?Uc.reverseBuffer(P.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!ft(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Vc(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function Wc(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Dc.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function $c(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function zc(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Xc=zc(Bc.p2ms),Yc=zc(Bc.p2pk),Jc=zc(Bc.p2pkh),Zc=zc(Bc.p2wpkh),Qc=zc(Bc.p2wsh),tf=zc(Bc.p2sh);function ef(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function rf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function nf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Hc.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Hc.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>ft(t)&&Hc.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Hc.signature.decode(t.signature),i=[];n&Fc.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Fc.Transaction.SIGHASH_ALL:break;case Fc.Transaction.SIGHASH_SINGLE:case Fc.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function of(t,e,r){if(!If(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function sf(t,e){const r=Uc.reverseBuffer(P.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function uf(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const af=uf(Bc.p2sh,"Redeem script"),hf=uf(Bc.p2wsh,"Witness script");function cf(t,e,r,n){if(!r.every($c))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),mf(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function ff(t,e,r,n,i,o){const s=Tf(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Wc(1,t.partialSig);case"multisig":const r=Bc.p2ms({output:e});return Wc(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return Bc.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=Bc.p2ms({output:t,signatures:e});break;case"pubkey":n=Bc.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=Bc.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=Bc.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?Bc.p2wsh({redeem:a}):null,c=i?Bc.p2sh({redeem:h||a}):null;n?(u=yf(h?h.witness:a.witness),c&&(s=c.input)):s=c?c.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function lf(t,e,r,n,i){const o=Rc.checkForInput(t,e),{hash:s,sighashType:u,script:a}=pf(e,o,n,!1,i);return of(r,a,"sign"),{hash:s,sighashType:u}}function pf(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Fc.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Fc.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Fc.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Fc.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Fc.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=wf(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:c}=_f(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(c)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if(Zc(h)){const e=Bc.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function df(t,e,r){const n=Rc.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function gf(t){let e=0;function r(){const r=Nc.decode(t,e);return e+=Nc.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=gf(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=wf(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function wf(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||vf(t,e,r),n[r]}function bf(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return wf(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function Ef(t){return 33===t.length&&Hc.isCanonicalPubKey(t)}function _f(t,e,r,n,i){const o=tf(t),s=o&&n&&Qc(n),u=Qc(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,af(e,t,n,r),hf(e,n,i,r),Sf(a)):u?(a=i,hf(e,t,i,r),Sf(a)):o?(a=n,af(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function Sf(t){if(Zc(t)||tf(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function If(t,e){const r=Lc.hash160(t),n=Hc.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function Tf(t){return Zc(t)?"witnesspubkeyhash":Jc(t)?"pubkeyhash":Xc(t)?"multisig":Yc(t)?"pubkey":"nonstandard"}function Of(t){return[...Array(t).keys()]}var Af={},Pf={},Mf={},kf={};Object.defineProperty(kf,"__esModule",{value:!0});const xf=fs,Nf=fs;function Rf(t){return t===Nf.OPS.OP_0||xf.isCanonicalScriptSignature(t)}function Cf(t,e){const r=xf.decompile(t);return!(r.length<2)&&(r[0]===Nf.OPS.OP_0&&(e?r.slice(1).every(Rf):r.slice(1).every(xf.isCanonicalScriptSignature)))}kf.check=Cf,Cf.toJSON=()=>"multisig input";var Uf={};Object.defineProperty(Uf,"__esModule",{value:!0});const Lf=fs,Df=fs,Bf=ds,Hf=Df.OPS.OP_RESERVED;function Ff(t,e){const r=Lf.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Df.OPS.OP_CHECKMULTISIG)return!1;if(!Bf.Number(r[0]))return!1;if(!Bf.Number(r[r.length-2]))return!1;const n=r[0]-Hf,i=r[r.length-2]-Hf;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(Lf.isCanonicalPubKey)}Uf.check=Ff,Ff.toJSON=()=>"multi-sig output",Object.defineProperty(Mf,"__esModule",{value:!0});const qf=kf;Mf.input=qf;const jf=Uf;Mf.output=jf;var Gf={};Object.defineProperty(Gf,"__esModule",{value:!0});const Kf=fs,Vf=Kf.OPS;function Wf(t){const e=Kf.compile(t);return e.length>1&&e[0]===Vf.OP_RETURN}Gf.check=Wf,Wf.toJSON=()=>"null data output";const $f={check:Wf};Gf.output=$f;var zf={},Xf={};Object.defineProperty(Xf,"__esModule",{value:!0});const Yf=fs;function Jf(t){const e=Yf.decompile(t);return 1===e.length&&Yf.isCanonicalScriptSignature(e[0])}Xf.check=Jf,Jf.toJSON=()=>"pubKey input";var Zf={};Object.defineProperty(Zf,"__esModule",{value:!0});const Qf=fs,tl=fs;function el(t){const e=Qf.decompile(t);return 2===e.length&&Qf.isCanonicalPubKey(e[0])&&e[1]===tl.OPS.OP_CHECKSIG}Zf.check=el,el.toJSON=()=>"pubKey output",Object.defineProperty(zf,"__esModule",{value:!0});const rl=Xf;zf.input=rl;const nl=Zf;zf.output=nl;var il={},ol={};Object.defineProperty(ol,"__esModule",{value:!0});const sl=fs;function ul(t){const e=sl.decompile(t);return 2===e.length&&sl.isCanonicalScriptSignature(e[0])&&sl.isCanonicalPubKey(e[1])}ol.check=ul,ul.toJSON=()=>"pubKeyHash input";var al={};Object.defineProperty(al,"__esModule",{value:!0});const hl=fs,cl=fs;function fl(t){const e=hl.compile(t);return 25===e.length&&e[0]===cl.OPS.OP_DUP&&e[1]===cl.OPS.OP_HASH160&&20===e[2]&&e[23]===cl.OPS.OP_EQUALVERIFY&&e[24]===cl.OPS.OP_CHECKSIG}al.check=fl,fl.toJSON=()=>"pubKeyHash output",Object.defineProperty(il,"__esModule",{value:!0});const ll=ol;il.input=ll;const pl=al;il.output=pl;var dl={},gl={},yl={};Object.defineProperty(yl,"__esModule",{value:!0});const vl=fs,ml=fs;function wl(t){const e=vl.compile(t);return 22===e.length&&e[0]===ml.OPS.OP_0&&20===e[1]}yl.check=wl,wl.toJSON=()=>"Witness pubKeyHash output";var bl={};Object.defineProperty(bl,"__esModule",{value:!0});const El=fs,_l=fs;function Sl(t){const e=El.compile(t);return 34===e.length&&e[0]===_l.OPS.OP_0&&32===e[1]}bl.check=Sl,Sl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(gl,"__esModule",{value:!0});const Il=fs,Tl=Mf,Ol=zf,Al=il,Pl=yl,Ml=bl;function kl(t,e){const r=Il.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!ft(n))return!1;const i=Il.decompile(Il.compile(r.slice(0,-1))),o=Il.decompile(n);return!!o&&(!!Il.isPushOnly(i)&&(1===r.length?Ml.check(o)||Pl.check(o):!(!Al.input.check(i)||!Al.output.check(o))||(!(!Tl.input.check(i,e)||!Tl.output.check(o))||!(!Ol.input.check(i)||!Ol.output.check(o)))))}gl.check=kl,kl.toJSON=()=>"scriptHash input";var xl={};Object.defineProperty(xl,"__esModule",{value:!0});const Nl=fs,Rl=fs;function Cl(t){const e=Nl.compile(t);return 23===e.length&&e[0]===Rl.OPS.OP_HASH160&&20===e[1]&&e[22]===Rl.OPS.OP_EQUAL}xl.check=Cl,Cl.toJSON=()=>"scriptHash output",Object.defineProperty(dl,"__esModule",{value:!0});const Ul=gl;dl.input=Ul;const Ll=xl;dl.output=Ll;var Dl={},Bl={};Object.defineProperty(Bl,"__esModule",{value:!0});const Hl=fs,Fl=fs,ql=ds,jl=Ho,Gl=P.from("aa21a9ed","hex");function Kl(t){const e=Hl.compile(t);return e.length>37&&e[0]===Fl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Gl)}Bl.check=Kl,Kl.toJSON=()=>"Witness commitment output",Bl.encode=function(t){jl(ql.Hash256bit,t);const e=P.allocUnsafe(36);return Gl.copy(e,0),t.copy(e,4),Hl.compile([Fl.OPS.OP_RETURN,e])},Bl.decode=function(t){return jl(Kl,t),Hl.decompile(t)[1].slice(4,36)},Object.defineProperty(Dl,"__esModule",{value:!0});const Vl=Bl;Dl.output=Vl;var Wl={},$l={};Object.defineProperty($l,"__esModule",{value:!0});const zl=fs;function Xl(t){const e=zl.decompile(t);return 2===e.length&&zl.isCanonicalScriptSignature(e[0])&&function(t){return zl.isCanonicalPubKey(t)&&33===t.length}(e[1])}$l.check=Xl,Xl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Wl,"__esModule",{value:!0});const Yl=$l;Wl.input=Yl;const Jl=yl;Wl.output=Jl;var Zl={},Ql={};Object.defineProperty(Ql,"__esModule",{value:!0});const tp=fs,ep=Ho,rp=Mf,np=zf,ip=il;function op(t,e){if(ep(ep.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!ft(r))return!1;const n=tp.decompile(r);if(!n||0===n.length)return!1;const i=tp.compile(t.slice(0,-1));return!(!ip.input.check(i)||!ip.output.check(n))||(!(!rp.input.check(i,e)||!rp.output.check(n))||!(!np.input.check(i)||!np.output.check(n)))}Ql.check=op,op.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Zl,"__esModule",{value:!0});const sp=Ql;Zl.input=sp;const up=bl;Zl.output=up,Object.defineProperty(Pf,"__esModule",{value:!0});const ap=fs,hp=Mf,cp=Gf,fp=zf,lp=il,pp=dl,dp=Dl,gp=Wl,yp=Zl,vp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Pf.types=vp,Pf.output=function(t){if(gp.output.check(t))return vp.P2WPKH;if(yp.output.check(t))return vp.P2WSH;if(lp.output.check(t))return vp.P2PKH;if(pp.output.check(t))return vp.P2SH;const e=ap.decompile(t);if(!e)throw new TypeError("Invalid script");return hp.output.check(e)?vp.P2MS:fp.output.check(e)?vp.P2PK:dp.output.check(e)?vp.WITNESS_COMMITMENT:cp.output.check(e)?vp.NULLDATA:vp.NONSTANDARD},Pf.input=function(t,e){const r=ap.decompile(t);if(!r)throw new TypeError("Invalid script");return lp.input.check(r)?vp.P2PKH:pp.input.check(r,e)?vp.P2SH:hp.input.check(r,e)?vp.P2MS:fp.input.check(r)?vp.P2PK:vp.NONSTANDARD},Pf.witness=function(t,e){const r=ap.decompile(t);if(!r)throw new TypeError("Invalid script");return gp.input.check(r)?vp.P2WPKH:yp.input.check(r,e)?vp.P2WSH:vp.NONSTANDARD},Object.defineProperty(Af,"__esModule",{value:!0});const mp=us,wp=Aa,bp=Pf,Ep=nu,_p=ga,Sp=as,Ip=hs,Tp=fs,Op=fs,Ap=Ba,Pp=ds,Mp=Ho,kp=bp.types,xp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Np(t,e,r){try{Mp(t,e)}catch(t){throw new Error(r)}}class Rp{constructor(t=Sp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new Ap.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Rp(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==kp.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=_p.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=Tp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Mp(Mp.maybe(Mp.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Mp(Pp.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Mp(Pp.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=wp.reverseBuffer(P.from(t,"hex"));else if(function(t){return t instanceof Ap.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=mp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=Tp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,c){let f;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),f=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!xp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Np(Mp.Number,e.vin,"sign must include vin parameter as Number (input index)"),Np(Pp.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Np(Mp.maybe(Mp.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires redeemScript`),Np(Mp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.Buffer,e.witnessScript,`${n} requires witnessScript`),Np(Mp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Np(Mp.Buffer,e.witnessScript,`${n} requires witnessScript`),Np(Mp.Buffer,e.redeemScript,`${n} requires witnessScript`),Np(Pp.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:f,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[f])throw new Error("No input at index: "+f);if(u=u||Ap.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[f];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Dp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Mp(Pp.Satoshi,a),l.value=a}if(!Dp(l)){const t=function(t,e,r,n){if(r&&n){const i=Ip.p2wsh({redeem:{output:n}}),o=Ip.p2wsh({output:r}),s=Ip.p2sh({redeem:{output:r}}),u=Ip.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Up(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+Tp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===kp.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:kp.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:kp.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=Ip.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=Ip.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Up(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+Tp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===kp.P2WPKH&&(o=Ip.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:kp.P2SH,prevOutScript:n.output,hasWitness:i.type===kp.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=Ip.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=Ip.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Up(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+Tp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===kp.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:kp.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===kp.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===kp.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Up(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+Tp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===kp.P2WPKH&&(n=Ip.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===kp.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=Ip.p2pkh({pubkey:e}).output;return{prevOutType:kp.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:kp.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Dp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(f,l.signScript,l.value,u):n.hashForSignature(f,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!c}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(Ap.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Cp(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Up(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||bp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=Lp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===kp.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Bp(t)&Ap.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===Ap.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Bp(t)&Ap.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Bp(r);return n===Ap.Transaction.SIGHASH_NONE||n===Ap.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Cp(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=bp.input(t,!0),i=bp.witness(e,!0);n===kp.NONSTANDARD&&(n=void 0),i===kp.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case kp.P2WPKH:{const{output:t,pubkey:r,signature:n}=Ip.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:kp.P2WPKH,pubkeys:[r],signatures:[n]}}case kp.P2PKH:{const{output:e,pubkey:r,signature:n}=Ip.p2pkh({input:t});return{prevOutScript:e,prevOutType:kp.P2PKH,pubkeys:[r],signatures:[n]}}case kp.P2PK:{const{signature:e}=Ip.p2pk({input:t});return{prevOutType:kp.P2PK,pubkeys:[void 0],signatures:[e]}}case kp.P2MS:{const{m:e,pubkeys:r,signatures:i}=Ip.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:kp.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===kp.P2SH){const{output:r,redeem:n}=Ip.p2sh({input:t,witness:e}),i=bp.output(n.output),o=Cp(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:kp.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===kp.P2WSH){const{output:r,redeem:n}=Ip.p2wsh({input:t,witness:e}),i=bp.output(n.output);let o;return o=i===kp.P2WPKH?Cp(n.input,n.witness,i):Cp(Tp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:kp.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:kp.NONSTANDARD,prevOutScript:t}}function Up(t,e){Mp(Pp.Buffer,t);const r=bp.output(t);switch(r){case kp.P2PKH:{if(!e)return{type:r};const n=Ip.p2pkh({output:t}).hash,i=Ep.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case kp.P2WPKH:{if(!e)return{type:r};const n=Ip.p2wpkh({output:t}).hash,i=Ep.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case kp.P2PK:return{type:r,pubkeys:[Ip.p2pk({output:t}).pubkey],signatures:[void 0]};case kp.P2MS:{const e=Ip.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function Lp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case kp.P2PKH:if(0===n.length)break;if(0===i.length)break;return Ip.p2pkh({pubkey:n[0],signature:i[0]});case kp.P2WPKH:if(0===n.length)break;if(0===i.length)break;return Ip.p2wpkh({pubkey:n[0],signature:i[0]});case kp.P2PK:if(0===n.length)break;if(0===i.length)break;return Ip.p2pk({signature:i[0]});case kp.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||Op.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return Ip.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case kp.P2SH:{const t=Lp(e.redeemScriptType,e,r);if(!t)return;return Ip.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case kp.P2WSH:{const t=Lp(e.witnessScriptType,e,r);if(!t)return;return Ip.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Dp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Bp(t){return t.readUInt8(t.length-1)}Af.TransactionBuilder=Rp,Object.defineProperty(Nt,"__esModule",{value:!0});const Hp=Rt;Nt.bip32=Hp;const Fp=us;Nt.address=Fp;const qp=nu;var jp=Nt.crypto=qp;const Gp=ga;Nt.ECPair=Gp;const Kp=as;Nt.networks=Kp;const Vp=hs;Nt.payments=Vp;const Wp=fs;Nt.script=Wp;var $p=Oa;Nt.Block=$p.Block;var zp=fh;Nt.Psbt=zp.Psbt;var Xp=fs;Nt.opcodes=Xp.OPS;var Yp=Ba;Nt.Transaction=Yp.Transaction;var Jp=Af;Nt.TransactionBuilder=Jp.TransactionBuilder;var Zp={exports:{}};var Qp={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};function td(){throw new Error("setTimeout has not been defined")}function ed(){throw new Error("clearTimeout has not been defined")}var rd=td,nd=ed;function id(t){if(rd===setTimeout)return setTimeout(t,0);if((rd===td||!rd)&&setTimeout)return rd=setTimeout,setTimeout(t,0);try{return rd(t,0)}catch(e){try{return rd.call(null,t,0)}catch(e){return rd.call(this,t,0)}}}"function"==typeof d.setTimeout&&(rd=setTimeout),"function"==typeof d.clearTimeout&&(nd=clearTimeout);var od,sd=[],ud=!1,ad=-1;function hd(){ud&&od&&(ud=!1,od.length?sd=od.concat(sd):ad=-1,sd.length&&cd())}function cd(){if(!ud){var t=id(hd);ud=!0;for(var e=sd.length;e;){for(od=sd,sd=[];++ad1)for(var r=1;rconsole.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=Qp,n=Td,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Zp,Zp.exports);const Od=["includePrerelease","loose","rtl"];var Ad=t=>t?"object"!=typeof t?{loose:!0}:Od.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Pd=/^[0-9]+$/,Md=(t,e)=>{const r=Pd.test(t),n=Pd.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tMd(e,t)};const xd=Td,{MAX_LENGTH:Nd,MAX_SAFE_INTEGER:Rd}=Qp,{re:Cd,t:Ud}=Zp.exports,Ld=Ad,{compareIdentifiers:Dd}=kd;class Bd{constructor(t,e){if(e=Ld(e),t instanceof Bd){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>Nd)throw new TypeError(`version is longer than ${Nd} characters`);xd("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?Cd[Ud.LOOSE]:Cd[Ud.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Rd||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rd||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rd||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var Hd=Bd;const{MAX_LENGTH:Fd}=Qp,{re:qd,t:jd}=Zp.exports,Gd=Hd,Kd=Ad;var Vd=(t,e)=>{if(e=Kd(e),t instanceof Gd)return t;if("string"!=typeof t)return null;if(t.length>Fd)return null;if(!(e.loose?qd[jd.LOOSE]:qd[jd.FULL]).test(t))return null;try{return new Gd(t,e)}catch(t){return null}};const Wd=Vd;var $d=(t,e)=>{const r=Wd(t,e);return r?r.version:null};const zd=Vd;var Xd=(t,e)=>{const r=zd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const Yd=Hd;var Jd=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new Yd(t,r).inc(e,n).version}catch(t){return null}};const Zd=Hd;var Qd=(t,e,r)=>new Zd(t,r).compare(new Zd(e,r));const tg=Qd;var eg=(t,e,r)=>0===tg(t,e,r);const rg=Vd,ng=eg;var ig=(t,e)=>{if(ng(t,e))return null;{const r=rg(t),n=rg(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const og=Hd;var sg=(t,e)=>new og(t,e).major;const ug=Hd;var ag=(t,e)=>new ug(t,e).minor;const hg=Hd;var cg=(t,e)=>new hg(t,e).patch;const fg=Vd;var lg=(t,e)=>{const r=fg(t,e);return r&&r.prerelease.length?r.prerelease:null};const pg=Qd;var dg=(t,e,r)=>pg(e,t,r);const gg=Qd;var yg=(t,e)=>gg(t,e,!0);const vg=Hd;var mg=(t,e,r)=>{const n=new vg(t,r),i=new vg(e,r);return n.compare(i)||n.compareBuild(i)};const wg=mg;var bg=(t,e)=>t.sort(((t,r)=>wg(t,r,e)));const Eg=mg;var _g=(t,e)=>t.sort(((t,r)=>Eg(r,t,e)));const Sg=Qd;var Ig=(t,e,r)=>Sg(t,e,r)>0;const Tg=Qd;var Og=(t,e,r)=>Tg(t,e,r)<0;const Ag=Qd;var Pg=(t,e,r)=>0!==Ag(t,e,r);const Mg=Qd;var kg=(t,e,r)=>Mg(t,e,r)>=0;const xg=Qd;var Ng=(t,e,r)=>xg(t,e,r)<=0;const Rg=eg,Cg=Pg,Ug=Ig,Lg=kg,Dg=Og,Bg=Ng;var Hg=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return Rg(t,r,n);case"!=":return Cg(t,r,n);case">":return Ug(t,r,n);case">=":return Lg(t,r,n);case"<":return Dg(t,r,n);case"<=":return Bg(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const Fg=Hd,qg=Vd,{re:jg,t:Gg}=Zp.exports;var Kg=(t,e)=>{if(t instanceof Fg)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=jg[Gg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),jg[Gg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;jg[Gg.COERCERTL].lastIndex=-1}else r=t.match(jg[Gg.COERCE]);return null===r?null:qg(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},Vg=Wg;function Wg(t){var e=this;if(e instanceof Wg||(e=new Wg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},Wg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},Wg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},Wg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},Wg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new Wg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},Wg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const hy=(t,e,r)=>{const n=t[sy].get(e);if(n){const e=n.value;if(cy(t,e)){if(ly(t,n),!t[ey])return}else r&&(t[uy]&&(n.value.now=Date.now()),t[oy].unshiftNode(n));return e.value}},cy=(t,e)=>{if(!e||!e.maxAge&&!t[ry])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[ry]&&r>t[ry]},fy=t=>{if(t[Qg]>t[Zg])for(let e=t[oy].tail;t[Qg]>t[Zg]&&null!==e;){const r=e.prev;ly(t,e),e=r}},ly=(t,e)=>{if(e){const r=e.value;t[ny]&&t[ny](r.key,r.value),t[Qg]-=r.length,t[sy].delete(r.key),t[oy].removeNode(e)}};class py{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const dy=(t,e,r,n)=>{let i=r.value;cy(t,i)&&(ly(t,r),t[ey]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var gy=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[Zg]=t.max||1/0;const e=t.length||ay;if(this[ty]="function"!=typeof e?ay:e,this[ey]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[ry]=t.maxAge||0,this[ny]=t.dispose,this[iy]=t.noDisposeOnSet||!1,this[uy]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[Zg]=t||1/0,fy(this)}get max(){return this[Zg]}set allowStale(t){this[ey]=!!t}get allowStale(){return this[ey]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[ry]=t,fy(this)}get maxAge(){return this[ry]}set lengthCalculator(t){"function"!=typeof t&&(t=ay),t!==this[ty]&&(this[ty]=t,this[Qg]=0,this[oy].forEach((t=>{t.length=this[ty](t.value,t.key),this[Qg]+=t.length}))),fy(this)}get lengthCalculator(){return this[ty]}get length(){return this[Qg]}get itemCount(){return this[oy].length}rforEach(t,e){e=e||this;for(let r=this[oy].tail;null!==r;){const n=r.prev;dy(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[oy].head;null!==r;){const n=r.next;dy(this,t,r,e),r=n}}keys(){return this[oy].toArray().map((t=>t.key))}values(){return this[oy].toArray().map((t=>t.value))}reset(){this[ny]&&this[oy]&&this[oy].length&&this[oy].forEach((t=>this[ny](t.key,t.value))),this[sy]=new Map,this[oy]=new Jg,this[Qg]=0}dump(){return this[oy].map((t=>!cy(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[oy]}set(t,e,r){if((r=r||this[ry])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[ty](e,t);if(this[sy].has(t)){if(i>this[Zg])return ly(this,this[sy].get(t)),!1;const o=this[sy].get(t).value;return this[ny]&&(this[iy]||this[ny](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Qg]+=i-o.length,o.length=i,this.get(t),fy(this),!0}const o=new py(t,e,i,n,r);return o.length>this[Zg]?(this[ny]&&this[ny](t,e),!1):(this[Qg]+=o.length,this[oy].unshift(o),this[sy].set(t,this[oy].head),fy(this),!0)}has(t){if(!this[sy].has(t))return!1;const e=this[sy].get(t).value;return!cy(this,e)}get(t){return hy(this,t,!0)}peek(t){return hy(this,t,!1)}pop(){const t=this[oy].tail;return t?(ly(this,t),t.value):null}del(t){ly(this,this[sy].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[sy].forEach(((t,e)=>hy(this,e,!1)))}};class yy{constructor(t,e){if(e=wy(e),t instanceof yy)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new yy(t.raw,e);if(t instanceof by)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Py(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&My(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=my.get(e);if(r)return r;const n=this.options.loose,i=n?Sy[Iy.HYPHENRANGELOOSE]:Sy[Iy.HYPHENRANGE];t=t.replace(i,qy(this.options.includePrerelease)),Ey("hyphen replace",t),t=t.replace(Sy[Iy.COMPARATORTRIM],Ty),Ey("comparator trim",t,Sy[Iy.COMPARATORTRIM]),t=(t=(t=t.replace(Sy[Iy.TILDETRIM],Oy)).replace(Sy[Iy.CARETTRIM],Ay)).split(/\s+/).join(" ");const o=n?Sy[Iy.COMPARATORLOOSE]:Sy[Iy.COMPARATOR],s=t.split(" ").map((t=>xy(t,this.options))).join(" ").split(/\s+/).map((t=>Fy(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new by(t,this.options)));s.length;const u=new Map;for(const t of s){if(Py(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return my.set(e,a),a}intersects(t,e){if(!(t instanceof yy))throw new TypeError("a Range is required");return this.set.some((r=>ky(r,e)&&t.set.some((t=>ky(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new _y(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,My=t=>""===t.value,ky=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},xy=(t,e)=>(Ey("comp",t,e),t=Uy(t,e),Ey("caret",t),t=Ry(t,e),Ey("tildes",t),t=Dy(t,e),Ey("xrange",t),t=Hy(t,e),Ey("stars",t),t),Ny=t=>!t||"x"===t.toLowerCase()||"*"===t,Ry=(t,e)=>t.trim().split(/\s+/).map((t=>Cy(t,e))).join(" "),Cy=(t,e)=>{const r=e.loose?Sy[Iy.TILDELOOSE]:Sy[Iy.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Ey("tilde",t,e,r,n,i,o),Ny(r)?s="":Ny(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:Ny(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Ey("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Ey("tilde return",s),s}))},Uy=(t,e)=>t.trim().split(/\s+/).map((t=>Ly(t,e))).join(" "),Ly=(t,e)=>{Ey("caret",t,e);const r=e.loose?Sy[Iy.CARETLOOSE]:Sy[Iy.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Ey("caret",t,e,r,i,o,s),Ny(r)?u="":Ny(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:Ny(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Ey("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Ey("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Ey("caret return",u),u}))},Dy=(t,e)=>(Ey("replaceXRanges",t,e),t.split(/\s+/).map((t=>By(t,e))).join(" ")),By=(t,e)=>{t=t.trim();const r=e.loose?Sy[Iy.XRANGELOOSE]:Sy[Iy.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Ey("xRange",t,r,n,i,o,s,u);const a=Ny(i),h=a||Ny(o),c=h||Ny(s),f=c;return"="===n&&f&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&f?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:c&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Ey("xRange return",r),r}))},Hy=(t,e)=>(Ey("replaceStars",t,e),t.trim().replace(Sy[Iy.STAR],"")),Fy=(t,e)=>(Ey("replaceGTE0",t,e),t.trim().replace(Sy[e.includePrerelease?Iy.GTE0PRE:Iy.GTE0],"")),qy=t=>(e,r,n,i,o,s,u,a,h,c,f,l,p)=>`${r=Ny(n)?"":Ny(i)?`>=${n}.0.0${t?"-0":""}`:Ny(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=Ny(h)?"":Ny(c)?`<${+h+1}.0.0-0`:Ny(f)?`<${h}.${+c+1}.0-0`:l?`<=${h}.${c}.${f}-${l}`:t?`<${h}.${c}.${+f+1}-0`:`<=${a}`}`.trim(),jy=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},Gy=Symbol("SemVer ANY");class Ky{static get ANY(){return Gy}constructor(t,e){if(e=Wy(e),t instanceof Ky){if(t.loose===!!e.loose)return t;t=t.value}Yy("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===Gy?this.value="":this.value=this.operator+this.semver.version,Yy("comp",this)}parse(t){const e=this.options.loose?$y[zy.COMPARATORLOOSE]:$y[zy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new Jy(r[2],this.options.loose):this.semver=Gy}toString(){return this.value}test(t){if(Yy("Comparator.test",t,this.options.loose),this.semver===Gy||t===Gy)return!0;if("string"==typeof t)try{t=new Jy(t,this.options)}catch(t){return!1}return Xy(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof Ky))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new Zy(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new Zy(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=Xy(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=Xy(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var Vy=Ky;const Wy=Ad,{re:$y,t:zy}=Zp.exports,Xy=Hg,Yy=Td,Jy=Hd,Zy=vy,Qy=vy;var tv=(t,e,r)=>{try{e=new Qy(e,r)}catch(t){return!1}return e.test(t)};const ev=vy;var rv=(t,e)=>new ev(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const nv=Hd,iv=vy;var ov=(t,e,r)=>{let n=null,i=null,o=null;try{o=new iv(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new nv(n,r)))})),n};const sv=Hd,uv=vy;var av=(t,e,r)=>{let n=null,i=null,o=null;try{o=new uv(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new sv(n,r)))})),n};const hv=Hd,cv=vy,fv=Ig;var lv=(t,e)=>{t=new cv(t,e);let r=new hv("0.0.0");if(t.test(r))return r;if(r=new hv("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new hv(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!fv(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!fv(r,i)||(r=i)}return r&&t.test(r)?r:null};const pv=vy;var dv=(t,e)=>{try{return new pv(t,e).range||"*"}catch(t){return null}};const gv=Hd,yv=Vy,{ANY:vv}=yv,mv=vy,wv=tv,bv=Ig,Ev=Og,_v=Ng,Sv=kg;var Iv=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new gv(t,n),e=new mv(e,n),r){case">":i=bv,o=_v,s=Ev,u=">",a=">=";break;case"<":i=Ev,o=Sv,s=bv,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(wv(t,e,n))return!1;for(let r=0;r{t.semver===vv&&(t=new yv(">=0.0.0")),c=c||t,f=f||t,i(t.semver,c.semver,n)?c=t:s(t.semver,f.semver,n)&&(f=t)})),c.operator===u||c.operator===a)return!1;if((!f.operator||f.operator===u)&&o(t,f.semver))return!1;if(f.operator===a&&s(t,f.semver))return!1}return!0};const Tv=Iv;var Ov=(t,e,r)=>Tv(t,e,">",r);const Av=Iv;var Pv=(t,e,r)=>Av(t,e,"<",r);const Mv=vy;var kv=(t,e,r)=>(t=new Mv(t,r),e=new Mv(e,r),t.intersects(e));const xv=tv,Nv=Qd;const Rv=vy,Cv=Vy,{ANY:Uv}=Cv,Lv=tv,Dv=Qd,Bv=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===Uv){if(1===e.length&&e[0].semver===Uv)return!0;t=r.includePrerelease?[new Cv(">=0.0.0-0")]:[new Cv(">=0.0.0")]}if(1===e.length&&e[0].semver===Uv){if(r.includePrerelease)return!0;e=[new Cv(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,c;for(const e of t)">"===e.operator||">="===e.operator?i=Hv(i,e,r):"<"===e.operator||"<="===e.operator?o=Fv(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=Dv(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!Lv(t,String(i),r))return null;if(o&&!Lv(t,String(o),r))return null;for(const n of e)if(!Lv(t,String(n),r))return!1;return!0}let f=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;f&&1===f.prerelease.length&&"<"===o.operator&&0===f.prerelease[0]&&(f=!1);for(const t of e){if(c=c||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=Hv(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!Lv(i.semver,String(t),r))return!1;if(o)if(f&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===f.major&&t.semver.minor===f.minor&&t.semver.patch===f.patch&&(f=!1),"<"===t.operator||"<="===t.operator){if(a=Fv(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!Lv(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&c&&!i&&0!==s)&&(!l&&!f))},Hv=(t,e,r)=>{if(!t)return e;const n=Dv(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},Fv=(t,e,r)=>{if(!t)return e;const n=Dv(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var qv=(t,e,r={})=>{if(t===e)return!0;t=new Rv(t,r),e=new Rv(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=Bv(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const jv=Zp.exports;var Gv={re:jv.re,src:jv.src,tokens:jv.t,SEMVER_SPEC_VERSION:Qp.SEMVER_SPEC_VERSION,SemVer:Hd,compareIdentifiers:kd.compareIdentifiers,rcompareIdentifiers:kd.rcompareIdentifiers,parse:Vd,valid:$d,clean:Xd,inc:Jd,diff:ig,major:sg,minor:ag,patch:cg,prerelease:lg,compare:Qd,rcompare:dg,compareLoose:yg,compareBuild:mg,sort:bg,rsort:_g,gt:Ig,lt:Og,eq:eg,neq:Pg,gte:kg,lte:Ng,cmp:Hg,coerce:Kg,Comparator:Vy,Range:vy,satisfies:tv,toComparators:rv,maxSatisfying:ov,minSatisfying:av,minVersion:lv,validRange:dv,outside:Iv,gtr:Ov,ltr:Pv,intersects:kv,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>Nv(t,e,r)));for(const t of s){xv(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Qv.alloc(0);for(var e=Qv.allocUnsafe(t>>>0),r=this.head,n=0;r;)rm(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Qv.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:em,value:function(t,e){return tm(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}cm("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),cm("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${fm(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${fm(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),cm("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),cm("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),cm("ERR_STREAM_PREMATURE_CLOSE","Premature close"),cm("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),cm("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),cm("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),cm("ERR_STREAM_WRITE_AFTER_END","write after end"),cm("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),cm("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),cm("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),am.codes=hm;var lm=am.codes.ERR_INVALID_OPT_VALUE;var pm,dm={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new lm(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},gm=l.default.deprecate,ym=Dm;function vm(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}Dm.WritableState=Lm;var mm={deprecate:gm},wm=Xv,bm=h.default.Buffer,Em=p.Uint8Array||function(){};var _m,Sm=um,Im=dm.getHighWaterMark,Tm=am.codes,Om=Tm.ERR_INVALID_ARG_TYPE,Am=Tm.ERR_METHOD_NOT_IMPLEMENTED,Pm=Tm.ERR_MULTIPLE_CALLBACK,Mm=Tm.ERR_STREAM_CANNOT_PIPE,km=Tm.ERR_STREAM_DESTROYED,xm=Tm.ERR_STREAM_NULL_VALUES,Nm=Tm.ERR_STREAM_WRITE_AFTER_END,Rm=Tm.ERR_UNKNOWN_ENCODING,Cm=Sm.errorOrDestroy;function Um(){}function Lm(t,e,r){pm=pm||Vm,t=t||{},"boolean"!=typeof r&&(r=e instanceof pm),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=Im(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new Pm;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(fd(i,n),fd(Gm,t,e),t._writableState.errorEmitted=!0,Cm(t,n)):(i(n),t._writableState.errorEmitted=!0,Cm(t,n),Gm(t,e))}(t,r,n,e,i);else{var o=qm(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||Fm(t,r),n?fd(Hm,t,r,o,i):Hm(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new vm(this)}function Dm(t){var e=this instanceof(pm=pm||Vm);if(!e&&!_m.call(Dm,this))return new Dm(t);this._writableState=new Lm(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),wm.call(this)}function Bm(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new km("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function Hm(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),Gm(t,e)}function Fm(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,Bm(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new vm(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,c=r.callback;if(Bm(t,e,!1,e.objectMode?1:a.length,a,h,c),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function qm(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function jm(t,e){t._final((function(r){e.pendingcb--,r&&Cm(t,r),e.prefinished=!0,t.emit("prefinish"),Gm(t,e)}))}function Gm(t,e){var r=qm(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,fd(jm,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}se.exports(Dm,wm),Lm.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(Lm.prototype,"buffer",{get:mm.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_m=Function.prototype[Symbol.hasInstance],Object.defineProperty(Dm,Symbol.hasInstance,{value:function(t){return!!_m.call(this,t)||this===Dm&&(t&&t._writableState instanceof Lm)}})):_m=function(t){return t instanceof this},Dm.prototype.pipe=function(){Cm(this,new Mm)},Dm.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,bm.isBuffer(n)||n instanceof Em);return s&&!bm.isBuffer(t)&&(t=function(t){return bm.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=Um),i.ending?function(t,e){var r=new Nm;Cm(t,r),fd(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new xm:"string"==typeof r||e.objectMode||(i=new Om("chunk",["string","Buffer"],r)),!i||(Cm(t,i),fd(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=bm.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new Rm(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(Dm.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Dm.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Dm.prototype._write=function(t,e,r){r(new Am("_write()"))},Dm.prototype._writev=null,Dm.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,Gm(t,e),r&&(e.finished?fd(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(Dm.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Dm.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),Dm.prototype.destroy=Sm.destroy,Dm.prototype._undestroy=Sm.undestroy,Dm.prototype._destroy=function(t,e){e(t)};var Km=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},Vm=Jm,Wm=Bw,$m=ym;se.exports(Jm,Wm);for(var zm=Km($m.prototype),Xm=0;Xm>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function ow(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function sw(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function uw(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function aw(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function hw(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function cw(t){return t.toString(this.encoding)}function fw(t){return t&&t.length?this.write(t):""}tw.StringDecoder=nw,nw.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},nw.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var lw=am.codes.ERR_STREAM_PREMATURE_CLOSE;function pw(){}var dw,gw=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===qw.prototype||(e=function(t){return qw.from(t)}(e)),n)s.endEmitted?rb(t,new eb):ub(t,s,e,!0);else if(s.ended)rb(t,new Qw);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?ub(t,s,e,!1):lb(t,s)):ub(t,s,e,!1)}else n||(s.reading=!1,lb(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=ab?t=ab:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function cb(t){var e=t._readableState;Gw("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Gw("emitReadable",e.flowing),e.emittedReadable=!0,fd(fb,t))}function fb(t){var e=t._readableState;Gw("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,vb(t)}function lb(t,e){e.readingMore||(e.readingMore=!0,fd(pb,t,e))}function pb(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function gb(t){Gw("readable nexttick read 0"),t.read(0)}function yb(t,e){Gw("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),vb(t),e.flowing&&!e.reading&&t.read(0)}function vb(t){var e=t._readableState;for(Gw("flow",e.flowing);e.flowing&&null!==t.read(););}function mb(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function wb(t){var e=t._readableState;Gw("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,fd(bb,e,t))}function bb(t,e){if(Gw("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function Eb(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return Gw("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?wb(this):cb(this),null;if(0===(t=hb(t,e))&&e.ended)return 0===e.length&&wb(this),null;var n,i=e.needReadable;return Gw("need readable",i),(0===e.length||e.length-t0?mb(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&wb(this)),null!==n&&this.emit("data",n),n},ob.prototype._read=function(t){rb(this,new tb("_read()"))},ob.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Gw("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==Id.stdout&&t!==Id.stderr?s:p;function o(e,i){Gw("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,Gw("cleanup"),t.removeListener("close",f),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",c),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){Gw("onend"),t.end()}n.endEmitted?fd(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Gw("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&Hw(t,"data")&&(e.flowing=!0,vb(t))}}(r);t.on("drain",u);var a=!1;function h(e){Gw("ondata");var i=t.write(e);Gw("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Eb(n.pipes,t))&&!a&&(Gw("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function c(e){Gw("onerror",e),p(),t.removeListener("error",c),0===Hw(t,"error")&&rb(t,e)}function f(){t.removeListener("finish",l),p()}function l(){Gw("onfinish"),t.removeListener("close",f),p()}function p(){Gw("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",c),t.once("close",f),t.once("finish",l),t.emit("pipe",r),n.flowing||(Gw("pipe resume"),r.resume()),t},ob.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Gw("on readable",n.length,n.reading),n.length?cb(this):n.reading||fd(gb,this))),r},ob.prototype.addListener=ob.prototype.on,ob.prototype.removeListener=function(t,e){var r=Fw.prototype.removeListener.call(this,t,e);return"readable"===t&&fd(db,this),r},ob.prototype.removeAllListeners=function(t){var e=Fw.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||fd(db,this),e},ob.prototype.resume=function(){var t=this._readableState;return t.flowing||(Gw("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,fd(yb,t,e))}(this,t)),t.paused=!1,this},ob.prototype.pause=function(){return Gw("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Gw("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},ob.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(Gw("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(Gw("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(jb),s||(o.forEach(jb),i(n))}))}));return e.reduce(Gb)};!function(t,e){var r=c.default;(e=t.exports=Bw).Stream=r||e,e.Readable=e,e.Writable=ym,e.Duplex=Vm,e.Transform=_b,e.PassThrough=Cb,e.finished=gw,e.pipeline=Vb}(zv,zv.exports);var Wb=vt.exports.Buffer,$b=zv.exports.Transform;function zb(t){$b.call(this),this._block=Wb.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,se.exports)(zb,$b),zb.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},zb.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},zb.prototype.update=function(t,e){if(function(t,e){if(!Wb.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");Wb.isBuffer(t)||(t=Wb.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},zb.prototype._update=function(){throw new Error("_update is not implemented")},zb.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},zb.prototype._digest=function(){throw new Error("_digest is not implemented")};var Xb=zb,Yb=h.default.Buffer,Jb=se.exports,Zb=Xb,Qb=new Array(16),tE=[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],eE=[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],rE=[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],nE=[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],iE=[0,1518500249,1859775393,2400959708,2840853838],oE=[1352829926,1548603684,1836072691,2053994217,0];function sE(){Zb.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function uE(t,e){return t<>>32-e}function aE(t,e,r,n,i,o,s,u){return uE(t+(e^r^n)+o+s|0,u)+i|0}function hE(t,e,r,n,i,o,s,u){return uE(t+(e&r|~e&n)+o+s|0,u)+i|0}function cE(t,e,r,n,i,o,s,u){return uE(t+((e|~r)^n)+o+s|0,u)+i|0}function fE(t,e,r,n,i,o,s,u){return uE(t+(e&n|r&~n)+o+s|0,u)+i|0}function lE(t,e,r,n,i,o,s,u){return uE(t+(e^(r|~n))+o+s|0,u)+i|0}Jb(sE,Zb),sE.prototype._update=function(){for(var t=Qb,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,c=0|this._d,f=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=aE(r,n,i,o,s,t[tE[l]],iE[0],rE[l]),d=lE(u,a,h,c,f,t[eE[l]],oE[0],nE[l])):l<32?(p=hE(r,n,i,o,s,t[tE[l]],iE[1],rE[l]),d=fE(u,a,h,c,f,t[eE[l]],oE[1],nE[l])):l<48?(p=cE(r,n,i,o,s,t[tE[l]],iE[2],rE[l]),d=cE(u,a,h,c,f,t[eE[l]],oE[2],nE[l])):l<64?(p=fE(r,n,i,o,s,t[tE[l]],iE[3],rE[l]),d=hE(u,a,h,c,f,t[eE[l]],oE[3],nE[l])):(p=lE(r,n,i,o,s,t[tE[l]],iE[4],rE[l]),d=aE(u,a,h,c,f,t[eE[l]],oE[4],nE[l])),r=s,s=o,o=uE(i,10),i=n,n=p,u=f,f=c,c=uE(h,10),h=a,a=d}var g=this._b+i+c|0;this._b=this._c+o+f|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},sE.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=Yb.alloc?Yb.alloc(20):new Yb(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var pE=sE,dE={exports:{}},gE=vt.exports.Buffer;function yE(t,e){this._block=gE.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}yE.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=gE.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},yE.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var vE=yE,mE=se.exports,wE=vE,bE=vt.exports.Buffer,EE=[1518500249,1859775393,-1894007588,-899497514],_E=new Array(80);function SE(){this.init(),this._w=_E,wE.call(this,64,56)}function IE(t){return t<<30|t>>>2}function TE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}mE(SE,wE),SE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},SE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var c=~~(h/20),f=0|((e=n)<<5|e>>>27)+TE(c,i,o,s)+u+r[h]+EE[c];u=s,s=o,o=IE(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},SE.prototype._hash=function(){var t=bE.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var OE=SE,AE=se.exports,PE=vE,ME=vt.exports.Buffer,kE=[1518500249,1859775393,-1894007588,-899497514],xE=new Array(80);function NE(){this.init(),this._w=xE,PE.call(this,64,56)}function RE(t){return t<<5|t>>>27}function CE(t){return t<<30|t>>>2}function UE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}AE(NE,PE),NE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},NE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var c=~~(h/20),f=RE(n)+UE(c,i,o,s)+u+r[h]+kE[c]|0;u=s,s=o,o=CE(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},NE.prototype._hash=function(){var t=ME.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var LE=NE,DE=se.exports,BE=vE,HE=vt.exports.Buffer,FE=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],qE=new Array(64);function jE(){this.init(),this._w=qE,BE.call(this,64,56)}function GE(t,e,r){return r^t&(e^r)}function KE(t,e,r){return t&e|r&(t|e)}function VE(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function WE(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function $E(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function zE(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}DE(jE,BE),jE.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},jE.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,c=0;c<16;++c)e[c]=t.readInt32BE(4*c);for(;c<64;++c)e[c]=zE(e[c-2])+e[c-7]+$E(e[c-15])+e[c-16]|0;for(var f=0;f<64;++f){var l=h+WE(s)+GE(s,u,a)+FE[f]+e[f]|0,p=VE(r)+KE(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},jE.prototype._hash=function(){var t=HE.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var XE=jE,YE=se.exports,JE=XE,ZE=vE,QE=vt.exports.Buffer,t_=new Array(64);function e_(){this.init(),this._w=t_,ZE.call(this,64,56)}YE(e_,JE),e_.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},e_.prototype._hash=function(){var t=QE.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var r_=e_,n_=se.exports,i_=vE,o_=vt.exports.Buffer,s_=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],u_=new Array(160);function a_(){this.init(),this._w=u_,i_.call(this,128,112)}function h_(t,e,r){return r^t&(e^r)}function c_(t,e,r){return t&e|r&(t|e)}function f_(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function l_(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function p_(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function d_(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function g_(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function y_(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function v_(t,e){return t>>>0>>0?1:0}n_(a_,i_),a_.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},a_.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,c=0|this._al,f=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,y=0|this._gl,v=0|this._hl,m=0;m<32;m+=2)e[m]=t.readInt32BE(4*m),e[m+1]=t.readInt32BE(4*m+4);for(;m<160;m+=2){var w=e[m-30],b=e[m-30+1],E=p_(w,b),_=d_(b,w),S=g_(w=e[m-4],b=e[m-4+1]),I=y_(b,w),T=e[m-14],O=e[m-14+1],A=e[m-32],P=e[m-32+1],M=_+O|0,k=E+T+v_(M,_)|0;k=(k=k+S+v_(M=M+I|0,I)|0)+A+v_(M=M+P|0,P)|0,e[m]=k,e[m+1]=M}for(var x=0;x<160;x+=2){k=e[x],M=e[x+1];var N=c_(r,n,i),R=c_(c,f,l),C=f_(r,c),U=f_(c,r),L=l_(s,d),D=l_(d,s),B=s_[x],H=s_[x+1],F=h_(s,u,a),q=h_(d,g,y),j=v+D|0,G=h+L+v_(j,v)|0;G=(G=(G=G+F+v_(j=j+q|0,q)|0)+B+v_(j=j+H|0,H)|0)+k+v_(j=j+M|0,M)|0;var K=U+R|0,V=C+N+v_(K,U)|0;h=a,v=y,a=u,y=g,u=s,g=d,s=o+G+v_(d=p+j|0,p)|0,o=i,p=l,i=n,l=f,n=r,f=c,r=G+V+v_(c=j+K|0,j)|0}this._al=this._al+c|0,this._bl=this._bl+f|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+v|0,this._ah=this._ah+r+v_(this._al,c)|0,this._bh=this._bh+n+v_(this._bl,f)|0,this._ch=this._ch+i+v_(this._cl,l)|0,this._dh=this._dh+o+v_(this._dl,p)|0,this._eh=this._eh+s+v_(this._el,d)|0,this._fh=this._fh+u+v_(this._fl,g)|0,this._gh=this._gh+a+v_(this._gl,y)|0,this._hh=this._hh+h+v_(this._hl,v)|0},a_.prototype._hash=function(){var t=o_.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var m_=a_,w_=se.exports,b_=m_,E_=vE,__=vt.exports.Buffer,S_=new Array(160);function I_(){this.init(),this._w=S_,E_.call(this,128,112)}w_(I_,b_),I_.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},I_.prototype._hash=function(){var t=__.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var T_=I_,O_=dE.exports=function(t){t=t.toLowerCase();var e=O_[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};O_.sha=OE,O_.sha1=LE,O_.sha224=r_,O_.sha256=XE,O_.sha384=T_,O_.sha512=m_;var A_=dE.exports;function P_(t){return(new pE).update(A_("sha256").update(t).digest()).digest()}var M_,k_=(M_=function(t,e){return M_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},M_(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}M_(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),x_=function(t,e){this.psbt=t,this.masterFp=e},N_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(x_),R_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=P_(t);return e.writeSlice(P.from([118,169,20])),e.writeSlice(r),e.writeSlice(P.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(N_),C_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new Kv,n=this.getTaprootOutputKey(e);return r.writeSlice(P.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=jp.sha256(P.from("TapTweak","utf-8"));return jp.sha256(P.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=P.concat([P.from([2]),t]),r=this.hashTapTweak(t);return P.from(Ht.exports.pointAddScalar(e,r)).slice(1)},e}(N_),U_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=this.createRedeemScript(t),n=P_(r);return e.writeSlice(P.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=P_(t);return P.concat([P.from("0014","hex"),e])},e}(N_),L_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return k_(e,t),e.prototype.singleKeyCondition=function(t){var e=new Kv,r=P_(t);return e.writeSlice(P.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(N_),D_=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},B_=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return j_(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new q_(void 0,void 0,P.alloc(32,0)),leaves:[]};if(1==e){var r=new q_(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=P.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function pS(t){var e=t.outputs,r=P.alloc(0);return void 0!==e&&(r=P.concat([r,lS(e.length)]),e.forEach((function(t){r=P.concat([r,t.amount,lS(t.script.length),t.script])}))),r}function dS(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=P.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?P.concat([s,t.prevout,P.from([0]),t.sequence]):P.concat([s,t.prevout,lS(t.script.length),t.script,t.sequence])}));var a=pS(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=P.concat([a,u&&t.witness||P.alloc(0),t.locktime,t.nExpiryHeight||P.alloc(0),t.extraData||P.alloc(0)])),P.concat([t.version,r||P.alloc(0),t.nVersionGroupId||P.alloc(0),u?P.from("0001","hex"):P.alloc(0),lS(t.inputs.length),s,a])}var gS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},yS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new G_(e,K_(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,P.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return gS(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I;return yS(this,(function(T){switch(T.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new Z_,[4,this.client.getMasterFingerprint()];case 1:n=T.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new C_(e,r):t.additionals.includes("bech32")?new L_(e,r):t.segwit?new U_(e,r):new R_(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,T.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(c=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((f=new Kv).writeVarInt(2),f.writeVarInt(c.length),f.writeSlice(c),f.writeVarInt(n[0].length),f.writeSlice(n[0]),t.setInputFinalScriptwitness(r,f.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new Kv;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new Kv;cS(h,c),cS(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var c,f;if(!(c=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=c.length&&65!=c.length)throw Error("Unexpected length of schnorr signature.");(f=new Kv).writeVarInt(1),f.writeVarSlice(c),t.setInputFinalScriptwitness(r,f.buffer())}hS(t,r)}}(r),I=function(t){var e,r,n=new Kv;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(P.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new Kv,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function NS(t,e,r){return MS(this,void 0,void 0,(function(){var n,i,o,s;return kS(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=P.alloc(4)).writeUInt32BE(r,0),n=P.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function RS(t,e,r,n){return void 0===n&&(n=[]),MS(this,void 0,void 0,(function(){var i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R=this;return kS(this,(function(C){switch(C.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return c=n.includes("decred"),f=n.includes("stealthcoin"),l=function(e,r){return MS(R,void 0,void 0,(function(){var n,i,o,s,u,a,h,c,f,l,p;return kS(this,(function(d){switch(d.label){case 0:for(n=r||P.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>Wv?Wv:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(P.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=xS(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(c=h.value,[4,NS(t,c)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return f=d.sent(),l={error:f},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return NS(t,e)},[4,NS(t,P.concat([r.version,r.timestamp||P.alloc(0),r.nVersionGroupId||P.alloc(0),lS(o.length)]),e)];case 1:C.sent(),C.label=2;case 2:C.trys.push([2,8,9,10]),d=xS(o),g=d.next(),C.label=3;case 3:return g.done?[3,7]:(y=g.value,v=f&&0===P.compare(i,P.from([2,0,0,0])),m=c?y.tree||P.from([0]):P.alloc(0),O=P.concat([y.prevout,m,v?P.from([0]):lS(y.script.length)]),[4,NS(t,O)]);case 4:return C.sent(),[4,c?p(P.concat([y.script,y.sequence])):v?p(y.sequence):l(y.script,y.sequence)];case 5:C.sent(),C.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=C.sent(),M={error:w},[3,10];case 9:try{g&&!g.done&&(k=d.return)&&k.call(d)}finally{if(M)throw M.error}return[7];case 10:return[4,NS(t,lS(s.length))];case 11:C.sent(),C.label=12;case 12:C.trys.push([12,17,18,19]),b=xS(s),E=b.next(),C.label=13;case 13:return E.done?[3,16]:(_=E.value,O=P.concat([_.amount,c?P.from([0,0]):P.alloc(0),lS(_.script.length),_.script]),[4,NS(t,O)]);case 14:C.sent(),C.label=15;case 15:return E=b.next(),[3,13];case 16:return[3,19];case 17:return S=C.sent(),x={error:S},[3,19];case 18:try{E&&!E.done&&(N=b.return)&&N.call(b)}finally{if(x)throw x.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(O=P.concat(I),T=c?O:P.concat([lS(O.length),O])),[4,l(P.concat([u,T||P.alloc(0)]))];case 20:return A=C.sent(),PS(A,"missing result in processScriptBlocks"),[2,A]}}))}))}var CS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},US=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function DS(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function BS(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),CS(this,void 0,void 0,(function(){var a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A;return US(this,(function(M){switch(M.label){case 0:return a=P.concat([r.version,r.timestamp||P.alloc(0),r.nVersionGroupId||P.alloc(0),lS(r.inputs.length)]),[4,DS(t,e,!0,a,i,o,s)];case 1:M.sent(),h=0,c=s.includes("decred"),M.label=2;case 2:M.trys.push([2,15,16,17]),f=LS(r.inputs),l=f.next(),M.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?P.from([1,g.length]):P.from([2]):n[h].trustedInput?P.from([1,n[h].value.length]):P.from([0]),a=P.concat([d,g,c?P.from([0]):P.alloc(0),lS(p.script.length)]),[4,DS(t,e,!1,a,i,o,s)]);case 4:if(M.sent(),y=[],v=0,0===p.script.length)y.push(p.sequence);else for(;v!==p.script.length;)m=p.script.length-v>Wv?Wv:p.script.length-v,v+m!==p.script.length?y.push(p.script.slice(v,v+m)):y.push(P.concat([p.script.slice(v,v+m),p.sequence])),v+=m;M.label=5;case 5:M.trys.push([5,10,11,12]),O=void 0,w=LS(y),b=w.next(),M.label=6;case 6:return b.done?[3,9]:(E=b.value,[4,DS(t,e,!1,E,i,o,s)]);case 7:M.sent(),M.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return _=M.sent(),O={error:_},[3,12];case 11:try{b&&!b.done&&(A=w.return)&&A.call(w)}finally{if(O)throw O.error}return[7];case 12:h++,M.label=13;case 13:return l=f.next(),[3,3];case 14:return[3,17];case 15:return S=M.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(T=f.return)&&T.call(f)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function HS(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=A_("sha256").update(A_("sha256").update(dS(r,!0)).digest()).digest(),o=P.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=P.concat([i,o,s[e].amount])).toString("hex")}function FS(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=At(e),a=P.alloc(4);a.writeUInt32BE(r,0);var h=s?P.concat([u,a,i||P.from([0,0,0,0]),P.from([n])]):P.concat([u,P.from([0]),a,P.from([n])]);return i&&!s&&(h=P.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var qS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},jS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:Wv,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var VS=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},WS=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ZS={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function QS(t,e){return XS(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R,C,U,L,D,B,H,F,q,j,G,K,V,W,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at,ht;return YS(this,(function(ct){switch(ct.label){case 0:if(r=zS(zS({},ZS),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,c=r.initialTimestamp,f=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(y=r.useTrustedInputForSegwit))return[3,4];ct.label=1;case 1:return ct.trys.push([1,3,,4]),[4,$S(t)];case 2:return v=ct.sent(),y=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||Gv.gte(e,"1.4.0"))}(v),[3,4];case 3:if(27904!==(m=ct.sent()).statusCode)throw m;return y=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=f.includes("decred"),E=f.includes("stealthcoin"),_=Date.now(),S=f.includes("sapling"),I=h&&f.includes("bech32"),T=h||!!f&&(f.includes("abc")||f.includes("gold")||f.includes("bip143"))||!!l&&!b,O=P.alloc(0),A=P.alloc(0),M=P.alloc(4),l&&!b?M.writeUInt32LE(S?2147483652:2147483651,0):E?M.writeUInt32LE(2,0):M.writeUInt32LE(1,0),k=[],x=[],N=[],R=[],C=!0,U=!1,L={inputs:[],version:M,timestamp:P.alloc(0)},D=T&&!y?HS:RS,B=P.from(s,"hex"),w(0,0),ct.label=5;case 5:ct.trys.push([5,11,12,13]),H=JS(n),F=H.next(),ct.label=6;case 6:return F.done?[3,10]:(z=F.value,U?[3,8]:[4,D(t,z[1],z[0],f)]);case 7:q=ct.sent(),_S("hw","got trustedInput="+q),(j=P.alloc(4)).writeUInt32LE(z.length>=4&&"number"==typeof z[3]?z[3]:$v,0),k.push({trustedInput:!0,value:P.from(q,"hex"),sequence:j}),ct.label=8;case 8:G=z[0].outputs,K=z[1],G&&K<=G.length-1&&x.push(G[K]),l&&!b?(L.nVersionGroupId=P.from(S?[133,32,47,137]:[112,130,196,3]),L.nExpiryHeight=l,L.extraData=P.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(L.nExpiryHeight=l),ct.label=9;case 9:return F=H.next(),[3,6];case 10:return[3,13];case 11:return V=ct.sent(),at={error:V},[3,13];case 12:try{F&&!F.done&&(ht=H.return)&&ht.call(H)}finally{if(at)throw at.error}return[7];case 13:if(L.inputs=n.map((function(t){var e=P.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:$v,0),{script:O,prevout:A,sequence:e}})),U)return[3,18];W=[],ot=0,ct.label=14;case 14:return ot=3&&"string"==typeof z[2]?P.from(z[2],"hex"):h?P.concat([P.from([118,169,20]),P_(R[ot]),P.from([136,172])]):x[ot].script,Y=Object.assign({},L),J=T?[k[ot]]:k,T?Y.inputs=[zS(zS({},Y.inputs[ot]),{script:X})]:Y.inputs[ot].script=X,[4,BS(t,!T&&C,Y,J,T,!!l&&!b,f,y)]):[3,34];case 27:return ct.sent(),T?[3,31]:U||!o?[3,29]:[4,GS(t,o)];case 28:ct.sent(),ct.label=29;case 29:return[4,KS(t,B,f)];case 30:ct.sent(),ct.label=31;case 31:return C&&(d(),w(1,0)),[4,FS(t,i[ot],u,a,l,f)];case 32:Z=ct.sent(),w(1,ot+1),N.push(Z),L.inputs[ot].script=O,C&&(C=!1),ct.label=33;case 33:return ot++,[3,26];case 34:for(ot=0;ot0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},sI={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function uI(t,e){return nI(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S,I,T,O,A,M,k,x,N,R,C,U,L;return iI(this,(function(D){switch(D.label){case 0:r=rI(rI({},sI),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,c=P.alloc(0),f=P.alloc(0),(l=P.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],y=!0,v=!1,m={inputs:[],version:l},w=a?HS:RS,b=P.from(o,"hex"),D.label=1;case 1:D.trys.push([1,7,8,9]),E=oI(n),_=E.next(),D.label=2;case 2:return _.done?[3,6]:(k=_.value,v?[3,4]:[4,w(t,k[1],k[0])]);case 3:S=D.sent(),(A=P.alloc(4)).writeUInt32LE(k.length>=4&&"number"==typeof k[3]?k[3]:$v,0),p.push({trustedInput:!1,value:a?P.from(S,"hex"):P.from(S,"hex").slice(4,40),sequence:A}),D.label=4;case 4:I=k[0].outputs,T=k[1],I&&T<=I.length-1&&d.push(I[T]),D.label=5;case 5:return _=E.next(),[3,2];case 6:return[3,9];case 7:return O=D.sent(),U={error:O},[3,9];case 8:try{_&&!_.done&&(L=E.return)&&L.call(E)}finally{if(U)throw U.error}return[7];case 9:for(M=0;M=4&&"number"==typeof n[M][3]?n[M][3]:$v,0),m.inputs.push({script:c,prevout:f,sequence:A});return a?[4,BS(t,!0,m,p,!0)]:[3,12];case 10:return D.sent(),[4,KS(t,b)];case 11:D.sent(),D.label=12;case 12:M=0,D.label=13;case 13:return M=3&&"string"==typeof k[2]?P.from(k[2],"hex"):d[M].script,N=Object.assign({},m),R=a?[p[M]]:p,a?N.inputs=[rI(rI({},N.inputs[M]),{script:x})]:N.inputs[M].script=x,[4,BS(t,!a&&y,N,R,a)]):[3,19];case 14:return D.sent(),a?[3,16]:[4,KS(t,b)];case 15:D.sent(),D.label=16;case 16:return[4,FS(t,i[M],s,u)];case 17:C=D.sent(),g.push(a?C.toString("hex"):C.slice(0,C.length-1).toString("hex")),m.inputs[M].script=c,y&&(y=!1),D.label=18;case 18:return M++,[3,13];case 19:return[2,g]}}))}))}var aI=function(){return aI=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=P.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},f.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return f.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,P.from([0]))];case 4:return u=f.sent(),a=u[0]-48,0===(h=u.slice(4,4+u[3]))[0]&&(h=h.slice(1)),h=h.toString("hex"),o=4+u[3]+2,0===(c=u.slice(o,o+u[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:a,r:h,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),QS(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),uI(this.transport,t)},t}();function lI(t){var e=P.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var pI=function(t){return P.concat([P.from([2+(1&t[64])]),t.slice(1,33)])};function dI(t){return A_("sha256").update(t).digest()}var gI,yI=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new H_(t.map((function(t){return F_(t)}))),this.values=e,this.valuesTree=new H_(e.map((function(t){return F_(t)})))}return t.prototype.commitment=function(){return P.concat([lS(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),vI=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),mI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},wI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},SI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(gI||(gI={}));var TI,OI,AI=function(){},PI=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=gI.YIELD,n.results=e,n}return EI(e,t),e.prototype.execute=function(t){return this.results.push(P.from(t.subarray(1))),this.progressCallback(),P.from("")},e}(AI),MI=function(t){function e(e,r){var n=t.call(this)||this;return n.code=gI.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return EI(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=P.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=lS(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),c=a.length-h;return c>0&&(e=this.queue).push.apply(e,SI([],_I(a.slice(-c)),!1)),P.concat(SI([u.getLeafHash(i),P.from([a.length]),P.from([h])],_I(a.slice(0,h)),!1))},e}(AI),xI=function(t){function e(e){var r=t.call(this)||this;return r.code=gI.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return EI(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=P.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=P.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(TI||(TI={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(OI||(OI={}));var DI=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return CI(this,void 0,void 0,(function(){var n,i,o;return UI(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,OI.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return CI(this,void 0,void 0,(function(){return UI(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(TI.GET_PUBKEY,P.concat([P.from(t?[1]:[0]),Ot(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return CI(this,void 0,void 0,(function(){var o,s;return UI(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new RI((function(){}))).addKnownList(t.keys.map((function(t){return P.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=P.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(TI.GET_WALLET_ADDRESS,P.concat([P.from(i?[1]:[0]),t.getWalletId(),e||P.alloc(32,0),P.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return CI(this,void 0,void 0,(function(){var i,o,s,u,a,h,c,f,l,p,d,g,y,v,m,w,b,E,_,S;return UI(this,(function(I){switch(I.label){case 0:if(i=new bI(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new RI(n)).addKnownList(e.keys.map((function(t){return P.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=LI(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())c=u.value,o.addKnownMapping(c)}catch(t){m={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(m)throw m.error}}try{for(a=LI(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())c=h.value,o.addKnownMapping(c)}catch(t){b={error:t}}finally{try{h&&!h.done&&(E=a.return)&&E.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),f=new H_(i.inputMapCommitments.map((function(t){return F_(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new H_(i.outputMapCommitments.map((function(t){return F_(t)}))).getRoot(),[4,this.makeRequest(TI.SIGN_PSBT,P.concat([i.getGlobalKeysValuesRoot(),lS(i.getGlobalInputCount()),f,lS(i.getGlobalOutputCount()),l,e.getWalletId(),r||P.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=LI(p),y=g.next();!y.done;y=g.next())v=y.value,d.set(v[0],v.slice(1))}catch(t){_={error:t}}finally{try{y&&!y.done&&(S=g.return)&&S.call(g)}finally{if(_)throw _.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return CI(this,void 0,void 0,(function(){return UI(this,(function(t){return[2,this.makeRequest(TI.GET_MASTER_FINGERPRINT,P.from([]))]}))}))},t}();var BI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},HI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof mS&&"bech32m"!=r.format)||r.verify&&0!=r.verify||qI(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=P.alloc(0),c=P.alloc(0),f=P.alloc(0),l=P.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=P.from(t,"hex"),y=g.slice(a,a+4),v=y.equals(P.from([3,0,0,128]))||y.equals(P.from([4,0,0,128])),m=y.equals(P.from([1,0,0,0]))||y.equals(P.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&m)&&(h=g.slice(a,4+a),a+=4),v&&(f=g.slice(a,4+a),a+=4);var w=fS(g,a),b=w[0];a+=w[1];for(var E=0;E=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new fI(this.transport)},t.prototype.new=function(){return new mS(new DI(this.transport))},t}();function qI(t){var e=2147483648,r=Mt(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var jI=Object.freeze({__proto__:null,default:FI}),GI={},KI={},VI={},WI={};Object.defineProperty(WI,"__esModule",{value:!0});var $I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zI={},XI={};WI.addCustomErrorDeserializer=function(t,e){XI[t]=e};var YI=WI.createCustomErrorClass=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,zI[t]=e,e};function JI(t,e){var r={};e.push(t);var n=!0,i=!1,o=void 0;try{for(var s,u=Object.keys(t)[Symbol.iterator]();!(n=(s=u.next()).done);n=!0){var a=s.value,h=t[a];"function"!=typeof h&&(h&&"object"===(void 0===h?"undefined":$I(h))?-1!==e.indexOf(t[a])?r[a]="[Circular]":r[a]=JI(t[a],e.slice(0)):r[a]=h)}}catch(t){i=!0,o=t}finally{try{!n&&u.return&&u.return()}finally{if(i)throw o}}return"string"==typeof t.name&&(r.name=t.name),"string"==typeof t.message&&(r.message=t.message),"string"==typeof t.stack&&(r.stack=t.stack),r}WI.deserializeError=function t(e){if("object"===(void 0===e?"undefined":$I(e))&&e){try{var r=JSON.parse(e.message);r.message&&r.name&&(e=r)}catch(t){}var n=void 0;if("string"==typeof e.name){var i=e.name,o=XI[i];if(o)n=o(e);else{var s="Error"===i?Error:zI[i];s||(console.warn("deserializing an unknown class '"+i+"'"),s=YI(i)),n=Object.create(s.prototype);try{for(var u in e)e.hasOwnProperty(u)&&(n[u]=e[u])}catch(t){}}}else n=new Error(e.message);return!n.stack&&Error.captureStackTrace&&Error.captureStackTrace(n,t),n}return new Error(String(e))},WI.serializeError=function(t){return t?"object"===(void 0===t?"undefined":$I(t))?JI(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},Object.defineProperty(VI,"__esModule",{value:!0}),VI.StatusCodes=VI.DBNotReset=VI.DBWrongPassword=VI.NoDBPathGiven=VI.FirmwareOrAppUpdateRequired=VI.LedgerAPI5xx=VI.LedgerAPI4xx=VI.GenuineCheckFailed=VI.PairingFailed=VI.SyncError=VI.FeeTooHigh=VI.FeeRequired=VI.FeeNotLoaded=VI.CantScanQRCode=VI.ETHAddressNonEIP=VI.WrongAppForCurrency=VI.WrongDeviceForAccount=VI.WebsocketConnectionFailed=VI.WebsocketConnectionError=VI.DeviceShouldStayInApp=VI.TransportWebUSBGestureRequired=VI.TransportInterfaceNotAvailable=VI.TransportOpenUserCancelled=VI.UserRefusedOnDevice=VI.UserRefusedAllowManager=VI.UserRefusedFirmwareUpdate=VI.UserRefusedAddress=VI.UserRefusedDeviceNameChange=VI.UpdateYourApp=VI.UnavailableTezosOriginatedAccountSend=VI.UnavailableTezosOriginatedAccountReceive=VI.RecipientRequired=VI.MCUNotGenuineToDashboard=VI.UnexpectedBootloader=VI.TimeoutTagged=VI.RecommendUndelegation=VI.RecommendSubAccountsToEmpty=VI.PasswordIncorrectError=VI.PasswordsDontMatchError=VI.GasLessThanEstimate=VI.NotSupportedLegacyAddress=VI.NotEnoughGas=VI.NoAccessToCamera=VI.NotEnoughBalanceBecauseDestinationNotCreated=VI.NotEnoughSpendableBalance=VI.NotEnoughBalanceInParentAccount=VI.NotEnoughBalanceToDelegate=VI.NotEnoughBalance=VI.NoAddressesFound=VI.NetworkDown=VI.ManagerUninstallBTCDep=VI.ManagerNotEnoughSpaceError=VI.ManagerFirmwareNotEnoughSpaceError=VI.ManagerDeviceLockedError=VI.ManagerAppDepUninstallRequired=VI.ManagerAppDepInstallRequired=VI.ManagerAppRelyOnBTCError=VI.ManagerAppAlreadyInstalledError=VI.LedgerAPINotAvailable=VI.LedgerAPIErrorWithMessage=VI.LedgerAPIError=VI.UnknownMCU=VI.LatestMCUInstalledError=VI.InvalidAddressBecauseDestinationIsAlsoSource=VI.InvalidAddress=VI.InvalidXRPTag=VI.HardResetFail=VI.FeeEstimationFailed=VI.EthAppPleaseEnableContractData=VI.EnpointConfigError=VI.DisconnectedDeviceDuringOperation=VI.DisconnectedDevice=VI.DeviceSocketNoBulkStatus=VI.DeviceSocketFail=VI.DeviceNameInvalid=VI.DeviceHalted=VI.DeviceInOSUExpected=VI.DeviceOnDashboardUnexpected=VI.DeviceOnDashboardExpected=VI.DeviceNotGenuineError=VI.DeviceGenuineSocketEarlyClose=VI.DeviceAppVerifyNotSupported=VI.CurrencyNotSupported=VI.CashAddrNotSupported=VI.CantOpenDevice=VI.BtcUnmatchedApp=VI.BluetoothRequired=VI.AmountRequired=VI.AccountNotSupported=VI.AccountNameRequiredError=VI.addCustomErrorDeserializer=VI.createCustomErrorClass=VI.deserializeError=VI.serializeError=void 0,VI.TransportError=QI,VI.getAltStatusMessage=eT,VI.TransportStatusError=rT;var ZI=WI;function QI(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}VI.serializeError=ZI.serializeError,VI.deserializeError=ZI.deserializeError,VI.createCustomErrorClass=ZI.createCustomErrorClass,VI.addCustomErrorDeserializer=ZI.addCustomErrorDeserializer,VI.AccountNameRequiredError=(0,ZI.createCustomErrorClass)("AccountNameRequired"),VI.AccountNotSupported=(0,ZI.createCustomErrorClass)("AccountNotSupported"),VI.AmountRequired=(0,ZI.createCustomErrorClass)("AmountRequired"),VI.BluetoothRequired=(0,ZI.createCustomErrorClass)("BluetoothRequired"),VI.BtcUnmatchedApp=(0,ZI.createCustomErrorClass)("BtcUnmatchedApp"),VI.CantOpenDevice=(0,ZI.createCustomErrorClass)("CantOpenDevice"),VI.CashAddrNotSupported=(0,ZI.createCustomErrorClass)("CashAddrNotSupported"),VI.CurrencyNotSupported=(0,ZI.createCustomErrorClass)("CurrencyNotSupported"),VI.DeviceAppVerifyNotSupported=(0,ZI.createCustomErrorClass)("DeviceAppVerifyNotSupported"),VI.DeviceGenuineSocketEarlyClose=(0,ZI.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"),VI.DeviceNotGenuineError=(0,ZI.createCustomErrorClass)("DeviceNotGenuine"),VI.DeviceOnDashboardExpected=(0,ZI.createCustomErrorClass)("DeviceOnDashboardExpected"),VI.DeviceOnDashboardUnexpected=(0,ZI.createCustomErrorClass)("DeviceOnDashboardUnexpected"),VI.DeviceInOSUExpected=(0,ZI.createCustomErrorClass)("DeviceInOSUExpected"),VI.DeviceHalted=(0,ZI.createCustomErrorClass)("DeviceHalted"),VI.DeviceNameInvalid=(0,ZI.createCustomErrorClass)("DeviceNameInvalid"),VI.DeviceSocketFail=(0,ZI.createCustomErrorClass)("DeviceSocketFail"),VI.DeviceSocketNoBulkStatus=(0,ZI.createCustomErrorClass)("DeviceSocketNoBulkStatus"),VI.DisconnectedDevice=(0,ZI.createCustomErrorClass)("DisconnectedDevice"),VI.DisconnectedDeviceDuringOperation=(0,ZI.createCustomErrorClass)("DisconnectedDeviceDuringOperation"),VI.EnpointConfigError=(0,ZI.createCustomErrorClass)("EnpointConfig"),VI.EthAppPleaseEnableContractData=(0,ZI.createCustomErrorClass)("EthAppPleaseEnableContractData"),VI.FeeEstimationFailed=(0,ZI.createCustomErrorClass)("FeeEstimationFailed"),VI.HardResetFail=(0,ZI.createCustomErrorClass)("HardResetFail"),VI.InvalidXRPTag=(0,ZI.createCustomErrorClass)("InvalidXRPTag"),VI.InvalidAddress=(0,ZI.createCustomErrorClass)("InvalidAddress"),VI.InvalidAddressBecauseDestinationIsAlsoSource=(0,ZI.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"),VI.LatestMCUInstalledError=(0,ZI.createCustomErrorClass)("LatestMCUInstalledError"),VI.UnknownMCU=(0,ZI.createCustomErrorClass)("UnknownMCU"),VI.LedgerAPIError=(0,ZI.createCustomErrorClass)("LedgerAPIError"),VI.LedgerAPIErrorWithMessage=(0,ZI.createCustomErrorClass)("LedgerAPIErrorWithMessage"),VI.LedgerAPINotAvailable=(0,ZI.createCustomErrorClass)("LedgerAPINotAvailable"),VI.ManagerAppAlreadyInstalledError=(0,ZI.createCustomErrorClass)("ManagerAppAlreadyInstalled"),VI.ManagerAppRelyOnBTCError=(0,ZI.createCustomErrorClass)("ManagerAppRelyOnBTC"),VI.ManagerAppDepInstallRequired=(0,ZI.createCustomErrorClass)("ManagerAppDepInstallRequired"),VI.ManagerAppDepUninstallRequired=(0,ZI.createCustomErrorClass)("ManagerAppDepUninstallRequired"),VI.ManagerDeviceLockedError=(0,ZI.createCustomErrorClass)("ManagerDeviceLocked"),VI.ManagerFirmwareNotEnoughSpaceError=(0,ZI.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"),VI.ManagerNotEnoughSpaceError=(0,ZI.createCustomErrorClass)("ManagerNotEnoughSpace"),VI.ManagerUninstallBTCDep=(0,ZI.createCustomErrorClass)("ManagerUninstallBTCDep"),VI.NetworkDown=(0,ZI.createCustomErrorClass)("NetworkDown"),VI.NoAddressesFound=(0,ZI.createCustomErrorClass)("NoAddressesFound"),VI.NotEnoughBalance=(0,ZI.createCustomErrorClass)("NotEnoughBalance"),VI.NotEnoughBalanceToDelegate=(0,ZI.createCustomErrorClass)("NotEnoughBalanceToDelegate"),VI.NotEnoughBalanceInParentAccount=(0,ZI.createCustomErrorClass)("NotEnoughBalanceInParentAccount"),VI.NotEnoughSpendableBalance=(0,ZI.createCustomErrorClass)("NotEnoughSpendableBalance"),VI.NotEnoughBalanceBecauseDestinationNotCreated=(0,ZI.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"),VI.NoAccessToCamera=(0,ZI.createCustomErrorClass)("NoAccessToCamera"),VI.NotEnoughGas=(0,ZI.createCustomErrorClass)("NotEnoughGas"),VI.NotSupportedLegacyAddress=(0,ZI.createCustomErrorClass)("NotSupportedLegacyAddress"),VI.GasLessThanEstimate=(0,ZI.createCustomErrorClass)("GasLessThanEstimate"),VI.PasswordsDontMatchError=(0,ZI.createCustomErrorClass)("PasswordsDontMatch"),VI.PasswordIncorrectError=(0,ZI.createCustomErrorClass)("PasswordIncorrect"),VI.RecommendSubAccountsToEmpty=(0,ZI.createCustomErrorClass)("RecommendSubAccountsToEmpty"),VI.RecommendUndelegation=(0,ZI.createCustomErrorClass)("RecommendUndelegation"),VI.TimeoutTagged=(0,ZI.createCustomErrorClass)("TimeoutTagged"),VI.UnexpectedBootloader=(0,ZI.createCustomErrorClass)("UnexpectedBootloader"),VI.MCUNotGenuineToDashboard=(0,ZI.createCustomErrorClass)("MCUNotGenuineToDashboard"),VI.RecipientRequired=(0,ZI.createCustomErrorClass)("RecipientRequired"),VI.UnavailableTezosOriginatedAccountReceive=(0,ZI.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"),VI.UnavailableTezosOriginatedAccountSend=(0,ZI.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"),VI.UpdateYourApp=(0,ZI.createCustomErrorClass)("UpdateYourApp"),VI.UserRefusedDeviceNameChange=(0,ZI.createCustomErrorClass)("UserRefusedDeviceNameChange"),VI.UserRefusedAddress=(0,ZI.createCustomErrorClass)("UserRefusedAddress"),VI.UserRefusedFirmwareUpdate=(0,ZI.createCustomErrorClass)("UserRefusedFirmwareUpdate"),VI.UserRefusedAllowManager=(0,ZI.createCustomErrorClass)("UserRefusedAllowManager"),VI.UserRefusedOnDevice=(0,ZI.createCustomErrorClass)("UserRefusedOnDevice"),VI.TransportOpenUserCancelled=(0,ZI.createCustomErrorClass)("TransportOpenUserCancelled"),VI.TransportInterfaceNotAvailable=(0,ZI.createCustomErrorClass)("TransportInterfaceNotAvailable"),VI.TransportWebUSBGestureRequired=(0,ZI.createCustomErrorClass)("TransportWebUSBGestureRequired"),VI.DeviceShouldStayInApp=(0,ZI.createCustomErrorClass)("DeviceShouldStayInApp"),VI.WebsocketConnectionError=(0,ZI.createCustomErrorClass)("WebsocketConnectionError"),VI.WebsocketConnectionFailed=(0,ZI.createCustomErrorClass)("WebsocketConnectionFailed"),VI.WrongDeviceForAccount=(0,ZI.createCustomErrorClass)("WrongDeviceForAccount"),VI.WrongAppForCurrency=(0,ZI.createCustomErrorClass)("WrongAppForCurrency"),VI.ETHAddressNonEIP=(0,ZI.createCustomErrorClass)("ETHAddressNonEIP"),VI.CantScanQRCode=(0,ZI.createCustomErrorClass)("CantScanQRCode"),VI.FeeNotLoaded=(0,ZI.createCustomErrorClass)("FeeNotLoaded"),VI.FeeRequired=(0,ZI.createCustomErrorClass)("FeeRequired"),VI.FeeTooHigh=(0,ZI.createCustomErrorClass)("FeeTooHigh"),VI.SyncError=(0,ZI.createCustomErrorClass)("SyncError"),VI.PairingFailed=(0,ZI.createCustomErrorClass)("PairingFailed"),VI.GenuineCheckFailed=(0,ZI.createCustomErrorClass)("GenuineCheckFailed"),VI.LedgerAPI4xx=(0,ZI.createCustomErrorClass)("LedgerAPI4xx"),VI.LedgerAPI5xx=(0,ZI.createCustomErrorClass)("LedgerAPI5xx"),VI.FirmwareOrAppUpdateRequired=(0,ZI.createCustomErrorClass)("FirmwareOrAppUpdateRequired"),VI.NoDBPathGiven=(0,ZI.createCustomErrorClass)("NoDBPathGiven"),VI.DBWrongPassword=(0,ZI.createCustomErrorClass)("DBWrongPassword"),VI.DBNotReset=(0,ZI.createCustomErrorClass)("DBNotReset"),QI.prototype=new Error,(0,ZI.addCustomErrorDeserializer)("TransportError",(function(t){return new QI(t.message,t.id)}));var tT=VI.StatusCodes={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function eT(t){switch(t){case 26368:return"Incorrect length";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function rT(t){this.name="TransportStatusError";var e=Object.keys(tT).find((function(e){return tT[e]===t}))||"UNKNOWN_ERROR",r=eT(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}rT.prototype=new Error,(0,ZI.addCustomErrorDeserializer)("TransportStatusError",(function(t){return new rT(t.statusCode)})),Object.defineProperty(KI,"__esModule",{value:!0}),KI.getAltStatusMessage=KI.StatusCodes=KI.TransportStatusError=KI.TransportError=void 0;var nT,iT=function(){function t(t,e){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:P.alloc(0),h=arguments.length>5&&void 0!==arguments[5]?arguments[5]:[uT.StatusCodes.OK];return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!(a.length>=256)){t.next=2;break}throw new uT.TransportError("data.length exceed 256 bytes limit. Got: "+a.length,"DataLengthTooBig");case 2:return t.next=4,n.exchange(P.concat([P.from([e,r,i,o]),P.from([a.length]),a]));case 4:if(s=t.sent,u=s.readUInt16BE(s.length-2),h.some((function(t){return t===u}))){t.next=8;break}throw new uT.TransportStatusError(u);case 8:return t.abrupt("return",s);case 9:case"end":return t.stop()}}),t,n)}))),function(t,r,n,i){return e.apply(this,arguments)}),this.exchangeAtomicImpl=(r=hT(regeneratorRuntime.mark((function t(e){var r,i,o;return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!n.exchangeBusyPromise){t.next=2;break}throw new uT.TransportError("Transport race condition","RaceCondition");case 2:return r=void 0,i=new Promise((function(t){r=t})),n.exchangeBusyPromise=i,t.prev=5,t.next=8,e();case 8:return o=t.sent,t.abrupt("return",o);case 10:return t.prev=10,r&&r(),n.exchangeBusyPromise=null,t.finish(10);case 14:case"end":return t.stop()}}),t,n,[[5,,10,14]])}))),function(t){return r.apply(this,arguments)}),this._appAPIlock=null}return iT(t,[{key:"on",value:function(t,e){this._events.on(t,e)}},{key:"off",value:function(t,e){this._events.removeListener(t,e)}},{key:"emit",value:function(t){for(var e,r=arguments.length,n=Array(r>1?r-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:3e3,r=arguments[1];return new Promise((function(n,i){var o=!1,s=t.listen({next:function(r){o=!0,s&&s.unsubscribe(),u&&clearTimeout(u),t.open(r.descriptor,e).then(n,i)},error:function(t){u&&clearTimeout(u),i(t)},complete:function(){u&&clearTimeout(u),o||i(new uT.TransportError(t.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),u=r?setTimeout((function(){s.unsubscribe(),i(new uT.TransportError(t.ErrorMessage_ListenTimeout,"ListenTimeout"))}),r):null}))}}]),t}();cT.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",cT.ErrorMessage_NoDeviceFound="No Ledger device found",KI.default=cT;var fT={};Object.defineProperty(fT,"__esModule",{value:!0});var lT=VI;function pT(t){var e=P.alloc(2);return e.writeUInt16BE(t,0),e}var dT={data:P.alloc(0),dataLength:0,sequence:0};fT.default=function(t,e){return{makeBlocks:function(r){var n=P.concat([pT(r.length),r]),i=e-5,o=Math.ceil(n.length/i);n=P.concat([n,P.alloc(o*i-n.length+1).fill(0)]);for(var s=[],u=0;uo&&(i=i.slice(0,o)),{data:i,dataLength:o,sequence:s}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}};var gT={};Object.defineProperty(gT,"__esModule",{value:!0});var yT=Object.assign||function(t){for(var e=1;e>8;return wT.find((function(t){return t.productIdMM===r}))},gT.identifyProductName=function(t){var e=mT[t];return wT.find((function(t){return t.id===e}))};var bT=[],ET={};for(var _T in vT){var ST=vT[_T],IT=ST.bluetoothSpec;if(IT)for(var TT=0;TT0)){t.next=5;break}return t.abrupt("return",e[0]);case 5:return t.abrupt("return",UT());case 6:case"end":return t.stop()}}),t,this)}))),function(){return CT.apply(this,arguments)});var DT=gT;function BT(t){return function(){var e=t.apply(this,arguments);return new Promise((function(t,r){return function n(i,o){try{var s=e[i](o),u=s.value}catch(t){return void r(t)}if(!s.done)return Promise.resolve(u).then((function(t){n("next",t)}),(function(t){n("throw",t)}));t(u)}("next")}))}}var HT=[{vendorId:DT.ledgerUSBVendorId}];xT.isSupported=function(){return Promise.resolve(!!navigator&&!!navigator.usb&&"function"==typeof navigator.usb.getDevices)},Object.defineProperty(GI,"__esModule",{value:!0});var FT=function(){function t(t,e){for(var r=0;r "+e.toString("hex")),o=(0,jT.default)(n,i),s=o.makeBlocks(e),u=0;case 5:if(!(u "+s[u].toString("hex")),r.next=9,t.device.transferOut(3,s[u]);case 9:u++,r.next=5;break;case 12:a=void 0,h=void 0;case 14:if(a=o.getReducedResult(h)){r.next=23;break}return r.next=17,t.device.transferIn(3,i);case 17:c=r.sent,f=P.from(c.data.buffer),(0,KT.log)("hid-frame","<= "+f.toString("hex")),h=o.reduceResponse(h,f),r.next=14;break;case 23:return(0,KT.log)("apdu","<= "+a.toString("hex")),r.abrupt("return",a);case 25:case"end":return r.stop()}}),r,t)})))).catch((function(e){if(e&&e.message&&e.message.includes("disconnected"))throw t._emitDisconnect(e),new VT.DisconnectedDeviceDuringOperation(e.message);throw e}))}},JT=GI.default=XT,ZT=Object.freeze(u({__proto__:null,default:JT},[GI]));t.Btc=jI,t.TransportWebUSB=ZT,Object.defineProperty(t,"__esModule",{value:!0})})); + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); + } + + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); + var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); + var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); + var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); + var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + var runtime = {exports: {}}; + + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + (function (module) { + var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined$1; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + define(Gp, "constructor", GeneratorFunctionPrototype); + define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined$1) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined$1; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined$1; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + define(Gp, iteratorSymbol, function() { + return this; + }); + + define(Gp, "toString", function() { + return "[object Generator]"; + }); + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined$1; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined$1, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined$1; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined$1; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined$1; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined$1; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports + )); + + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, in modern engines + // we can explicitly access globalThis. In older engines we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } + } + }(runtime)); + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + 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]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (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) + } + + function write (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; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use 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+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer$g.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + function kMaxLength () { + return Buffer$g.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$g.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$g(length); + } + that.length = length; + } + + return that + } + + /** + * 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$g (arg, encodingOrOffset, length) { + if (!Buffer$g.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$g)) { + return new Buffer$g(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from$2(this, arg, encodingOrOffset, length) + } + + Buffer$g.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$g._augment = function (arr) { + arr.__proto__ = Buffer$g.prototype; + return arr + }; + + function from$2 (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, 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$g.from = function (value, encodingOrOffset, length) { + return from$2(null, value, encodingOrOffset, length) + }; + + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + Buffer$g.prototype.__proto__ = Uint8Array.prototype; + Buffer$g.__proto__ = Uint8Array; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer$g.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$g.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$g.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer$g.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$g.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.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') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$g.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer$g.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer$g.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var 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$g.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$g.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$g.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$g.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + 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 utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer$g.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var 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 coersion 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; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$g.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer$g.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer$g.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer$g.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var 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$g.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer$g.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$g.compare(this, b) === 0 + }; + + Buffer$g.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer$g.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + 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 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var 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 (isNaN(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$g.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(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 (Buffer$g.TYPED_ARRAY_SUPPORT && + 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) { + var indexSize = 1; + var arrLength = arr.length; + var 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) + } + } + + var i; + if (dir) { + var 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--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer$g.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer$g.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer$g.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(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 latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, 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$g.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; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var 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'; + + var 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': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(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$g.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 fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var 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 + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var 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". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex$1(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer$g.prototype.slice = function slice (start, end) { + var 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; + + var newBuf; + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$g.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$g(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + 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$g.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer$g.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer$g.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer$g.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer$g.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer$g.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer$g.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer$g.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var 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$g.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var 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$g.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer$g.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$g.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$g.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer$g.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer$g.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer$g.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer$g.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer$g.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(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$g.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$g.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$g.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$g.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer$g.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$g.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer$g.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$g.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer$g.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var 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$g.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var 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$g.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$g.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer$g.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$g.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer$g.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$g.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; + if (Buffer$g.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + 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) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer$g.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer$g.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer$g.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer$g.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer$g.prototype.copy = function copy (target, targetStart, start, end) { + 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('sourceStart out of bounds') + 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; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$g.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer$g.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 (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$g.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // 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; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer$g(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).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 stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex$1 (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var 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) { + var byteArray = []; + for (var 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) { + var c, hi, lo; + var byteArray = []; + for (var 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 toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + /* + * Bitcoin BIP32 path helpers + * (C) 2016 Alex Beregszaszi + */ + + const HARDENED = 0x80000000; + + var BIPPath = function (path) { + if (!Array.isArray(path)) { + throw new Error('Input must be an Array') + } + if (path.length === 0) { + throw new Error('Path must contain at least one level') + } + for (var i = 0; i < path.length; i++) { + if (typeof path[i] !== 'number') { + throw new Error('Path element is not a number') + } + } + this.path = path; + }; + + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false + } + }; + + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false + } + }; + + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) + }; + + BIPPath.fromString = function (text, reqRoot) { + // skip the root + if (/^m\//i.test(text)) { + text = text.slice(2); + } else if (reqRoot) { + throw new Error('Root element is required') + } + + var path = text.split('/'); + var ret = new Array(path.length); + for (var i = 0; i < path.length; i++) { + var tmp = /(\d+)([hH\']?)/.exec(path[i]); + if (tmp === null) { + throw new Error('Invalid input') + } + ret[i] = parseInt(tmp[1], 10); + + if (ret[i] >= HARDENED) { + throw new Error('Invalid child index') + } + + if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { + ret[i] += HARDENED; + } else if (tmp[2].length != 0) { + throw new Error('Invalid modifier') + } + } + return new BIPPath(ret) + }; + + BIPPath.prototype.toPathArray = function () { + return this.path + }; + + BIPPath.prototype.toString = function (noRoot, oldStyle) { + var ret = new Array(this.path.length); + for (var i = 0; i < this.path.length; i++) { + var tmp = this.path[i]; + if (tmp & HARDENED) { + ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); + } else { + ret[i] = tmp; + } + } + return (noRoot ? '' : 'm/') + ret.join('/') + }; + + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; + + var bip32Path = BIPPath; + + var createHash$3 = require$$0__default["default"].createHash; + + var index = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': createHash$3 + }, [createHash$3])); + + var safeBuffer = {exports: {}}; + + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer = require$$0__default$1["default"]; + 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) + }; + }(safeBuffer, safeBuffer.exports)); + + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; + } + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; + } + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } + } + var src$2 = base$2; + + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + var bs58 = basex(ALPHABET$1); + + var base58 = bs58; + var Buffer$f = safeBuffer.exports.Buffer; + + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); + + return base58.encode(Buffer$f.concat([ + payload, + checksum + ], payload.length + 4)) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } + }; + + var createHash$2 = createHash$3; + var bs58checkBase = base$1; + + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() + } + + var bs58check$5 = bs58checkBase(sha256x2); + + function pathElementsToBuffer(paths) { + var buffer = Buffer$g.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } + + var src$1 = {}; + + var src = {}; + + var bip32$1 = {}; + + var crypto$4 = {}; + + var createHmac$2 = require$$0__default["default"].createHmac; + + Object.defineProperty(crypto$4, "__esModule", { value: true }); + const createHash$1 = createHash$3; + const createHmac$1 = createHmac$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } + } + crypto$4.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$4.hmacSHA512 = hmacSHA512; + + var tinySecp256k1 = {exports: {}}; + + var bn = {exports: {}}; + + (function (module) { + (function (module, exports) { + + // 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 = require('buffer').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) ; 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); + }; + })(module, commonjsGlobal); + }(bn)); + + var elliptic = {}; + + var name = "elliptic"; + var version$1 = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0 = { + name: name, + version: version$1, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; + + var utils$n = {}; + + var minimalisticAssert = assert$f; + + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } + + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; + + var utils$m = {}; + + (function (exports) { + + 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; + }; + }(utils$m)); + + (function (exports) { + + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; + + 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; + }(utils$n)); + + var brorand = {exports: {}}; + + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; + } + brorand.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$3 = require('crypto'); + if (typeof crypto$3.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$3.randomBytes(n); + }; + } catch (e) { + } + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); + } + } + var base = 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$e(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$e(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]; + 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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; + }; + + var inherits$c = {exports: {}}; + + var inherits_browser = {exports: {}}; + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } + + try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + inherits$c.exports = util.inherits; + } catch (e) { + /* istanbul ignore next */ + inherits$c.exports = inherits_browser.exports; + } + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$b = inherits$c.exports; + var Base$2 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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$b(ShortCurve, Base$2); + var short = 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$7(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$7(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$d(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$7(vec.a, 16), + b: new BN$7(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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$b(Point$2, Base$2.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.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$2.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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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$b(JPoint, Base$2.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$7(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; + }; + + var BN$6 = bn.exports; + var inherits$a = inherits$c.exports; + var Base$1 = base; + + var utils$j = utils$n; + + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); + + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$a(MontCurve, Base$1); + var mont = 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$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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$a(Point$1, Base$1.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); + }; + + Point$1.prototype.precompute = function precompute() { + // No-op + }; + + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; + + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point$1.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$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$9 = inherits$c.exports; + var Base = base; + + var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$9(EdwardsCurve, Base); + var edwards = 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$5(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$5(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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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$9(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; + + (function (exports) { + + var curve = exports; + + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); + + var curves$2 = {}; + + var hash$3 = {}; + + var utils$h = {}; + + var assert$b = minimalisticAssert; + var inherits$8 = inherits$c.exports; + + utils$h.inherits = inherits$8; + + 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; + } + utils$h.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.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; + } + utils$h.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.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; + } + utils$h.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.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; + } + utils$h.split32 = split32; + + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; + + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; + + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; + + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; + + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; + + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; + + function sum64$1(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; + } + utils$h.sum64 = sum64$1; + + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; + + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; + + function sum64_4_hi$1(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; + } + utils$h.sum64_4_hi = sum64_4_hi$1; + + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; + + function sum64_5_hi$1(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; + } + utils$h.sum64_5_hi = sum64_5_hi$1; + + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; + + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; + + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; + + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; + + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; + + var common$5 = {}; + + var utils$g = utils$h; + var assert$a = minimalisticAssert; + + function BlockHash$4() { + 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; + } + common$5.BlockHash = BlockHash$4; + + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); + + return this._digest(enc); + }; + + BlockHash$4.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; + }; + + var sha$2 = {}; + + var common$4 = {}; + + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; + + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); + } + common$4.ft_1 = ft_1$1; + + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; + + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + common$4.maj32 = maj32$1; + + function p32(x, y, z) { + return x ^ y ^ z; + } + common$4.p32 = p32; + + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$4.s0_256 = s0_256$1; + + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$4.s1_256 = s1_256$1; + + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + common$4.g0_256 = g0_256$1; + + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + common$4.g1_256 = g1_256$1; + + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; + + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; + + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; + + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); + } + + utils$e.inherits(SHA1, BlockHash$3); + var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; + + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; + + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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$2 = common$2.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$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; + + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; + + SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } + + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; + + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; + + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; + + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; + + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; + + var BlockHash$1 = common$1.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$2() { + if (!(this instanceof SHA512$2)) + return new SHA512$2(); + + BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); + var _512 = SHA512$2; + + SHA512$2.blockSize = 1024; + SHA512$2.outSize = 512; + SHA512$2.hmacStrength = 192; + SHA512$2.padLength = 128; + + SHA512$2.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$2.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$8(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); + 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); + 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$2.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.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; + } + + var utils$a = utils$h; + + var SHA512$1 = _512; + + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512$1.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; + } + utils$a.inherits(SHA384, SHA512$1); + var _384 = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); + }; + + sha$2.sha1 = _1; + sha$2.sha224 = _224; + sha$2.sha256 = _256; + sha$2.sha384 = _384; + sha$2.sha512 = _512; + + var ripemd = {}; + + var utils$9 = utils$h; + var common = common$5; + + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; + var BlockHash = common.BlockHash; + + function RIPEMD160$1() { + if (!(this instanceof RIPEMD160$1)) + return new RIPEMD160$1(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; + } + utils$9.inherits(RIPEMD160$1, BlockHash); + ripemd.ripemd160 = RIPEMD160$1; + + RIPEMD160$1.blockSize = 512; + RIPEMD160$1.outSize = 160; + RIPEMD160$1.hmacStrength = 192; + RIPEMD160$1.padLength = 64; + + RIPEMD160$1.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$4(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$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$9.toHex32(this.h, 'little'); + else + return utils$9.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$4(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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); + } + var hmac = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(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); + }; + + (function (exports) { + var hash = exports; + + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha$2; + hash.ripemd = ripemd; + hash.hmac = hmac; + + // 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; + }(hash$3)); + + (function (exports) { + + var curves = exports; + + var hash = hash$3; + var curve$1 = curve; + var utils = utils$n; + + var assert = utils.assert; + + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.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 = require('./precomputed/secp256k1'); + } 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, + ], + }); + }(curves$2)); + + var hash$2 = hash$3; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; + + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; + + HmacDRBG$1.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$1.prototype._hmac = function hmac() { + return new hash$2.hmac(this.hash, this.K); + }; + + HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); + + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG$1.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$7.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$7.encode(res, enc); + }; + + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; + + function KeyPair$4(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); + } + var key$1 = KeyPair$4; + + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; + + KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + var signature$1 = Signature$3; + + 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$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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$3(r); + this.s = new BN$3(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$3.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$5.encode(res, enc); + }; + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); + }; + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); + }; + + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; + + EC$1.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(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + + EC$1.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$1.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$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); + } + + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; + + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; + + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; + + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; + + var key = KeyPair$2; + + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.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$1(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes$1(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + 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$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + var signature = Signature$1; + + var hash$1 = hash$3; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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$1.sha512; + } + + var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = createHmac$2; + + const ONE1 = Buffer$g.alloc(1, 1); + const ZERO1 = Buffer$g.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$g.alloc(32, 0); + let v = Buffer$g.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; + } + + return T + } + + var rfc6979 = deterministicGenerateK$1; + + const BN = bn.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer$g.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$g.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$g.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 + } + + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false + + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true + } + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false + } + + function __isPointCompressed (p) { + return p[0] !== 0x04 + } + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) + } + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 + } + + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } + + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$g, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$g.from(P._encode(compressed)) } + + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) + } + + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) + } + + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + + const compressed = assumeCompression(__compressed, p); + + return getEncoded(pp, compressed) + } + + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) + } + + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null + + return getEncoded(qq, compressed) + } + + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function sign (hash, x) { + return __sign(hash, x) + } + + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) + } + + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); + + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); + + if (Q.isInfinity()) return false + + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer$g.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer + } + + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) + } + + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign, + signWithEntropy, + verify + }; + + try { + tinySecp256k1.exports = require('./native'); + } catch (err) { + tinySecp256k1.exports = js; + } + + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); + } + + var native$1 = types$c; + + var native = native$1; + + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } + + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); + } + } + + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' + } + + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') + } + + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); + + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + } + + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } + + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); + } + + captureStackTrace(e); + return e + } + + var errors$1 = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors$1; + + function _Buffer (value) { + return isBuffer(value) + } + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors$1; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str + }; + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; + } + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) }; + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected }; + + return _value + } + }; + + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; + + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) + } + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce$b(compile(type), value, strict) + } + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } + } + + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$g(compressed ? 34 : 33); + + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result + } + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) + } + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw + }; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$2 = crypto$4; + const bs58check$3 = bs58check$5; + const ecc$6 = tinySecp256k1.exports; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); + } + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; + } + get depth() { + return this.__DEPTH; + } + get index() { + return this.__INDEX; + } + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; + } + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; + } + get privateKey() { + return this.__D; + } + get identifier() { + return crypto$2.hash160(this.publicKey); + } + get fingerprint() { + return this.identifier.slice(0, 4); + } + get compressed() { + return true; + } + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; + } + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$g.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$g.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$2.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$g.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); + } + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); + } + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) + } + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } + return hd; + } + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$2.hmacSHA512(Buffer$g.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; + + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; + + var address$1 = {}; + + var networks$3 = {}; + + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + + var payments$4 = {}; + + var embed = {}; + + var script$1 = {}; + + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$g.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { + return ( + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); + } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$e = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } + + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + } + } + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$e.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature + } + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$g.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$g.concat([ZERO$1, x], 1 + x.length); + return x; + } + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$g.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$g.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$g.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$g.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); + } + + return size + } + + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; + + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; + + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; + + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; + + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + + number = buffer.readUInt32LE(offset + 1); + size = 5; + } + + return { + opcode: opcode, + number: number, + size: size + } + } + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; + + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; + } + + var map_1 = map; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = tinySecp256k1.exports; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); + } + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); + } + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); + } + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; + } + function chunksIsBuffer(buf) { + return isBuffer(buf); + } + function chunksIsArray(buf) { + return types.Array(buf); + } + function singleChunkIsBuffer(buf) { + return isBuffer(buf); + } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$g.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; + } + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; + } + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); + } + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$g.from(chunkStr, 'hex'); + }), + ); + } + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$g.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); + } + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); + } + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; + } + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); + + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); + } + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; + } + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); + } + embed.p2data = p2data; + + var p2ms$3 = {}; + + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = tinySecp256k1.exports; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + + var p2pk$3 = {}; + + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = tinySecp256k1.exports; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); + } + p2pk$3.p2pk = p2pk$2; + + var p2pkh$4 = {}; + + var crypto$1 = {}; + + Object.defineProperty(crypto$1, '__esModule', { value: true }); + const createHash = createHash$3; + function ripemd160$2(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } + } + crypto$1.ripemd160 = ripemd160$2; + function sha1$1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$1.sha1 = sha1$1; + function sha256$2(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$1.sha256 = sha256$2; + function hash160$1(buffer) { + return ripemd160$2(sha256$2(buffer)); + } + crypto$1.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$2(sha256$2(buffer)); + } + crypto$1.hash256 = hash256$1; + + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$1; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = tinySecp256k1.exports; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$g.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$g.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2pkh$4.p2pkh = p2pkh$3; + + var p2sh$1 = {}; + + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$1; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; + } + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); + return { + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$g.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$g.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); + } + p2sh$1.p2sh = p2sh; + + var p2wpkh$2 = {}; + + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk + } + + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + + return result + } + + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' + + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } + + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) + } + + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result + } + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } + + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$1; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = tinySecp256k1.exports; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$g.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$g.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$g.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2wpkh$2.p2wpkh = p2wpkh$1; + + var p2wsh$1 = {}; + + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$1; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = tinySecp256k1.exports; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$g.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + function chunkHasUncompressedPubkey(chunk) { + if ( + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; + } + } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$g.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$g.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$g.from(data), + }; + } + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$g.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); + } + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); + } + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } + } + throw new Error(address + ' has no matching Script'); + } + address$1.toOutputScript = toOutputScript; + + var ecpair = {}; + + var randombytes = require$$0__default["default"].randomBytes; + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = tinySecp256k1.exports; + const randomBytes = randombytes; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$g.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer$d = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer$d.allocUnsafe(encodingLength$1(number)); + if (!Buffer$d.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; + } + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer$d.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number + } + } + + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$g.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; + } + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; + } + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$1; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$g.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$g.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$g.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$g.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$g.from(hex, 'hex'), false); + } + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer$g.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$g.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$g.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$g.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$g.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$g.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$g.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$g.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$g.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$g.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; + } + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$1; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(Buffer$g.from(hex, 'hex')); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$g.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$g.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$g.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$g && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$g && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); + } + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$g.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } + } + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); + } + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); + } + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$g.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$g.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$g.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); + } + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); + } + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$g.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; + } + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$g.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; + } + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); + } + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; + } + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$g.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; + } + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); + } + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); + } + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$g.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; + } + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); + } + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; + } + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$g.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$g.concat([head, pSig.pubkey]), + value: pSig.signature, + }; + } + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); + } + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$g.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer$g.from(data, 'utf8'), + }; + } + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); + } + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$g.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$g.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; + } + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; + } + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; + } + sighashType$1.canAdd = canAdd$1; + + var witnessUtxo$1 = {}; + + var tools = {}; + + var varint$1 = {}; + + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); + } + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$g.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); + } + return buffer; + } + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; + + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$g.from([0])); + return Buffer$g.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$g.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; + + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$g.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$g.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; + + var bip32Derivation$1 = {}; + + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer$g.from([TYPE_BYTE]); + const key = Buffer$g.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$g.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; + } + bip32Derivation$1.makeConverter = makeConverter$2; + + var checkPubkey$1 = {}; + + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } + } + checkPubkey$1.makeChecker = makeChecker; + + var redeemScript$1 = {}; + + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$g.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + redeemScript$1.makeConverter = makeConverter$1; + + var witnessScript$1 = {}; + + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$g.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + witnessScript$1.makeConverter = makeConverter; + + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; + + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$g.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + + var toBuffer = {}; + + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$g.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$g.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$g.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); + } + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); + }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; + + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); + + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); + } + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; + } + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; + } + + var utils = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; + } + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; + } + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } + } + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; + } + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; + } + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); + } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; + } + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$g.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer$g.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$1; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + static fromBase64(data, opts = {}) { + const buffer = Buffer$g.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer$g.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); + } + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); + } + return results.every(res => res === true); + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } + } + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$g.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$g.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + throws = true; + } + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); + } + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); + } + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$g.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; + } + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; + } + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; + } + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$g.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$g.concat([buffer, Buffer$g.from(slice)]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$g.concat([buffer, Buffer$g.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } + + var transaction_builder = {}; + + var classify$1 = {}; + + var multisig$1 = {}; + + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); + } + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; + }; + + var output$e = {}; + + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; + }; + + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; + + var nulldata = {}; + + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; + }; + const output$c = { check: check$b }; + nulldata.output = output$c; + + var pubkey = {}; + + var input$9 = {}; + + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; + }; + + var output$b = {}; + + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; + }; + + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; + + var pubkeyhash = {}; + + var input$7 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; + }; + + var output$9 = {}; + + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; + }; + + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; + + var scripthash = {}; + + var input$5 = {}; + + var output$7 = {}; + + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; + + var output$6 = {}; + + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); + } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; + + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); + } + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; + } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; + + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); + } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; + + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; + + var witnesscommitment = {}; + + var output$3 = {}; + + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$g.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); + } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$g.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; + + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; + + var witnesspubkeyhash = {}; + + var input$3 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; + + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; + + var witnessscripthash = {}; + + var input$1 = {}; + + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; + + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; + + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; + + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$1; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); + } + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); + } + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, + }); + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; + } + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; + } + this.__USE_LOW_R = setting; + return setting; + } + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); + } + this.__TX.locktime = locktime; + } + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; + } + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$g.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); + } + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); + } + build() { + return this.__build(false); + } + buildIncomplete() { + return this.__build(true); + } + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); + } + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } + prevOutType = expanded.type; + } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; + } + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } + } + return tx; + } + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); + } + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); + } + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; + } + } + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; + } + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; + } + } + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); + } + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; + } + } + return { type }; + } + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, + }); + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); + } + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); + } + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); + } + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + } + } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); + } + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; + } + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); + } + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); + } + if (keyPair === undefined) { + throw new Error('sign requires keypair'); + } + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); + } + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } + + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$1; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop$2() {} + + var on = noop$2; + var addListener = noop$2; + var once$2 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once$2, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + const debug$4 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$4; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$3 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } + + debug$3('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$3('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self + } + + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted + } + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } + } + + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } + } + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$2('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$2 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$2('comp', comp, options); + comp = replaceCarets(comp, options); + debug$2('caret', comp); + comp = replaceTildes(comp, options); + debug$2('tildes', comp); + comp = replaceXRanges(comp, options); + debug$2('xrange', comp); + comp = replaceStars(comp, options); + debug$2('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$2('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$2('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$2('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$2('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$2('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } + + debug$2('caret return', ret); + return ret + }) + }; + + const replaceXRanges = (comp, options) => { + debug$2('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$2('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$2('xRange return', ret); + + return ret + }) + }; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$2('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; + + const replaceGTE0 = (comp, options) => { + debug$2('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$2(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + }; + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } + } + + debug$1('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug$1('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug$1('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } + } + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug$1 = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true + }; + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; + + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$g.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$g.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$g.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + var readable = {exports: {}}; + + var stream = require$$0__default$2["default"]; + + function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + + function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + var _require$2 = require$$0__default$1["default"], + Buffer$c = _require$2.Buffer; + + var _require2 = require$$1__default["default"], + inspect = _require2.inspect; + + var custom = inspect && inspect.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$c.prototype.copy.call(src, target, offset); + } + + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck$2(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass$2(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$c.alloc(0); + var ret = Buffer$c.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$c.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread$1({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; + }(); + + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); + } else { + nextTick(emitCloseNT, _this); + } + }); + + return this; + } + + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.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(self, err) { + self.emit('error', err); + } + + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } + + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; + + var errors = {}; + + const codes = {}; + + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; + } + + // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + + errors.codes = codes; + + var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; + } + + var state = { + getHighWaterMark: getHighWaterMark$2 + }; + + /** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + + var node = require$$1__default["default"].deprecate; + + var _stream_writable = Writable$1; + // there will be only 2 of these for each stream + + + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ + + /**/ + + + var Duplex$3; + /**/ + + Writable$1.WritableState = WritableState; + /**/ + + var internalUtil = { + deprecate: node + }; + /**/ + + /**/ + + var Stream$1 = stream; + /**/ + + + var Buffer$b = require$$0__default$1["default"].Buffer; + + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$b.from(chunk); + } + + function _isUint8Array$1(obj) { + return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array$1; + } + + var destroyImpl$1 = destroy_1; + + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; + + var _require$codes$3 = errors.codes, + ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + + inherits$c.exports(Writable$1, Stream$1); + + function nop() {} + + function WritableState(options, stream, isDuplex) { + Duplex$3 = Duplex$3 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + + + var realHasInstance; + + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$1, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$1) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } + + function Writable$1(options) { + Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$3; + if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. + + + Writable$1.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; + + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + + + function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } + + return true; + } + + Writable$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$b.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; + + Writable$1.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$b.from(chunk, encoding); + } + + return chunk; + } + + Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + + + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } // if there's something in the buffer waiting, then process it + + + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; + + Writable$1.prototype._writev = null; + + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + + function prefinish$1(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish$1(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; + } + + Object.defineProperty(Writable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl$1.destroy; + Writable$1.prototype._undestroy = destroyImpl$1.undestroy; + + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; + + /**/ + + var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; + }; + /**/ + + + var _stream_duplex = Duplex$2; + + var Readable$1 = _stream_readable; + + var Writable = _stream_writable; + + inherits$c.exports(Duplex$2, Readable$1); + + { + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; + } + } + + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); + Readable$1.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } + } + + Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer + + function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + Object.defineProperty(Duplex$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + var string_decoder = {}; + + /**/ + + var Buffer$a = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$a.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$a.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. + string_decoder.StringDecoder = StringDecoder$1; + function StringDecoder$1(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$a.allocUnsafe(nb); + } + + StringDecoder$1.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$1.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$1.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$1.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); + 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) : ''; + } + + var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; + + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; + } + + function noop$1() {} + + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } + + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } + + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty$1(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty$1(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; + + var async_iterator = createReadableStreamAsyncIterator$1; + + 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$3(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); }); }; } + + 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; + + function from$1(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator$3(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; + } + + var from_1 = from$1; + + var _stream_readable = Readable; + /**/ + + var Duplex$1; + /**/ + + Readable.ReadableState = ReadableState; + /**/ + + require$$0__default$3["default"].EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + /**/ + + + var Stream = stream; + /**/ + + + var Buffer$9 = require$$0__default$1["default"].Buffer; + + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer(chunk) { + return Buffer$9.from(chunk); + } + + function _isUint8Array(obj) { + return Buffer$9.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ + + + var debugUtil = require$$1__default["default"]; + + var debug; + + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function debug() {}; + } + /**/ + + + var BufferList = buffer_list; + + var destroyImpl = destroy_1; + + var _require = state, + getHighWaterMark = _require.getHighWaterMark; + + var _require$codes$2 = errors.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + + var StringDecoder; + var createReadableStreamAsyncIterator; + var from; + + inherits$c.exports(Readable, Stream); + + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState(options, stream, isDuplex) { + Duplex$1 = Duplex$1 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + Duplex$1 = Duplex$1 || _stream_duplex; + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$1; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); + } + + Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + + + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer$9.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() + + + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$9.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); + } + + function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; + } + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. + + + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB + + + var MAX_HWM = 0x40000000; + + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; + } // you can override either this method, or the async _read(n) below. + + + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; + }; + + function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + + + function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_, stream); + } + } + + function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + + + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something + + + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + nextTick(nReadingNextTick, this); + } + } + } + + return res; + }; + + Readable.prototype.addListener = Readable.prototype.on; + + Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + + + Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + + + Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } + + return createReadableStreamAsyncIterator(this); + }; + } + + Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + + if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = from_1; + } + + return from(Readable, iterable, opts); + }; + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; + } + + var _stream_transform = Transform$2; + + var _require$codes$1 = errors.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + + var Duplex = _stream_duplex; + + inherits$c.exports(Transform$2, Duplex); + + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform$2(options) { + if (!(this instanceof Transform$2)) return new Transform$2(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); + } + + function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + + Transform$2.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + + + Transform$2.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + + Transform$2.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + + + Transform$2.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform$2.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + + var _stream_passthrough = PassThrough; + + var Transform$1 = _stream_transform; + + inherits$c.exports(PassThrough, Transform$1); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform$1.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + var eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + + var _require$codes = errors.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } + + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + + function call(fn) { + fn(); + } + + function pipe(from, to) { + return from.pipe(to); + } + + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + + var pipeline_1 = pipeline; + + (function (module, exports) { + var Stream = require$$0__default$2["default"]; + { + exports = module.exports = _stream_readable; + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + } + }(readable, readable.exports)); + + var Buffer$8 = safeBuffer.exports.Buffer; + var Transform = readable.exports.Transform; + var inherits$7 = inherits$c.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$8.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } + + function HashBase$1 (blockSize) { + Transform.call(this); + + this._block = Buffer$8.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + + this._finalized = false; + } + + inherits$7(HashBase$1, Transform); + + HashBase$1.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$1.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$1.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$8.isBuffer(data)) data = Buffer$8.from(data, encoding); + + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } + + return this + }; + + HashBase$1.prototype._update = function () { + throw new Error('_update is not implemented') + }; + + HashBase$1.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; + + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); + + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; + + return digest + }; + + HashBase$1.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; + + var hashBase = HashBase$1; + + var Buffer$7 = require$$0__default$1["default"].Buffer; + var inherits$6 = inherits$c.exports; + var HashBase = hashBase; + + var ARRAY16 = new Array(16); + + var zl = [ + 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 zr = [ + 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 sl = [ + 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 sr = [ + 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 + ]; + + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + + function RIPEMD160 () { + HashBase.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } + + inherits$6(RIPEMD160, HashBase); + + RIPEMD160.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; + + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } + + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; + + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } + + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; + + RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$7.alloc ? Buffer$7.alloc(20) : new Buffer$7(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + var ripemd160$1 = RIPEMD160; + + var sha_js = {exports: {}}; + + var Buffer$6 = safeBuffer.exports.Buffer; + + // prototype class for hash functions + function Hash$6 (blockSize, finalSize) { + this._block = Buffer$6.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + + Hash$6.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$6.from(data, enc); + } + + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } + } + + this._len += length; + return this + }; + + Hash$6.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; + + this._block[rem] = 0x80; + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + + var bits = this._len * 8; + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; + + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash + }; + + Hash$6.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; + + var hash = Hash$6; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits$5 = inherits$c.exports; + var Hash$5 = hash; + var Buffer$5 = safeBuffer.exports.Buffer; + + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; + + Hash$5.call(this, 64, 56); + } + + inherits$5(Sha, Hash$5); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } + + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha.prototype._hash = function () { + var H = Buffer$5.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha$1 = Sha; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits$4 = inherits$c.exports; + var Hash$4 = hash; + var Buffer$4 = safeBuffer.exports.Buffer; + + var K$2 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$4.call(this, 64, 56); + } + + inherits$4(Sha1, Hash$4); + + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha1.prototype._hash = function () { + var H = Buffer$4.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha1 = Sha1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$3 = inherits$c.exports; + var Hash$3 = hash; + var Buffer$3 = safeBuffer.exports.Buffer; + + var K$1 = [ + 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 W$3 = new Array(64); + + function Sha256$1 () { + this.init(); + + this._w = W$3; // new Array(64) + + Hash$3.call(this, 64, 56); + } + + inherits$3(Sha256$1, Hash$3); + + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; + + return this + }; + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256$1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; + + Sha256$1.prototype._hash = function () { + var H = Buffer$3.allocUnsafe(32); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + + return H + }; + + var sha256$1 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$2 = inherits$c.exports; + var Sha256 = sha256$1; + var Hash$2 = hash; + var Buffer$2 = safeBuffer.exports.Buffer; + + var W$2 = new Array(64); + + function Sha224 () { + this.init(); + + this._w = W$2; // new Array(64) + + Hash$2.call(this, 64, 56); + } + + inherits$2(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this + }; + + Sha224.prototype._hash = function () { + var H = Buffer$2.allocUnsafe(28); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H + }; + + var sha224 = Sha224; + + var inherits$1 = inherits$c.exports; + var Hash$1 = hash; + var Buffer$1 = safeBuffer.exports.Buffer; + + 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 W$1 = new Array(160); + + function Sha512 () { + this.init(); + this._w = W$1; + + Hash$1.call(this, 128, 112); + } + + inherits$1(Sha512, Hash$1); + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this + }; + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } + + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } + + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } + + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } + + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w; + + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); + + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; + + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; + + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + + W[i] = Wih; + W[i + 1] = Wil; + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; + + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); + + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j]; + var Kil = K[j + 1]; + + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); + + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } + + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; + + Sha512.prototype._hash = function () { + var H = Buffer$1.allocUnsafe(64); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + + return H + }; + + var sha512 = Sha512; + + var inherits = inherits$c.exports; + var SHA512 = sha512; + var Hash = hash; + var Buffer = safeBuffer.exports.Buffer; + + var W = new Array(160); + + function Sha384 () { + this.init(); + this._w = W; + + Hash.call(this, 128, 112); + } + + inherits(Sha384, SHA512); + + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; + + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; + + return this + }; + + Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H + }; + + var sha384 = Sha384; + + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() + }; + + exports$1.sha = sha$1; + exports$1.sha1 = sha1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$1; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; + + var sha = sha_js.exports; + + function hashPublicKey(buffer) { + return new ripemd160$1().update(sha("sha256").update(buffer).digest()).digest(); + } + + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$3(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$3(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$g.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$g.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$3(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$g.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$g.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$g.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$g.concat([ + Buffer$g.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$g.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$3(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$g.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$g.concat([Buffer$g.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$3(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$g.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$g.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$g.concat([Buffer$g.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$g.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$g.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$2([node.parent.rightChild.hash], __read$2(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$2([node.parent.leftChild.hash], __read$2(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$g.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$g.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$g.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$g.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$g.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$2(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); + }; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); + }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + }; + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); + }; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$g.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$g.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); + } + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; + } + }; + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$g.from(k.substring(2), "hex")); + } + }); + return result; + }; + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$g.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); + }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$g.from([])); + this.globalMap.set(key.toString(), value); + }; + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); + }; + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); + }; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); + }; + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$4({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$g.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); + }; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; + } + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$g.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer$g.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$g.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + var b = Buffer$g.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); + } + } + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); + } + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); + } + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$g.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$g.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$g.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$g.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$g.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$g.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$g.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$g.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$g.concat([ + inputBuffer, + input.prevout, + Buffer$g.from([0x00]), + input.sequence, + ]) + : Buffer$g.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$g.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$g.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$g.alloc(0), + transaction.extraData || Buffer$g.alloc(0), + ]); + } + return Buffer$g.concat([ + transaction.version, + timestamp ? timestamp : Buffer$g.alloc(0), + transaction.nVersionGroupId || Buffer$g.alloc(0), + useWitness ? Buffer$g.from("0001", "hex") : Buffer$g.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } + /** + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. + */ + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; + } + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$b(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$b(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$b(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$b(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$g.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); + }; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$b(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$g.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); + }; + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$b(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$g.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); + }; + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$b(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); + }); + }; + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$b(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$g.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); + }; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$b(this, void 0, void 0, function () { + var sigs; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$g.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); + }); + }; + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$1 = 0; + var subscribers$1 = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch$1(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen$1 = function (cb) { + subscribers$1.push(cb); + return function () { + var i = subscribers$1.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; + subscribers$1.pop(); + } + }; + }; + function dispatch$1(log) { + for (var i = 0; i < subscribers$1.length; i++) { + try { + subscribers$1[i](log); + } + catch (e) { + console.error(e); + } + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen$1; + } + + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$a(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$a(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$3({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var invariant_1 = invariant; + + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$9(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$g.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$g.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$9(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$9(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$9(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$9(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$g.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$g.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$g.concat([ + transaction.version, + transaction.timestamp || Buffer$g.alloc(0), + transaction.nVersionGroupId || Buffer$g.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$g.compare(version, Buffer$g.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$g.from([0x00]) + : Buffer$g.alloc(0); + data = Buffer$g.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$g.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$g.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$g.concat([ + output.amount, + isDecred ? Buffer$g.from([0x00, 0x00]) : Buffer$g.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$g.concat(endData); + extraPart = isDecred + ? data + : Buffer$g.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$g.concat([locktime, extraPart || Buffer$g.alloc(0)]))]; + case 20: + res = _c.sent(); + invariant_1(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$8(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$8(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$g.concat([ + transaction.version, + transaction.timestamp || Buffer$g.alloc(0), + transaction.nVersionGroupId || Buffer$g.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$4(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$g.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$g.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$g.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$g.from([0x00]); + } + } + data = Buffer$g.concat([ + prefix, + inputValue, + isDecred ? Buffer$g.from([0x00]) : Buffer$g.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$g.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha("sha256") + .update(sha("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$g.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$g.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$g.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$g.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$g.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$g.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$g.from([0x00, 0x00, 0x00, 0x00]), + Buffer$g.from([sigHashType]), + ]) + : Buffer$g.concat([ + pathsBuffer, + Buffer$g.from([0x00]), + lockTimeBuffer, + Buffer$g.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$g.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$7(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$7(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$6(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + invariant_1(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } + + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$5(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$2(__assign$2({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$g.alloc(0); + nullPrevout = Buffer$g.alloc(0); + defaultVersion = Buffer$g.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$g.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$g.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$g.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$g.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$g.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$g.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$g.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$g.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$g.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$g.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$g.concat([ + Buffer$g.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$g.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$g.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$g.concat([ + Buffer$g.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$g.alloc(1); + keySize = Buffer$g.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$g.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$g.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$g.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$g.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$g.concat([ + Buffer$g.from("02", "hex"), + Buffer$g.from([signatures[i].length]), + signatures[i], + Buffer$g.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$g.concat([witness, tmpScriptData]); + } + result = Buffer$g.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$g.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$g.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$g.alloc(0), + targetTransaction.extraData || Buffer$g.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$g.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$g.concat([ + decredWitness_1, + Buffer$g.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$g.from([0x00, 0x00, 0x00, 0x00]), + Buffer$g.from([0xff, 0xff, 0xff, 0xff]), + Buffer$g.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$g.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } + + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$4(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$4(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$g.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$4(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$g.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$g.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } + + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$3(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$3(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$1(__assign$1({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$g.alloc(0); + nullPrevout = Buffer$g.alloc(0); + defaultVersion = Buffer$g.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$g.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$g.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$g.from(trustedInput, "hex") + : Buffer$g.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$g.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$g.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$1(__assign$1({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } + + var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$2(this, void 0, void 0, function () { + var res; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$2(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$2(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$g.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$g.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$g.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign(__assign({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$g.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$g.concat([ + Buffer$g.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$g.concat([ + asBufferUInt32BE(version), + Buffer$g.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$g.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$1().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$g.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$1(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$1([], __read$1(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$1([], __read$1(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$1([], __read$1(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$g.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$g.from(request.subarray(1))); + this.progressCallback(); + return Buffer$g.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$g.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$g.from([known_preimage[i]])); + } + } + return Buffer$g.concat([ + preimage_len_varint, + Buffer$g.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray([], __read(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$g.concat(__spreadArray([ + mt.getLeafHash(leaf_index), + Buffer$g.from([proof.length]), + Buffer$g.from([n_response_elements]) + ], __read(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$g.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$g.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$g.concat([Buffer$g.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$g.concat(__spreadArray([ + Buffer$g.from([n_returned_elements]), + Buffer$g.from([element_len]) + ], __read(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$1(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } + } + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$1(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$g.concat([Buffer$g.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); + + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$1(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$1(this, void 0, void 0, function () { + var response; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$g.concat([ + Buffer$g.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$1(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$g.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$g.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$g.concat([ + Buffer$g.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$g.alloc(32, 0), + Buffer$g.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$1(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$1(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$g.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$g.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$g.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$1(this, void 0, void 0, function () { + return __generator$1(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$g.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$g.alloc(0); + var nExpiryHeight = Buffer$g.alloc(0); + var nVersionGroupId = Buffer$g.alloc(0); + var extraData = Buffer$g.alloc(0); + var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); + var transaction = Buffer$g.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$g.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$g.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$g.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$g.from([0x02, 0x00, 0x00, 0x00])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$g.alloc(0); + var tree = Buffer$g.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } + + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@backpacker69/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + var TransportWebUSB$2 = {}; + + var Transport$1 = {}; + + var lib$2 = {}; + + var helpers = {}; + + Object.defineProperty(helpers, "__esModule", { + value: true + }); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + /* eslint-disable no-continue */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + + var errorClasses = {}; + var deserializers = {}; + + helpers.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { + deserializers[name] = deserializer; + }; + + var createCustomErrorClass = helpers.createCustomErrorClass = function createCustomErrorClass(name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + // $FlowFixMe + C.prototype = new Error(); + + errorClasses[name] = C; + // $FlowFixMe we can't easily type a subset of Error for now... + return C; + }; + + // inspired from https://github.com/programble/errio/blob/master/index.js + helpers.deserializeError = function deserializeError(object) { + if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } catch (e) { + // nothing + } + + var error = void 0; + if (typeof object.name === "string") { + var _object = object, + name = _object.name; + + var des = deserializers[name]; + if (des) { + error = des(object); + } else { + var _constructor = name === "Error" ? Error : errorClasses[name]; + + if (!_constructor) { + console.warn("deserializing an unknown class '" + name + "'"); + _constructor = createCustomErrorClass(name); + } + + error = Object.create(_constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } else { + error = new Error(object.message); + } + + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + helpers.serializeError = function serializeError(value) { + if (!value) return value; + if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var to = {}; + seen.push(from); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var key = _step.value; + + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + Object.defineProperty(lib$2, "__esModule", { + value: true + }); + lib$2.StatusCodes = lib$2.DBNotReset = lib$2.DBWrongPassword = lib$2.NoDBPathGiven = lib$2.FirmwareOrAppUpdateRequired = lib$2.LedgerAPI5xx = lib$2.LedgerAPI4xx = lib$2.GenuineCheckFailed = lib$2.PairingFailed = lib$2.SyncError = lib$2.FeeTooHigh = lib$2.FeeRequired = lib$2.FeeNotLoaded = lib$2.CantScanQRCode = lib$2.ETHAddressNonEIP = lib$2.WrongAppForCurrency = lib$2.WrongDeviceForAccount = lib$2.WebsocketConnectionFailed = lib$2.WebsocketConnectionError = lib$2.DeviceShouldStayInApp = lib$2.TransportWebUSBGestureRequired = lib$2.TransportInterfaceNotAvailable = lib$2.TransportOpenUserCancelled = lib$2.UserRefusedOnDevice = lib$2.UserRefusedAllowManager = lib$2.UserRefusedFirmwareUpdate = lib$2.UserRefusedAddress = lib$2.UserRefusedDeviceNameChange = lib$2.UpdateYourApp = lib$2.UnavailableTezosOriginatedAccountSend = lib$2.UnavailableTezosOriginatedAccountReceive = lib$2.RecipientRequired = lib$2.MCUNotGenuineToDashboard = lib$2.UnexpectedBootloader = lib$2.TimeoutTagged = lib$2.RecommendUndelegation = lib$2.RecommendSubAccountsToEmpty = lib$2.PasswordIncorrectError = lib$2.PasswordsDontMatchError = lib$2.GasLessThanEstimate = lib$2.NotSupportedLegacyAddress = lib$2.NotEnoughGas = lib$2.NoAccessToCamera = lib$2.NotEnoughBalanceBecauseDestinationNotCreated = lib$2.NotEnoughSpendableBalance = lib$2.NotEnoughBalanceInParentAccount = lib$2.NotEnoughBalanceToDelegate = lib$2.NotEnoughBalance = lib$2.NoAddressesFound = lib$2.NetworkDown = lib$2.ManagerUninstallBTCDep = lib$2.ManagerNotEnoughSpaceError = lib$2.ManagerFirmwareNotEnoughSpaceError = lib$2.ManagerDeviceLockedError = lib$2.ManagerAppDepUninstallRequired = lib$2.ManagerAppDepInstallRequired = lib$2.ManagerAppRelyOnBTCError = lib$2.ManagerAppAlreadyInstalledError = lib$2.LedgerAPINotAvailable = lib$2.LedgerAPIErrorWithMessage = lib$2.LedgerAPIError = lib$2.UnknownMCU = lib$2.LatestMCUInstalledError = lib$2.InvalidAddressBecauseDestinationIsAlsoSource = lib$2.InvalidAddress = lib$2.InvalidXRPTag = lib$2.HardResetFail = lib$2.FeeEstimationFailed = lib$2.EthAppPleaseEnableContractData = lib$2.EnpointConfigError = lib$2.DisconnectedDeviceDuringOperation = lib$2.DisconnectedDevice = lib$2.DeviceSocketNoBulkStatus = lib$2.DeviceSocketFail = lib$2.DeviceNameInvalid = lib$2.DeviceHalted = lib$2.DeviceInOSUExpected = lib$2.DeviceOnDashboardUnexpected = lib$2.DeviceOnDashboardExpected = lib$2.DeviceNotGenuineError = lib$2.DeviceGenuineSocketEarlyClose = lib$2.DeviceAppVerifyNotSupported = lib$2.CurrencyNotSupported = lib$2.CashAddrNotSupported = lib$2.CantOpenDevice = lib$2.BtcUnmatchedApp = lib$2.BluetoothRequired = lib$2.AmountRequired = lib$2.AccountNotSupported = lib$2.AccountNameRequiredError = lib$2.addCustomErrorDeserializer = lib$2.createCustomErrorClass = lib$2.deserializeError = lib$2.serializeError = undefined; + lib$2.TransportError = TransportError; + lib$2.getAltStatusMessage = getAltStatusMessage; + lib$2.TransportStatusError = TransportStatusError; + + var _helpers = helpers; + + lib$2.serializeError = _helpers.serializeError; + lib$2.deserializeError = _helpers.deserializeError; + lib$2.createCustomErrorClass = _helpers.createCustomErrorClass; + lib$2.addCustomErrorDeserializer = _helpers.addCustomErrorDeserializer; + lib$2.AccountNameRequiredError = (0, _helpers.createCustomErrorClass)("AccountNameRequired"); + lib$2.AccountNotSupported = (0, _helpers.createCustomErrorClass)("AccountNotSupported"); + lib$2.AmountRequired = (0, _helpers.createCustomErrorClass)("AmountRequired"); + lib$2.BluetoothRequired = (0, _helpers.createCustomErrorClass)("BluetoothRequired"); + lib$2.BtcUnmatchedApp = (0, _helpers.createCustomErrorClass)("BtcUnmatchedApp"); + lib$2.CantOpenDevice = (0, _helpers.createCustomErrorClass)("CantOpenDevice"); + lib$2.CashAddrNotSupported = (0, _helpers.createCustomErrorClass)("CashAddrNotSupported"); + lib$2.CurrencyNotSupported = (0, _helpers.createCustomErrorClass)("CurrencyNotSupported"); + lib$2.DeviceAppVerifyNotSupported = (0, _helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); + lib$2.DeviceGenuineSocketEarlyClose = (0, _helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); + lib$2.DeviceNotGenuineError = (0, _helpers.createCustomErrorClass)("DeviceNotGenuine"); + lib$2.DeviceOnDashboardExpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); + lib$2.DeviceOnDashboardUnexpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); + lib$2.DeviceInOSUExpected = (0, _helpers.createCustomErrorClass)("DeviceInOSUExpected"); + lib$2.DeviceHalted = (0, _helpers.createCustomErrorClass)("DeviceHalted"); + lib$2.DeviceNameInvalid = (0, _helpers.createCustomErrorClass)("DeviceNameInvalid"); + lib$2.DeviceSocketFail = (0, _helpers.createCustomErrorClass)("DeviceSocketFail"); + lib$2.DeviceSocketNoBulkStatus = (0, _helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); + lib$2.DisconnectedDevice = (0, _helpers.createCustomErrorClass)("DisconnectedDevice"); + lib$2.DisconnectedDeviceDuringOperation = (0, _helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); + lib$2.EnpointConfigError = (0, _helpers.createCustomErrorClass)("EnpointConfig"); + lib$2.EthAppPleaseEnableContractData = (0, _helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); + lib$2.FeeEstimationFailed = (0, _helpers.createCustomErrorClass)("FeeEstimationFailed"); + lib$2.HardResetFail = (0, _helpers.createCustomErrorClass)("HardResetFail"); + lib$2.InvalidXRPTag = (0, _helpers.createCustomErrorClass)("InvalidXRPTag"); + lib$2.InvalidAddress = (0, _helpers.createCustomErrorClass)("InvalidAddress"); + lib$2.InvalidAddressBecauseDestinationIsAlsoSource = (0, _helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); + lib$2.LatestMCUInstalledError = (0, _helpers.createCustomErrorClass)("LatestMCUInstalledError"); + lib$2.UnknownMCU = (0, _helpers.createCustomErrorClass)("UnknownMCU"); + lib$2.LedgerAPIError = (0, _helpers.createCustomErrorClass)("LedgerAPIError"); + lib$2.LedgerAPIErrorWithMessage = (0, _helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); + lib$2.LedgerAPINotAvailable = (0, _helpers.createCustomErrorClass)("LedgerAPINotAvailable"); + lib$2.ManagerAppAlreadyInstalledError = (0, _helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); + lib$2.ManagerAppRelyOnBTCError = (0, _helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); + lib$2.ManagerAppDepInstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); + lib$2.ManagerAppDepUninstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); + lib$2.ManagerDeviceLockedError = (0, _helpers.createCustomErrorClass)("ManagerDeviceLocked"); + lib$2.ManagerFirmwareNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); + lib$2.ManagerNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); + lib$2.ManagerUninstallBTCDep = (0, _helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); + lib$2.NetworkDown = (0, _helpers.createCustomErrorClass)("NetworkDown"); + lib$2.NoAddressesFound = (0, _helpers.createCustomErrorClass)("NoAddressesFound"); + lib$2.NotEnoughBalance = (0, _helpers.createCustomErrorClass)("NotEnoughBalance"); + lib$2.NotEnoughBalanceToDelegate = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); + lib$2.NotEnoughBalanceInParentAccount = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); + lib$2.NotEnoughSpendableBalance = (0, _helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); + lib$2.NotEnoughBalanceBecauseDestinationNotCreated = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); + lib$2.NoAccessToCamera = (0, _helpers.createCustomErrorClass)("NoAccessToCamera"); + lib$2.NotEnoughGas = (0, _helpers.createCustomErrorClass)("NotEnoughGas"); + lib$2.NotSupportedLegacyAddress = (0, _helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); + lib$2.GasLessThanEstimate = (0, _helpers.createCustomErrorClass)("GasLessThanEstimate"); + lib$2.PasswordsDontMatchError = (0, _helpers.createCustomErrorClass)("PasswordsDontMatch"); + lib$2.PasswordIncorrectError = (0, _helpers.createCustomErrorClass)("PasswordIncorrect"); + lib$2.RecommendSubAccountsToEmpty = (0, _helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); + lib$2.RecommendUndelegation = (0, _helpers.createCustomErrorClass)("RecommendUndelegation"); + lib$2.TimeoutTagged = (0, _helpers.createCustomErrorClass)("TimeoutTagged"); + lib$2.UnexpectedBootloader = (0, _helpers.createCustomErrorClass)("UnexpectedBootloader"); + lib$2.MCUNotGenuineToDashboard = (0, _helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); + lib$2.RecipientRequired = (0, _helpers.createCustomErrorClass)("RecipientRequired"); + lib$2.UnavailableTezosOriginatedAccountReceive = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); + lib$2.UnavailableTezosOriginatedAccountSend = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); + lib$2.UpdateYourApp = (0, _helpers.createCustomErrorClass)("UpdateYourApp"); + lib$2.UserRefusedDeviceNameChange = (0, _helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); + lib$2.UserRefusedAddress = (0, _helpers.createCustomErrorClass)("UserRefusedAddress"); + lib$2.UserRefusedFirmwareUpdate = (0, _helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); + lib$2.UserRefusedAllowManager = (0, _helpers.createCustomErrorClass)("UserRefusedAllowManager"); + lib$2.UserRefusedOnDevice = (0, _helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + lib$2.TransportOpenUserCancelled = (0, _helpers.createCustomErrorClass)("TransportOpenUserCancelled"); + lib$2.TransportInterfaceNotAvailable = (0, _helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); + lib$2.TransportWebUSBGestureRequired = (0, _helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); + lib$2.DeviceShouldStayInApp = (0, _helpers.createCustomErrorClass)("DeviceShouldStayInApp"); + lib$2.WebsocketConnectionError = (0, _helpers.createCustomErrorClass)("WebsocketConnectionError"); + lib$2.WebsocketConnectionFailed = (0, _helpers.createCustomErrorClass)("WebsocketConnectionFailed"); + lib$2.WrongDeviceForAccount = (0, _helpers.createCustomErrorClass)("WrongDeviceForAccount"); + lib$2.WrongAppForCurrency = (0, _helpers.createCustomErrorClass)("WrongAppForCurrency"); + lib$2.ETHAddressNonEIP = (0, _helpers.createCustomErrorClass)("ETHAddressNonEIP"); + lib$2.CantScanQRCode = (0, _helpers.createCustomErrorClass)("CantScanQRCode"); + lib$2.FeeNotLoaded = (0, _helpers.createCustomErrorClass)("FeeNotLoaded"); + lib$2.FeeRequired = (0, _helpers.createCustomErrorClass)("FeeRequired"); + lib$2.FeeTooHigh = (0, _helpers.createCustomErrorClass)("FeeTooHigh"); + lib$2.SyncError = (0, _helpers.createCustomErrorClass)("SyncError"); + lib$2.PairingFailed = (0, _helpers.createCustomErrorClass)("PairingFailed"); + lib$2.GenuineCheckFailed = (0, _helpers.createCustomErrorClass)("GenuineCheckFailed"); + lib$2.LedgerAPI4xx = (0, _helpers.createCustomErrorClass)("LedgerAPI4xx"); + lib$2.LedgerAPI5xx = (0, _helpers.createCustomErrorClass)("LedgerAPI5xx"); + lib$2.FirmwareOrAppUpdateRequired = (0, _helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); + + // db stuff, no need to translate + lib$2.NoDBPathGiven = (0, _helpers.createCustomErrorClass)("NoDBPathGiven"); + lib$2.DBWrongPassword = (0, _helpers.createCustomErrorClass)("DBWrongPassword"); + lib$2.DBNotReset = (0, _helpers.createCustomErrorClass)("DBNotReset"); + + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + //$FlowFixMe + TransportError.prototype = new Error(); + + (0, _helpers.addCustomErrorDeserializer)("TransportError", function (e) { + return new TransportError(e.message, e.id); + }); + + var StatusCodes = lib$2.StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { + return StatusCodes[k] === statusCode; + }) || "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + //$FlowFixMe + TransportStatusError.prototype = new Error(); + + (0, _helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { + return new TransportStatusError(e.statusCode); + }); + + Object.defineProperty(Transport$1, "__esModule", { + value: true + }); + Transport$1.getAltStatusMessage = Transport$1.StatusCodes = Transport$1.TransportStatusError = Transport$1.TransportError = undefined; + + var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _events2 = require$$0__default$3["default"]; + + var _events3 = _interopRequireDefault$1(_events2); + + var _errors$2 = lib$2; + + function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + function _asyncToGenerator$2(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + Transport$1.TransportError = _errors$2.TransportError; + Transport$1.TransportStatusError = _errors$2.TransportStatusError; + Transport$1.StatusCodes = _errors$2.StatusCodes; + Transport$1.getAltStatusMessage = _errors$2.getAltStatusMessage; + + /** + */ + + + /** + */ + + + /** + * type: add or remove event + * descriptor: a parameter that can be passed to open(descriptor) + * deviceModel: device info on the model (is it a nano s, nano x, ...) + * device: transport specific device info + */ + + /** + */ + + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport = function () { + function Transport() { + var _this = this; + + _classCallCheck$1(this, Transport); + + this.exchangeTimeout = 30000; + this._events = new _events3.default(); + + this.send = function () { + var _ref = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { + var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer$g.alloc(0); + var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [_errors$2.StatusCodes.OK]; + var response, sw; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!(data.length >= 256)) { + _context.next = 2; + break; + } + + throw new _errors$2.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + + case 2: + _context.next = 4; + return _this.exchange(Buffer$g.concat([Buffer$g.from([cla, ins, p1, p2]), Buffer$g.from([data.length]), data])); + + case 4: + response = _context.sent; + sw = response.readUInt16BE(response.length - 2); + + if (statusList.some(function (s) { + return s === sw; + })) { + _context.next = 8; + break; + } + + throw new _errors$2.TransportStatusError(sw); + + case 8: + return _context.abrupt("return", response); + + case 9: + case "end": + return _context.stop(); + } + } + }, _callee, _this); + })); + + return function (_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; + }(); + + this.exchangeAtomicImpl = function () { + var _ref2 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { + var resolveBusy, busyPromise, res; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!_this.exchangeBusyPromise) { + _context2.next = 2; + break; + } + + throw new _errors$2.TransportError("Transport race condition", "RaceCondition"); + + case 2: + resolveBusy = void 0; + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + + _this.exchangeBusyPromise = busyPromise; + _context2.prev = 5; + _context2.next = 8; + return f(); + + case 8: + res = _context2.sent; + return _context2.abrupt("return", res); + + case 10: + _context2.prev = 10; + + if (resolveBusy) resolveBusy(); + _this.exchangeBusyPromise = null; + return _context2.finish(10); + + case 14: + case "end": + return _context2.stop(); + } + } + }, _callee2, _this, [[5,, 10, 14]]); + })); + + return function (_x7) { + return _ref2.apply(this, arguments); + }; + }(); + + this._appAPIlock = null; + } + + /** + * Statically check if a transport is supported on the user's platform/browser. + */ + + + /** + * List once all available descriptors. For a better granularity, checkout `listen()`. + * @return a promise of descriptors + * @example + * TransportFoo.list().then(descriptors => ...) + */ + + + /** + * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) + * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. + * each listen() call will first emit all potential device already connected and then will emit events can come over times, + * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. + * @param observer is an object with a next, error and complete function (compatible with observer pattern) + * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. + * @example + const sub = TransportFoo.listen({ + next: e => { + if (e.type==="add") { + sub.unsubscribe(); + const transport = await TransportFoo.open(e.descriptor); + ... + } + }, + error: error => {}, + complete: () => {} + }) + */ + + + /** + * attempt to create a Transport instance with potentially a descriptor. + * @param descriptor: the descriptor to open the transport with. + * @param timeout: an optional timeout + * @return a Promise of Transport instance + * @example + TransportFoo.open(descriptor).then(transport => ...) + */ + + + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + + + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + + + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + + + _createClass$1(Transport, [{ + key: "on", + + + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + value: function on(eventName, cb) { + this._events.on(eventName, cb); + } + + /** + * Stop listening to an event on an instance of transport. + */ + + }, { + key: "off", + value: function off(eventName, cb) { + this._events.removeListener(eventName, cb); + } + }, { + key: "emit", + value: function emit(event) { + var _events; + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); + } + + /** + * Enable or not logs of the binary exchange + */ + + }, { + key: "setDebugMode", + value: function setDebugMode() { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + } + + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + + }, { + key: "setExchangeTimeout", + value: function setExchangeTimeout(exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + } + + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + + }, { + key: "decorateAppAPIMethods", + value: function decorateAppAPIMethods(self, methods, scrambleKey) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var methodName = _step.value; + + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, { + key: "decorateAppAPIMethod", + value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { + var _this2 = this; + + return function () { + var _ref3 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var _appAPIlock; + + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _appAPIlock = _this2._appAPIlock; + + if (!_appAPIlock) { + _context3.next = 3; + break; + } + + return _context3.abrupt("return", Promise.reject(new _errors$2.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); + + case 3: + _context3.prev = 3; + + _this2._appAPIlock = methodName; + _this2.setScrambleKey(scrambleKey); + _context3.next = 8; + return f.apply(ctx, args); + + case 8: + return _context3.abrupt("return", _context3.sent); + + case 9: + _context3.prev = 9; + + _this2._appAPIlock = null; + return _context3.finish(9); + + case 12: + case "end": + return _context3.stop(); + } + } + }, _callee3, _this2, [[3,, 9, 12]]); + })); + + return function () { + return _ref3.apply(this, arguments); + }; + }(); + } + }], [{ + key: "create", + + + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + value: function create() { + var _this3 = this; + + var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; + var listenTimeout = arguments[1]; + + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this3.listen({ + next: function next(e) { + found = true; + if (sub) sub.unsubscribe(); + if (listenTimeoutId) clearTimeout(listenTimeoutId); + _this3.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function error(e) { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function complete() { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + if (!found) { + reject(new _errors$2.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout ? setTimeout(function () { + sub.unsubscribe(); + reject(new _errors$2.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) : null; + }); + } + + // $FlowFixMe + + }]); + + return Transport; + }(); + + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + Transport$1.default = Transport; + + var hidFraming = {}; + + Object.defineProperty(hidFraming, "__esModule", { + value: true + }); + + var _errors$1 = lib$2; + + var Tag = 0x05; + + function asUInt16BE(value) { + var b = Buffer$g.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + + var initialAcc = { + data: Buffer$g.alloc(0), + dataLength: 0, + sequence: 0 + }; + + /** + * + */ + var createHIDframing = function createHIDframing(channel, packetSize) { + return { + makeBlocks: function makeBlocks(apdu) { + var data = Buffer$g.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$g.concat([data, // fill data with padding + Buffer$g.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); + + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$g.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$g.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function reduceResponse(acc, chunk) { + var _ref = acc || initialAcc, + data = _ref.data, + dataLength = _ref.dataLength, + sequence = _ref.sequence; + + if (chunk.readUInt16BE(0) !== channel) { + throw new _errors$1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new _errors$1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new _errors$1.TransportError("Invalid sequence", "InvalidSequence"); + } + + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$g.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function getReducedResult(acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + + hidFraming.default = createHIDframing; + + var lib$1 = {}; + + Object.defineProperty(lib$1, "__esModule", { + value: true + }); + + var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; + + /** + * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) + * + ** Model + * Ledger Nano S : 0x10 + * Ledger Blue : 0x00 + * Ledger Nano X : 0x40 + * + ** Interface support bitfield + * Generic HID : 0x01 + * Keyboard HID : 0x02 + * U2F : 0x04 + * CCID : 0x08 + * WebUSB : 0x10 + */ + + lib$1.IIGenericHID = 0x01; + lib$1.IIKeyboardHID = 0x02; + lib$1.IIU2F = 0x04; + lib$1.IICCID = 0x08; + lib$1.IIWebUSB = 0x10; + + var devices = { + blue: { + id: "blue", + productName: "Ledger Blue", + productIdMM: 0x00, + legacyUsbProductId: 0x0000, + usbOnly: true, + memorySize: 480 * 1024, + blockSize: 4 * 1024 + }, + nanoS: { + id: "nanoS", + productName: "Ledger Nano S", + productIdMM: 0x10, + legacyUsbProductId: 0x0001, + usbOnly: true, + memorySize: 320 * 1024, + blockSize: 4 * 1024 + }, + nanoX: { + id: "nanoX", + productName: "Ledger Nano X", + productIdMM: 0x40, + legacyUsbProductId: 0x0004, + usbOnly: false, + memorySize: 2 * 1024 * 1024, + blockSize: 4 * 1024, + bluetoothSpec: [{ + // this is the legacy one (prototype version). we will eventually drop it. + serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", + notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", + writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" + }, { + serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", + notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", + writeUuid: "13d63400-2c97-0004-0002-4c6564676572" + }] + } + }; + + var productMap = { + Blue: "blue", + "Nano S": "nanoS", + "Nano X": "nanoX" + }; + + // $FlowFixMe + var devicesList = Object.values(devices); + + /** + * + */ + lib$1.ledgerUSBVendorId = 0x2c97; + + /** + * + */ + lib$1.getDeviceModel = function getDeviceModel(id) { + var info = devices[id]; + if (!info) throw new Error("device '" + id + "' does not exist"); + return info; + }; + + /** + * + */ + lib$1.identifyUSBProductId = function identifyUSBProductId(usbProductId) { + var legacy = devicesList.find(function (d) { + return d.legacyUsbProductId === usbProductId; + }); + if (legacy) return legacy; + + var mm = usbProductId >> 8; + var deviceModel = devicesList.find(function (d) { + return d.productIdMM === mm; + }); + return deviceModel; + }; + + lib$1.identifyProductName = function identifyProductName(productName) { + var productId = productMap[productName]; + var deviceModel = devicesList.find(function (d) { + return d.id === productId; + }); + + return deviceModel; + }; + + var bluetoothServices = []; + var serviceUuidToInfos = {}; + + for (var _id in devices) { + var _deviceModel = devices[_id]; + var _bluetoothSpec = _deviceModel.bluetoothSpec; + + if (_bluetoothSpec) { + for (var i = 0; i < _bluetoothSpec.length; i++) { + var spec = _bluetoothSpec[i]; + bluetoothServices.push(spec.serviceUuid); + serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); + } + } + } + + /** + * + */ + lib$1.getBluetoothServiceUuids = function getBluetoothServiceUuids() { + return bluetoothServices; + }; + + /** + * + */ + lib$1.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { + return serviceUuidToInfos[uuid.toLowerCase()]; + }; + + var lib = {}; + + Object.defineProperty(lib, "__esModule", { + value: true + }); + + + /** + * A Log object + */ + var id = 0; + var subscribers = []; + + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + lib.log = function log(type, message, data) { + var obj = { type: type, id: String(++id), date: new Date() }; + if (message) obj.message = message; + if (data) obj.data = data; + dispatch(obj); + }; + + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = lib.listen = function listen(cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } catch (e) { + console.error(e); + } + } + } + + // for debug purpose + commonjsGlobal.__ledgerLogsListen = listen; + + var webusb = {}; + + Object.defineProperty(webusb, "__esModule", { + value: true + }); + webusb.isSupported = webusb.getFirstLedgerDevice = webusb.getLedgerDevices = webusb.requestLedgerDevice = undefined; + + var requestLedgerDevice = webusb.requestLedgerDevice = function () { + var _ref = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + var device; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return navigator.usb.requestDevice({ filters: ledgerDevices }); + + case 2: + device = _context.sent; + return _context.abrupt("return", device); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + return function requestLedgerDevice() { + return _ref.apply(this, arguments); + }; + }(); + + var getLedgerDevices = webusb.getLedgerDevices = function () { + var _ref2 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var devices; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return navigator.usb.getDevices(); + + case 2: + devices = _context2.sent; + return _context2.abrupt("return", devices.filter(function (d) { + return d.vendorId === _devices$1.ledgerUSBVendorId; + })); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + return function getLedgerDevices() { + return _ref2.apply(this, arguments); + }; + }(); + + webusb.getFirstLedgerDevice = function () { + var _ref3 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var existingDevices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getLedgerDevices(); + + case 2: + existingDevices = _context3.sent; + + if (!(existingDevices.length > 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", existingDevices[0]); + + case 5: + return _context3.abrupt("return", requestLedgerDevice()); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + return function getFirstLedgerDevice() { + return _ref3.apply(this, arguments); + }; + }(); + + var _devices$1 = lib$1; + + function _asyncToGenerator$1(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + var ledgerDevices = [{ vendorId: _devices$1.ledgerUSBVendorId }]; + + webusb.isSupported = function isSupported() { + return Promise.resolve(!!navigator && + // $FlowFixMe + !!navigator.usb && typeof navigator.usb.getDevices === "function"); + }; + + Object.defineProperty(TransportWebUSB$2, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _hwTransport = Transport$1; + + var _hwTransport2 = _interopRequireDefault(_hwTransport); + + var _hidFraming = hidFraming; + + var _hidFraming2 = _interopRequireDefault(_hidFraming); + + var _devices = lib$1; + + var _logs = lib; + + var _errors = lib$2; + + var _webusb = webusb; + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var configurationValue = 1; + var endpointNumber = 3; + + /** + * WebUSB Transport implementation + * @example + * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ + + var TransportWebUSB = function (_Transport) { + _inherits(TransportWebUSB, _Transport); + + function TransportWebUSB(device, interfaceNumber) { + _classCallCheck(this, TransportWebUSB); + + var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); + + _initialiseProps.call(_this); + + _this.device = device; + _this.interfaceNumber = interfaceNumber; + _this.deviceModel = (0, _devices.identifyUSBProductId)(device.productId); + return _this; + } + + /** + * Check if WebUSB transport is supported. + */ + + + /** + * List the WebUSB devices that was previously authorized by the user. + */ + + + /** + * Actively listen to WebUSB devices and emit ONE device + * that was either accepted before, if not it will trigger the native permission UI. + * + * Important: it must be called in the context of a UI click! + */ + + + _createClass(TransportWebUSB, [{ + key: "close", + + + /** + * Release the transport device + */ + value: function () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.exchangeBusyPromise; + + case 2: + _context.next = 4; + return this.device.releaseInterface(this.interfaceNumber); + + case 4: + _context.next = 6; + return this.device.reset(); + + case 6: + _context.next = 8; + return this.device.close(); + + case 8: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _ref.apply(this, arguments); + } + + return close; + }() + + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + + }, { + key: "setScrambleKey", + value: function setScrambleKey() {} + }], [{ + key: "request", + + + /** + * Similar to create() except it will always display the device permission (even if some devices are already accepted). + */ + value: function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { + var device; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _webusb.requestLedgerDevice)(); + + case 2: + device = _context2.sent; + return _context2.abrupt("return", TransportWebUSB.open(device)); + + case 4: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function request() { + return _ref2.apply(this, arguments); + } + + return request; + }() + + /** + * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). + */ + + }, { + key: "openConnected", + value: function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { + var devices; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _webusb.getLedgerDevices)(); + + case 2: + devices = _context3.sent; + + if (!(devices.length === 0)) { + _context3.next = 5; + break; + } + + return _context3.abrupt("return", null); + + case 5: + return _context3.abrupt("return", TransportWebUSB.open(devices[0])); + + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function openConnected() { + return _ref3.apply(this, arguments); + } + + return openConnected; + }() + + /** + * Create a Ledger transport with a USBDevice + */ + + }, { + key: "open", + value: function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { + var iface, interfaceNumber, transport, onDisconnect; + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return device.open(); + + case 2: + if (!(device.configuration === null)) { + _context4.next = 5; + break; + } + + _context4.next = 5; + return device.selectConfiguration(configurationValue); + + case 5: + _context4.next = 7; + return device.reset(); + + case 7: + iface = device.configurations[0].interfaces.find(function (_ref5) { + var alternates = _ref5.alternates; + return alternates.some(function (a) { + return a.interfaceClass === 255; + }); + }); + + if (iface) { + _context4.next = 10; + break; + } + + throw new _errors.TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); + + case 10: + interfaceNumber = iface.interfaceNumber; + _context4.prev = 11; + _context4.next = 14; + return device.claimInterface(interfaceNumber); + + case 14: + _context4.next = 21; + break; + + case 16: + _context4.prev = 16; + _context4.t0 = _context4["catch"](11); + _context4.next = 20; + return device.close(); + + case 20: + throw new _errors.TransportInterfaceNotAvailable(_context4.t0.message); + + case 21: + transport = new TransportWebUSB(device, interfaceNumber); + + onDisconnect = function onDisconnect(e) { + if (device === e.device) { + // $FlowFixMe + navigator.usb.removeEventListener("disconnect", onDisconnect); + transport._emitDisconnect(new _errors.DisconnectedDevice()); + } + }; + // $FlowFixMe + + + navigator.usb.addEventListener("disconnect", onDisconnect); + return _context4.abrupt("return", transport); + + case 25: + case "end": + return _context4.stop(); + } + } + }, _callee4, this, [[11, 16]]); + })); + + function open(_x) { + return _ref4.apply(this, arguments); + } + + return open; + }() + }]); + + return TransportWebUSB; + }(_hwTransport2.default); + + TransportWebUSB.isSupported = _webusb.isSupported; + TransportWebUSB.list = _webusb.getLedgerDevices; + + TransportWebUSB.listen = function (observer) { + var unsubscribed = false; + (0, _webusb.getFirstLedgerDevice)().then(function (device) { + if (!unsubscribed) { + var deviceModel = (0, _devices.identifyUSBProductId)(device.productId); + observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); + observer.complete(); + } + }, function (error) { + if (window.DOMException && error instanceof window.DOMException && error.code === 18) { + observer.error(new _errors.TransportWebUSBGestureRequired(error.message)); + } else { + observer.error(new _errors.TransportOpenUserCancelled(error.message)); + } + }); + function unsubscribe() { + unsubscribed = true; + } + return { unsubscribe: unsubscribe }; + }; + + var _initialiseProps = function _initialiseProps() { + var _this2 = this; + + this.channel = Math.floor(Math.random() * 0xffff); + this.packetSize = 64; + this._disconnectEmitted = false; + + this._emitDisconnect = function (e) { + if (_this2._disconnectEmitted) return; + _this2._disconnectEmitted = true; + _this2.emit("disconnect", e); + }; + + this.exchange = function (apdu) { + return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { + var channel, packetSize, framing, blocks, i, result, acc, r, buffer; + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + channel = _this2.channel, packetSize = _this2.packetSize; + + (0, _logs.log)("apdu", "=> " + apdu.toString("hex")); + + framing = (0, _hidFraming2.default)(channel, packetSize); + + // Write... + + blocks = framing.makeBlocks(apdu); + i = 0; + + case 5: + if (!(i < blocks.length)) { + _context5.next = 12; + break; + } + + (0, _logs.log)("hid-frame", "=> " + blocks[i].toString("hex")); + _context5.next = 9; + return _this2.device.transferOut(endpointNumber, blocks[i]); + + case 9: + i++; + _context5.next = 5; + break; + + case 12: + + // Read... + result = void 0; + acc = void 0; + + case 14: + if (result = framing.getReducedResult(acc)) { + _context5.next = 23; + break; + } + + _context5.next = 17; + return _this2.device.transferIn(endpointNumber, packetSize); + + case 17: + r = _context5.sent; + buffer = Buffer$g.from(r.data.buffer); + + (0, _logs.log)("hid-frame", "<= " + buffer.toString("hex")); + acc = framing.reduceResponse(acc, buffer); + _context5.next = 14; + break; + + case 23: + + (0, _logs.log)("apdu", "<= " + result.toString("hex")); + return _context5.abrupt("return", result); + + case 25: + case "end": + return _context5.stop(); + } + } + }, _callee5, _this2); + }))).catch(function (e) { + if (e && e.message && e.message.includes("disconnected")) { + _this2._emitDisconnect(e); + throw new _errors.DisconnectedDeviceDuringOperation(e.message); + } + throw e; + }); + }; + }; + + var _default = TransportWebUSB$2.default = TransportWebUSB; + + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': _default + }, [TransportWebUSB$2])); + + exports.Btc = Btc$1; + exports.TransportWebUSB = TransportWebUSB$1; + exports.createHash = index; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file From 3e61004b19a8dbba7ba998cafab9935babf4bcb4 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 21:22:01 +1100 Subject: [PATCH 15/78] please work --- js/ledger.js | 14901 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 9867 insertions(+), 5034 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 86334648..c310956e 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1,8 +1,12 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).buffer=t()}}(function(){return function(){return function t(r,e,n){function i(f,u){if(!e[f]){if(!r[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var h=new Error("Cannot find module '"+f+"'");throw h.code="MODULE_NOT_FOUND",h}var a=e[f]={exports:{}};r[f][0].call(a.exports,function(t){return i(r[f][1][t]||t)},a,a.exports,t,r,e,n)}return e[f].exports}for(var o="function"==typeof require&&require,f=0;fo)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=r.prototype,e}function r(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return u(t,r,e)}function u(t,e,n){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!r.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var n=0|c(t,e),i=f(n),o=i.write(t,e);o!==n&&(i=i.slice(0,o));return i}(t,e);if(ArrayBuffer.isView(t))return a(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(z(t,ArrayBuffer)||t&&z(t.buffer,ArrayBuffer))return function(t,e,n){if(e<0||t.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function c(t,e){if(r.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||z(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var n=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var o=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return P(t).length;default:if(o)return i?-1:N(t).length;e=(""+e).toLowerCase(),o=!0}}function l(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function y(t,e,n,i,o){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),D(n=+n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof e&&(e=r.from(e,i)),r.isBuffer(e))return 0===e.length?-1:g(t,e,n,i,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):g(t,[e],n,i,o);throw new TypeError("val must be string, number or Buffer")}function g(t,r,e,n,i){var o,f=1,u=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;f=2,u/=2,s/=2,e/=2}function h(t,r){return 1===f?t[r]:t.readUInt16BE(r*f)}if(i){var a=-1;for(o=e;ou&&(e=u-s),o=e;o>=0;o--){for(var p=!0,c=0;ci&&(n=i):n=i;var o=r.length;n>o/2&&(n=o/2);for(var f=0;f>8,i=e%256,o.push(i),o.push(n);return o}(r,t.length-e),t,e,n)}function A(t,r,e){return 0===r&&e===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(r,e))}function B(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i239?4:h>223?3:h>191?2:1;if(i+p<=e)switch(p){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],f=t[i+2],128==(192&o)&&128==(192&f)&&(s=(15&h)<<12|(63&o)<<6|63&f)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],f=t[i+2],u=t[i+3],128==(192&o)&&128==(192&f)&&128==(192&u)&&(s=(15&h)<<18|(63&o)<<12|(63&f)<<6|63&u)>65535&&s<1114112&&(a=s)}null===a?(a=65533,p=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=p}return function(t){var r=t.length;if(r<=U)return String.fromCharCode.apply(String,t);var e="",n=0;for(;nthis.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,r,e);case"utf8":case"utf-8":return B(this,r,e);case"ascii":return _(this,r,e);case"latin1":case"binary":return T(this,r,e);case"base64":return A(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},r.prototype.toLocaleString=r.prototype.toString,r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),""},r.prototype.compare=function(t,e,n,i,o){if(z(t,Uint8Array)&&(t=r.from(t,t.offset,t.byteLength)),!r.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),e<0||n>t.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&e>=n)return 0;if(i>=o)return-1;if(e>=n)return 1;if(this===t)return 0;for(var f=(o>>>=0)-(i>>>=0),u=(n>>>=0)-(e>>>=0),s=Math.min(f,u),h=this.slice(i,o),a=t.slice(e,n),p=0;p>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return w(this,t,r,e);case"utf8":case"utf-8":return d(this,t,r,e);case"ascii":return v(this,t,r,e);case"latin1":case"binary":return b(this,t,r,e);case"base64":return m(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var U=4096;function _(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;in)&&(e=n);for(var i="",o=r;oe)throw new RangeError("Trying to access beyond buffer length")}function L(t,e,n,i,o,f){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function R(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function x(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,4),i.write(t,r,e,n,23,4),e+4}function M(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,8),i.write(t,r,e,n,52,8),e+8}r.prototype.slice=function(t,e){var n=this.length;(t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},r.prototype.readUInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*r)),n},r.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},r.prototype.readInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt16BE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r>>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},r.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,255,0),this[r]=255&t,r+1},r.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},r.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=0,f=1,u=0;for(this[r]=255&t;++o>0)-u&255;return r+e},r.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=e-1,f=1,u=0;for(this[r+o]=255&t;--o>=0&&(f*=256);)t<0&&0===u&&0!==this[r+o+1]&&(u=1),this[r+o]=(t/f>>0)-u&255;return r+e},r.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},r.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},r.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeFloatLE=function(t,r,e){return x(this,t,r,!0,e)},r.prototype.writeFloatBE=function(t,r,e){return x(this,t,r,!1,e)},r.prototype.writeDoubleLE=function(t,r,e){return M(this,t,r,!0,e)},r.prototype.writeDoubleBE=function(t,r,e){return M(this,t,r,!1,e)},r.prototype.copy=function(t,e,n,i){if(!r.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--f)t[f+e]=this[f+n];else Uint8Array.prototype.set.call(t,this.subarray(n,i),e);return o},r.prototype.fill=function(t,e,n,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!r.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var o=t.charCodeAt(0);("utf8"===i&&o<128||"latin1"===i)&&(t=o)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(f=e;f55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(f+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function P(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function j(t,r,e,n){for(var i=0;i=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function z(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function D(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":2,buffer:5,ieee754:3}],2:[function(t,r,e){"use strict";e.byteLength=function(t){var r=h(t),e=r[0],n=r[1];return 3*(e+n)/4-n},e.toByteArray=function(t){for(var r,e=h(t),n=e[0],f=e[1],u=new o(function(t,r,e){return 3*(r+e)/4-e}(0,n,f)),s=0,a=f>0?n-4:n,p=0;p>16&255,u[s++]=r>>8&255,u[s++]=255&r;2===f&&(r=i[t.charCodeAt(p)]<<2|i[t.charCodeAt(p+1)]>>4,u[s++]=255&r);1===f&&(r=i[t.charCodeAt(p)]<<10|i[t.charCodeAt(p+1)]<<4|i[t.charCodeAt(p+2)]>>2,u[s++]=r>>8&255,u[s++]=255&r);return u},e.fromByteArray=function(t){for(var r,e=t.length,i=e%3,o=[],f=0,u=e-i;fu?u:f+16383));1===i?(r=t[e-1],o.push(n[r>>2]+n[r<<4&63]+"==")):2===i&&(r=(t[e-2]<<8)+t[e-1],o.push(n[r>>10]+n[r>>4&63]+n[r<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,s=f.length;u0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function a(t,r,e){for(var i,o,f=[],u=r;u>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return f.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],3:[function(t,r,e){e.read=function(t,r,e,n,i){var o,f,u=8*i-n-1,s=(1<>1,a=-7,p=e?i-1:0,c=e?-1:1,l=t[r+p];for(p+=c,o=l&(1<<-a)-1,l>>=-a,a+=u;a>0;o=256*o+t[r+p],p+=c,a-=8);for(f=o&(1<<-a)-1,o>>=-a,a+=n;a>0;f=256*f+t[r+p],p+=c,a-=8);if(0===o)o=1-h;else{if(o===s)return f?NaN:1/0*(l?-1:1);f+=Math.pow(2,n),o-=h}return(l?-1:1)*f*Math.pow(2,o-n)},e.write=function(t,r,e,n,i,o){var f,u,s,h=8*o-i-1,a=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:o-1,y=n?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,f=a):(f=Math.floor(Math.log(r)/Math.LN2),r*(s=Math.pow(2,-f))<1&&(f--,s*=2),(r+=f+p>=1?c/s:c*Math.pow(2,1-p))*s>=2&&(f++,s/=2),f+p>=a?(u=0,f=a):f+p>=1?(u=(r*s-1)*Math.pow(2,i),f+=p):(u=r*Math.pow(2,p-1)*Math.pow(2,i),f=0));i>=8;t[e+l]=255&u,l+=y,u/=256,i-=8);for(f=f<0;t[e+l]=255&f,l+=y,f/=256,h-=8);t[e+l-y]|=128*g}},{}],4:[function(t,r,e){arguments[4][2][0].apply(e,arguments)},{dup:2}],5:[function(t,r,e){arguments[4][1][0].apply(e,arguments)},{"base64-js":4,buffer:5,dup:1,ieee754:6}],6:[function(t,r,e){arguments[4][3][0].apply(e,arguments)},{dup:3}]},{},[1])(1)}); +window.global = window; +window.Buffer = buffer.Buffer; + (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util')) : - typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$1, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.require$$1)); -})(this, (function (exports, require$$0$1, require$$0$2, require$$0$3, require$$0$4, require$$1) { 'use strict'; + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util'), require('string_decoder')) : + typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util', 'string_decoder'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.EventEmitter, global.require$$1, global.require$$2)); +})(this, (function (exports, require$$0$2, require$$0$3, require$$0$4, EventEmitter, require$$1, require$$2) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -21,14 +25,34 @@ return Object.freeze(n); } - var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); - var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); - var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); - var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); + var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); + var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); + var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + var runtime = {exports: {}}; /** @@ -1018,12 +1042,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$g.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$i.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$g.TYPED_ARRAY_SUPPORT + return Buffer$i.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1032,14 +1056,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$g.prototype; + that.__proto__ = Buffer$i.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$g(length); + that = new Buffer$i(length); } that.length = length; } @@ -1057,9 +1081,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$g (arg, encodingOrOffset, length) { - if (!Buffer$g.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$g)) { - return new Buffer$g(arg, encodingOrOffset, length) + function Buffer$i (arg, encodingOrOffset, length) { + if (!Buffer$i.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$i)) { + return new Buffer$i(arg, encodingOrOffset, length) } // Common case. @@ -1074,11 +1098,11 @@ return from$2(this, arg, encodingOrOffset, length) } - Buffer$g.poolSize = 8192; // not used by this implementation + Buffer$i.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$g._augment = function (arr) { - arr.__proto__ = Buffer$g.prototype; + Buffer$i._augment = function (arr) { + arr.__proto__ = Buffer$i.prototype; return arr }; @@ -1106,13 +1130,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$g.from = function (value, encodingOrOffset, length) { + Buffer$i.from = function (value, encodingOrOffset, length) { return from$2(null, value, encodingOrOffset, length) }; - if (Buffer$g.TYPED_ARRAY_SUPPORT) { - Buffer$g.prototype.__proto__ = Uint8Array.prototype; - Buffer$g.__proto__ = Uint8Array; + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + Buffer$i.prototype.__proto__ = Uint8Array.prototype; + Buffer$i.__proto__ = Uint8Array; } function assertSize (size) { @@ -1143,14 +1167,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$g.alloc = function (size, fill, encoding) { + Buffer$i.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$g.TYPED_ARRAY_SUPPORT) { + if (!Buffer$i.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1161,13 +1185,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$g.allocUnsafe = function (size) { + Buffer$i.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$g.allocUnsafeSlow = function (size) { + Buffer$i.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1176,7 +1200,7 @@ encoding = 'utf8'; } - if (!Buffer$g.isEncoding(encoding)) { + if (!Buffer$i.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1223,10 +1247,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$g.prototype; + that.__proto__ = Buffer$i.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1273,12 +1297,12 @@ } return length | 0 } - Buffer$g.isBuffer = isBuffer; + Buffer$i.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$g.compare = function compare (a, b) { + Buffer$i.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1301,7 +1325,7 @@ return 0 }; - Buffer$g.isEncoding = function isEncoding (encoding) { + Buffer$i.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1320,13 +1344,13 @@ } }; - Buffer$g.concat = function concat (list, length) { + Buffer$i.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$g.alloc(0) + return Buffer$i.alloc(0) } var i; @@ -1337,7 +1361,7 @@ } } - var buffer = Buffer$g.allocUnsafe(length); + var buffer = Buffer$i.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1393,7 +1417,7 @@ } } } - Buffer$g.byteLength = byteLength; + Buffer$i.byteLength = byteLength; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1467,7 +1491,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$g.prototype._isBuffer = true; + Buffer$i.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1475,7 +1499,7 @@ b[m] = i; } - Buffer$g.prototype.swap16 = function swap16 () { + Buffer$i.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1486,7 +1510,7 @@ return this }; - Buffer$g.prototype.swap32 = function swap32 () { + Buffer$i.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1498,7 +1522,7 @@ return this }; - Buffer$g.prototype.swap64 = function swap64 () { + Buffer$i.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1512,20 +1536,20 @@ return this }; - Buffer$g.prototype.toString = function toString () { + Buffer$i.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$g.prototype.equals = function equals (b) { + Buffer$i.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$g.compare(this, b) === 0 + return Buffer$i.compare(this, b) === 0 }; - Buffer$g.prototype.inspect = function inspect () { + Buffer$i.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1535,7 +1559,7 @@ return '' }; - Buffer$g.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$i.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1634,7 +1658,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$g.from(val, encoding); + val = Buffer$i.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1646,7 +1670,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$g.TYPED_ARRAY_SUPPORT && + if (Buffer$i.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1716,15 +1740,15 @@ return -1 } - Buffer$g.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$i.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$g.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$i.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$g.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$i.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1775,7 +1799,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$g.prototype.write = function write (string, offset, length, encoding) { + Buffer$i.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1847,7 +1871,7 @@ } }; - Buffer$g.prototype.toJSON = function toJSON () { + Buffer$i.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2000,7 +2024,7 @@ return res } - Buffer$g.prototype.slice = function slice (start, end) { + Buffer$i.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2022,12 +2046,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$g.prototype; + newBuf.__proto__ = Buffer$i.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$g(sliceLen, undefined); + newBuf = new Buffer$i(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2044,7 +2068,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$g.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$i.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2059,7 +2083,7 @@ return val }; - Buffer$g.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$i.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2075,22 +2099,22 @@ return val }; - Buffer$g.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$i.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$g.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$i.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$g.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$i.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$g.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$i.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2099,7 +2123,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$g.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$i.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2108,7 +2132,7 @@ this[offset + 3]) }; - Buffer$g.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$i.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2126,7 +2150,7 @@ return val }; - Buffer$g.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$i.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2144,25 +2168,25 @@ return val }; - Buffer$g.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$i.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$g.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$i.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$g.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$i.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$g.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$i.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2171,7 +2195,7 @@ (this[offset + 3] << 24) }; - Buffer$g.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$i.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2180,22 +2204,22 @@ (this[offset + 3]) }; - Buffer$g.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$i.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$g.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$i.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$g.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$i.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$g.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$i.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2206,7 +2230,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$g.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$i.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2225,7 +2249,7 @@ return offset + byteLength }; - Buffer$g.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$i.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2244,11 +2268,11 @@ return offset + byteLength }; - Buffer$g.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$i.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$g.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2261,11 +2285,11 @@ } } - Buffer$g.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$i.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2274,11 +2298,11 @@ return offset + 2 }; - Buffer$g.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$i.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2294,11 +2318,11 @@ } } - Buffer$g.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$i.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2309,11 +2333,11 @@ return offset + 4 }; - Buffer$g.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$i.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2324,7 +2348,7 @@ return offset + 4 }; - Buffer$g.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$i.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2347,7 +2371,7 @@ return offset + byteLength }; - Buffer$g.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$i.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2370,21 +2394,21 @@ return offset + byteLength }; - Buffer$g.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$i.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$g.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$g.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$i.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2393,11 +2417,11 @@ return offset + 2 }; - Buffer$g.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$i.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2406,11 +2430,11 @@ return offset + 2 }; - Buffer$g.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$i.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2421,12 +2445,12 @@ return offset + 4 }; - Buffer$g.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$i.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; - if (Buffer$g.TYPED_ARRAY_SUPPORT) { + if (Buffer$i.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2450,11 +2474,11 @@ return offset + 4 } - Buffer$g.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$i.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$g.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$i.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2466,16 +2490,16 @@ return offset + 8 } - Buffer$g.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$i.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$g.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$i.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$g.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$i.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2507,7 +2531,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$g.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$i.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2527,7 +2551,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$g.prototype.fill = function fill (val, start, end, encoding) { + Buffer$i.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2547,7 +2571,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$g.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$i.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2576,7 +2600,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$g(val, encoding).toString()); + : utf8ToBytes(new Buffer$i(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -2851,11 +2875,6 @@ var createHash$3 = require$$0__default["default"].createHash; - var index = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': createHash$3 - }, [createHash$3])); - var safeBuffer = {exports: {}}; /*! safe-buffer. MIT License. Feross Aboukhadijeh */ @@ -3052,14 +3071,14 @@ var bs58 = basex(ALPHABET$1); var base58 = bs58; - var Buffer$f = safeBuffer.exports.Buffer; + var Buffer$h = safeBuffer.exports.Buffer; var base$1 = function (checksumFn) { // Encode a buffer as a base58-check encoded string function encode (payload) { var checksum = checksumFn(payload); - return base58.encode(Buffer$f.concat([ + return base58.encode(Buffer$h.concat([ payload, checksum ], payload.length + 4)) @@ -3112,7 +3131,7 @@ var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$g.alloc(1 + paths.length * 4); + var buffer = Buffer$i.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -3191,7 +3210,7 @@ var tinySecp256k1 = {exports: {}}; - var bn = {exports: {}}; + var bn$1 = {exports: {}}; (function (module) { (function (module, exports) { @@ -6637,7 +6656,7 @@ return res._forceRed(this); }; })(module, commonjsGlobal); - }(bn)); + }(bn$1)); var elliptic = {}; @@ -6695,7 +6714,7 @@ "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" }; - var require$$0 = { + var require$$0$1 = { name: name, version: version$1, description: description, @@ -6714,1278 +6733,4726 @@ var utils$n = {}; - var minimalisticAssert = assert$f; + var bn = {exports: {}}; - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } + (function (module) { + (function (module, exports) { - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - var utils$m = {}; + // 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; + } - (function (exports) { + // BN - var utils = exports; + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - 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; + 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 (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)); + if (typeof module === 'object') { + module.exports = BN; } 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); + 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 = require('buffer').Buffer; } + } catch (e) { } - return res; - } - utils.toArray = toArray; - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils.zero2 = zero2; + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils.toHex = toHex; + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; - }; - }(utils$m)); + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - (function (exports) { + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - utils.assert = minAssert; - utils.toArray = minUtils.toArray; - utils.zero2 = minUtils.zero2; - utils.toHex = minUtils.toHex; - utils.encode = minUtils.encode; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - // 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); + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - var ws = 1 << (w + 1); - var k = num.clone(); + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - 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); + 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 { - z = 0; + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - naf[i] = z; - k.iushrn(1); - } + if (endian !== 'le') return; - return naf; - } - utils.getNAF = getNAF; + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - // Represent k1, k2 in a Joint Sparse Form - function getJSF(k1, k2) { - var jsf = [ - [], - [], - ]; + 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; + } - 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; + 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; } - jsf[0].push(u1); - var u2; - if ((m24 & 1) === 0) { - u2 = 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 { - m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + return (c - 48) & 0xf; } - 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); + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; } - return jsf; - } - utils.getJSF = getJSF; + 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; + } - 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; + // 24-bits chunks + var off = 0; + var j = 0; - function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; - } - utils.parseBytes = parseBytes; + 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; + } + } + } - function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); - } - utils.intFromLE = intFromLE; - }(utils$n)); + this.strip(); + }; - var brorand = {exports: {}}; + 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; - var r$1; + r *= mul; - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - return r$1.generate(len); - }; + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - function Rand(rand) { - this.rand = rand; - } - brorand.exports.Rand = Rand; + // '0' - '9' + } else { + r += c; + } + } + return r; + } - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; - }; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - 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; - }; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - // 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$3 = require('crypto'); - if (typeof crypto$3.randomBytes !== 'function') - throw new Error('Not supported'); + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - Rand.prototype._rand = function _rand(n) { - return crypto$3.randomBytes(n); - }; - } catch (e) { - } - } + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - var curve = {}; + for (i = 0; i < mod; i++) { + pow *= base; + } - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); + this.strip(); + }; - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN$8(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + 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; + }; - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - this._bitLength = this.n ? this.n.bitLength() : 0; + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; - // 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); - } - } - var base = BaseCurve; + // 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(); + }; - BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); - }; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); - }; + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$e(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; + var zeros = []; + var groupSizes = []; + var groupBases = []; - // 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 s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; } - - 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()); + 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; } - a = a.add(b); + groupSizes[base] = groupSize; + groupBases[base] = groupBase; } - 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; + 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' + ]; - // Get NAF form - var naf = getNAF(k, w, this._bitLength); + 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 + ]; - // 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); + 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 + ]; - if (i < 0) - break; - var z = naf[i]; - assert$e(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; - }; + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; - BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; + 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; + } - // 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; - } + 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); - // 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; + 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; } - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; + assert(false, 'Base should be between 2 and 36'); + }; - // 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()); + 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; + }; - 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 */ - ]; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - 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; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - var k = 0; + 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'); - while (i >= 0) { - var zero = true; - for (j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; + 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; } - 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]; - 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(); + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (i = 0; i < len; i++) - wnd[i] = null; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - if (jacobianResult) - return acc; - else - return acc.toP(); - }; + res[i] = b; + } - function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; - } - BaseCurve.BasePoint = BasePoint; + for (; i < reqLength; i++) { + res[i] = 0; + } + } - BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); - }; + return res; + }; - BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); - }; + 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; + }; + } - BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$l.toArray(bytes, enc); + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - var len = this.p.byteLength(); + 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; + }; - // 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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(bytes[bytes.length - 1] % 2 === 1); + // 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; + }; - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); + function toBitArray (num) { + var w = new Array(num.bitLength()); - 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); + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); - }; + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } - BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); - }; + return w; + } - BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - var precomputed = { - doubles: null, - naf: null, - beta: null, + 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; }; - 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; + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - var doubles = this.precomputed.doubles; - if (!doubles) - return false; + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); - }; + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - 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, + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); }; - }; - BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } - 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, + return this; }; - }; - - 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; - }; + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - var inherits$c = {exports: {}}; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - var inherits_browser = {exports: {}}; + return this.strip(); + }; - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - } - }); - } + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); }; - } else { - // old school shim for old browsers - inherits_browser.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; - } + + // 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); }; - } - try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - inherits$c.exports = util.inherits; - } catch (e) { - /* istanbul ignore next */ - inherits$c.exports = inherits_browser.exports; - } + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$b = inherits$c.exports; - var Base$2 = base; + // 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; + } - var assert$d = utils$k.assert; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); + this.length = b.length; - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); + return this.strip(); + }; - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; - // 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$b(ShortCurve, Base$2); - var short = ShortCurve; + // 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); + }; - ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN$7(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$7(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]; + // 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 { - lambda = lambdas[1]; - assert$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + a = num; + b = this; } - } - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN$7(vec.a, 16), - b: new BN$7(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - return { - beta: beta, - lambda: lambda, - basis: basis, - }; - }; + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - 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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); + this.length = a.length; - var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); + return this.strip(); + }; - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; - }; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + // 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); + }; - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(1); + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - // 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; + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - 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)); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; } - prevR = r; - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } + // And remove leading zeroes + return this.strip(); + }; - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ]; - }; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); + var off = (bit / 26) | 0; + var wbit = bit % 26; - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); + this._expand(off + 1); - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; - }; + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$7(x, 16); - if (!x.red) - x = x.toRed(this.red); + return this.strip(); + }; - 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'); + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; - // 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(); + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - return this.point(x, y); - }; + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } - ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } - var x = point.x; - var y = point.y; + 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; + } - 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; - }; + 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]; + } + } - 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(); + return this; + }; - 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; - } + // 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; - }; - - function Point$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$b(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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); - } + if (this.length > num.length) return this.clone().iadd(num); - 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 num.clone().iadd(this); }; - return res; - }; - - Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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); - }; + // 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(); - Point$2.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } - 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; - }; + // At this point both numbers are positive + var cmp = this.cmp(num); - Point$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - function JPoint(curve, x, y, z) { - Base$2.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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); + 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; + } - this.zOne = this.z === this.curve.one; - } - inherits$b(JPoint, Base$2.BasePoint); + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); - }; + this.length = Math.max(this.length, i); - JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); + if (a !== this) { + this.negative = 1; + } - 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.strip(); + }; - return this.curve.point(ax, ay); - }; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; - JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }; + 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; - JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; + // 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; - // P + O = P - if (p.isInfinity()) - return this; + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - // 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)); + 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--; + } - 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(); + return out.strip(); } - 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); + // 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; - 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); + 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) ; 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); + }; + })(module, commonjsGlobal); + }(bn)); + + var minimalisticAssert = assert$f; + + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } + + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; + + var utils$m = {}; + + (function (exports) { + + 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; + }; + }(utils$m)); + + (function (exports) { + + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; + + 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; + }(utils$n)); + + var brorand = {exports: {}}; + + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; + } + brorand.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$3 = require('crypto'); + if (typeof crypto$3.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$3.randomBytes(n); + }; + } catch (e) { + } + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); + } + } + var base = 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$e(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$e(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]; + 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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; + }; + + var inherits$f = {exports: {}}; + + var inherits_browser = {exports: {}}; + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } + + try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + inherits$f.exports = util.inherits; + } catch (e) { + /* istanbul ignore next */ + inherits$f.exports = inherits_browser.exports; + } + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$e = inherits$f.exports; + var Base$3 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$3.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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$e(ShortCurve, Base$3); + var short = 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$7(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$7(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$d(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$7(vec.a, 16), + b: new BN$7(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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { + Base$3.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$e(Point$2, Base$3.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.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$2.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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$3.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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$e(JPoint, Base$3.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(); } @@ -8337,13 +11804,13 @@ }; var BN$6 = bn.exports; - var inherits$a = inherits$c.exports; - var Base$1 = base; + var inherits$d = inherits$f.exports; + var Base$2 = base; var utils$j = utils$n; function MontCurve(conf) { - Base$1.call(this, 'mont', conf); + Base$2.call(this, 'mont', conf); this.a = new BN$6(conf.a, 16).toRed(this.red); this.b = new BN$6(conf.b, 16).toRed(this.red); @@ -8351,7 +11818,7 @@ this.two = new BN$6(2).toRed(this.red); this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } - inherits$a(MontCurve, Base$1); + inherits$d(MontCurve, Base$2); var mont = MontCurve; MontCurve.prototype.validate = function validate(point) { @@ -8364,7 +11831,7 @@ }; function Point$1(curve, x, z) { - Base$1.BasePoint.call(this, curve, 'projective'); + Base$2.BasePoint.call(this, curve, 'projective'); if (x === null && z === null) { this.x = this.curve.one; this.z = this.curve.zero; @@ -8377,7 +11844,7 @@ this.z = this.z.toRed(this.curve.red); } } - inherits$a(Point$1, Base$1.BasePoint); + inherits$d(Point$1, Base$2.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { return this.point(utils$j.toArray(bytes, enc), 1); @@ -8515,8 +11982,8 @@ var utils$i = utils$n; var BN$5 = bn.exports; - var inherits$9 = inherits$c.exports; - var Base = base; + var inherits$c = inherits$f.exports; + var Base$1 = base; var assert$c = utils$i.assert; @@ -8526,7 +11993,7 @@ this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; - Base.call(this, 'edwards', conf); + Base$1.call(this, 'edwards', conf); this.a = new BN$5(conf.a, 16).umod(this.red.m); this.a = this.a.toRed(this.red); @@ -8538,7 +12005,7 @@ assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); this.oneC = (conf.c | 0) === 1; } - inherits$9(EdwardsCurve, Base); + inherits$c(EdwardsCurve, Base$1); var edwards = EdwardsCurve; EdwardsCurve.prototype._mulA = function _mulA(num) { @@ -8625,7 +12092,7 @@ }; function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); + Base$1.BasePoint.call(this, curve, 'projective'); if (x === null && y === null && z === null) { this.x = this.curve.zero; this.y = this.curve.one; @@ -8655,7 +12122,7 @@ } } } - inherits$9(Point, Base.BasePoint); + inherits$c(Point, Base$1.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); @@ -8964,9 +12431,9 @@ var utils$h = {}; var assert$b = minimalisticAssert; - var inherits$8 = inherits$c.exports; + var inherits$b = inherits$f.exports; - utils$h.inherits = inherits$8; + utils$h.inherits = inherits$b; function isSurrogatePair(msg, i) { if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { @@ -9333,7 +12800,7 @@ return res; }; - var sha$2 = {}; + var sha$3 = {}; var common$4 = {}; @@ -9953,11 +13420,11 @@ return utils$a.split32(this.h.slice(0, 12), 'big'); }; - sha$2.sha1 = _1; - sha$2.sha224 = _224; - sha$2.sha256 = _256; - sha$2.sha384 = _384; - sha$2.sha512 = _512; + sha$3.sha1 = _1; + sha$3.sha224 = _224; + sha$3.sha256 = _256; + sha$3.sha384 = _384; + sha$3.sha512 = _512; var ripemd = {}; @@ -9970,24 +13437,24 @@ var sum32_4 = utils$9.sum32_4; var BlockHash = common.BlockHash; - function RIPEMD160$1() { - if (!(this instanceof RIPEMD160$1)) - return new RIPEMD160$1(); + function RIPEMD160$2() { + if (!(this instanceof RIPEMD160$2)) + return new RIPEMD160$2(); BlockHash.call(this); this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.endian = 'little'; } - utils$9.inherits(RIPEMD160$1, BlockHash); - ripemd.ripemd160 = RIPEMD160$1; + utils$9.inherits(RIPEMD160$2, BlockHash); + ripemd.ripemd160 = RIPEMD160$2; - RIPEMD160$1.blockSize = 512; - RIPEMD160$1.outSize = 160; - RIPEMD160$1.hmacStrength = 192; - RIPEMD160$1.padLength = 64; + RIPEMD160$2.blockSize = 512; + RIPEMD160$2.outSize = 160; + RIPEMD160$2.hmacStrength = 192; + RIPEMD160$2.padLength = 64; - RIPEMD160$1.prototype._update = function update(msg, start) { + RIPEMD160$2.prototype._update = function update(msg, start) { var A = this.h[0]; var B = this.h[1]; var C = this.h[2]; @@ -10028,7 +13495,7 @@ this.h[0] = T; }; - RIPEMD160$1.prototype._digest = function digest(enc) { + RIPEMD160$2.prototype._digest = function digest(enc) { if (enc === 'hex') return utils$9.toHex32(this.h, 'little'); else @@ -10157,7 +13624,7 @@ hash.utils = utils$h; hash.common = common$5; - hash.sha = sha$2; + hash.sha = sha$3; hash.ripemd = ripemd; hash.hmac = hmac; @@ -11296,7 +14763,7 @@ var elliptic = exports; - elliptic.version = require$$0.version; + elliptic.version = require$$0$1.version; elliptic.utils = utils$n; elliptic.rand = brorand.exports; elliptic.curve = curve; @@ -11309,16 +14776,16 @@ const createHmac = createHmac$2; - const ONE1 = Buffer$g.alloc(1, 1); - const ZERO1 = Buffer$g.alloc(1, 0); + const ONE1 = Buffer$i.alloc(1, 1); + const ZERO1 = Buffer$i.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$g.alloc(32, 0); - let v = Buffer$g.alloc(32, 1); + let k = Buffer$i.alloc(32, 0); + let v = Buffer$i.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -11370,14 +14837,14 @@ var rfc6979 = deterministicGenerateK$1; - const BN = bn.exports; + const BN = bn$1.exports; const EC = elliptic.ec; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$g.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$g.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$g.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$i.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$i.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$i.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -11449,9 +14916,9 @@ } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$g, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$i, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$g.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$i.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -11541,7 +15008,7 @@ return dt } - function sign (hash, x) { + function sign$1 (hash, x) { return __sign(hash, x) } @@ -11583,7 +15050,7 @@ s = n.sub(s); } - const buffer = Buffer$g.allocUnsafe(64); + const buffer = Buffer$i.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -11648,7 +15115,7 @@ pointMultiply, privateAdd, privateSub, - sign, + sign: sign$1, signWithEntropy, verify }; @@ -12174,7 +15641,7 @@ } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$g(compressed ? 34 : 33); + var result = new Buffer$i(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -12293,7 +15760,7 @@ const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$g.allocUnsafe(78); + const buffer = Buffer$i.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -12327,7 +15794,7 @@ derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$g.allocUnsafe(37); + const data = Buffer$i.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -12407,7 +15874,7 @@ } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$g.alloc(32, 0); + const extraData = Buffer$i.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -12499,7 +15966,7 @@ if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$2.hmacSHA512(Buffer$g.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$2.hmacSHA512(Buffer$i.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -12606,7 +16073,7 @@ function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$g.allocUnsafe(size); + const buffer = Buffer$i.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -12687,7 +16154,7 @@ // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] // NOTE: SIGHASH byte ignored AND restricted, truncate before use - var Buffer$e = safeBuffer.exports.Buffer; + var Buffer$g = safeBuffer.exports.Buffer; function check$m (buffer) { if (buffer.length < 8) return false @@ -12776,7 +16243,7 @@ if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - var signature = Buffer$e.allocUnsafe(6 + lenR + lenS); + var signature = Buffer$g.allocUnsafe(6 + lenR + lenS); // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] signature[0] = 0x30; @@ -12801,18 +16268,18 @@ const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$g.alloc(1, 0); + const ZERO$1 = Buffer$i.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$g.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$i.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$g.alloc(32, 0); + const buffer = Buffer$i.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -12826,7 +16293,7 @@ const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$g.concat([r, s], 64); + const signature = Buffer$i.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -12841,11 +16308,11 @@ const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$g.allocUnsafe(1); + const hashTypeBuffer = Buffer$i.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$g.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$i.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -13234,7 +16701,7 @@ // opcode return accum + 1; }, 0.0); - const buffer = Buffer$g.allocUnsafe(bufferSize); + const buffer = Buffer$i.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -13319,7 +16786,7 @@ if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$g.from(chunkStr, 'hex'); + return Buffer$i.from(chunkStr, 'hex'); }), ); } @@ -13329,7 +16796,7 @@ typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$g.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$i.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -13737,7 +17204,7 @@ const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$g.allocUnsafe(21); + const payload = Buffer$i.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -13776,7 +17243,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$g.from([]); + let hash = Buffer$i.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -13895,7 +17362,7 @@ // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$g.allocUnsafe(21); + const payload = Buffer$i.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -13931,7 +17398,7 @@ return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$g.from([]); + let hash = Buffer$i.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -14207,7 +17674,7 @@ const OPS$2 = bscript$j.OPS; const ecc$2 = tinySecp256k1.exports; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$g.alloc(0); + const EMPTY_BUFFER$1 = Buffer$i.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -14235,7 +17702,7 @@ return { version, prefix: result.prefix, - data: Buffer$g.from(data), + data: Buffer$i.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -14275,7 +17742,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$g.from([]); + let hash = Buffer$i.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -14339,7 +17806,7 @@ const OPS$1 = bscript$i.OPS; const ecc$1 = tinySecp256k1.exports; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$g.alloc(0); + const EMPTY_BUFFER = Buffer$i.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -14389,7 +17856,7 @@ return { version, prefix: result.prefix, - data: Buffer$g.from(data), + data: Buffer$i.from(data), }; }); const _rchunks = lazy.value(() => { @@ -14454,7 +17921,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$g.from([]); + let hash = Buffer$i.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -14577,13 +18044,13 @@ return { version: result.words[0], prefix: result.prefix, - data: Buffer$g.from(data), + data: Buffer$i.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$g.allocUnsafe(21); + const payload = Buffer$i.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -14690,7 +18157,7 @@ return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$g.alloc(32, 0); + const extraData = Buffer$i.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -14759,7 +18226,7 @@ var bufferutils = {}; - var Buffer$d = safeBuffer.exports.Buffer; + var Buffer$f = safeBuffer.exports.Buffer; // Number.MAX_SAFE_INTEGER var MAX_SAFE_INTEGER$3 = 9007199254740991; @@ -14771,8 +18238,8 @@ function encode$b (number, buffer, offset) { checkUInt53$1(number); - if (!buffer) buffer = Buffer$d.allocUnsafe(encodingLength$1(number)); - if (!Buffer$d.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!buffer) buffer = Buffer$f.allocUnsafe(encodingLength$1(number)); + if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') if (!offset) offset = 0; // 8 bit @@ -14804,7 +18271,7 @@ } function decode$a (buffer, offset) { - if (!Buffer$d.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') if (!offset) offset = 0; var first = buffer.readUInt8(offset); @@ -14892,7 +18359,7 @@ } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$g.allocUnsafe(buffer.length); + const clone = Buffer$i.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -15015,17 +18482,17 @@ }, 0) ); } - const EMPTY_SCRIPT = Buffer$g.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$i.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$g.from( + const ZERO = Buffer$i.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$g.from( + const ONE = Buffer$i.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$g.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$i.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -15087,7 +18554,7 @@ return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$g.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$i.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -15247,7 +18714,7 @@ txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$g.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$i.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -15257,13 +18724,13 @@ types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$g.from([]); + let tbuffer = Buffer$i.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$g.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$i.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -15276,7 +18743,7 @@ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$g.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$i.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -15290,7 +18757,7 @@ const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$g.allocUnsafe(txOutsSize); + tbuffer = Buffer$i.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -15302,13 +18769,13 @@ inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$g.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$i.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$g.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$i.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -15326,7 +18793,7 @@ } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$g.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$i.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -15348,7 +18815,7 @@ this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$g.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$i.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -15410,7 +18877,7 @@ for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$g.concat([left, right]); + var data = Buffer$i.concat([left, right]); results[j] = digestFn(data); } @@ -15477,12 +18944,12 @@ return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$g.from(hex, 'hex')); + return Block.fromBuffer(Buffer$i.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$g.alloc(32, 0); + const target = Buffer$i.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -15497,7 +18964,7 @@ const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$g.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$i.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -15509,18 +18976,18 @@ // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$g.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$i.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$g && result.length === 32)) return null; + if (!(result instanceof Buffer$i && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$g && + this.witnessCommit instanceof Buffer$i && this.witnessCommit.length === 32 ) return true; @@ -15556,7 +19023,7 @@ } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$g.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$i.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -15733,10 +19200,10 @@ } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$g.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$g.concat([head, data.extendedPubkey]); + const head = Buffer$i.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$i.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$g.allocUnsafe(splitPath.length * 4); + const value = Buffer$i.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -15785,7 +19252,7 @@ const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$g.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$i.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -15806,7 +19273,7 @@ } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$g.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$i.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -15838,7 +19305,7 @@ } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$g.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$i.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -15873,7 +19340,7 @@ nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$g.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$i.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -15916,9 +19383,9 @@ } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$g.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$i.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$g.concat([head, pSig.pubkey]), + key: Buffer$i.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -15970,10 +19437,10 @@ } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$g.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$i.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$g.from(data, 'utf8'), + value: Buffer$i.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -16002,8 +19469,8 @@ } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$g.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$g.allocUnsafe(4); + const key = Buffer$i.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$i.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -16036,7 +19503,7 @@ } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$g.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$i.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -16122,8 +19589,8 @@ tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$g.from([0])); - return Buffer$g.concat(buffers); + buffers.push(Buffer$i.from([0])); + return Buffer$i.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -16131,7 +19598,7 @@ const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$g.allocUnsafe( + const buffer = Buffer$i.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -16195,12 +19662,12 @@ function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$g.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$i.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$g.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$i.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -16256,10 +19723,10 @@ return data; } function encode(data) { - const head = Buffer$g.from([TYPE_BYTE]); - const key = Buffer$g.concat([head, data.pubkey]); + const head = Buffer$i.from([TYPE_BYTE]); + const key = Buffer$i.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$g.allocUnsafe(splitPath.length * 4); + const value = Buffer$i.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -16339,7 +19806,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$g.from([TYPE_BYTE]); + const key = Buffer$i.from([TYPE_BYTE]); return { key, value: data, @@ -16376,7 +19843,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$g.from([TYPE_BYTE]); + const key = Buffer$i.from([TYPE_BYTE]); return { key, value: data, @@ -16585,7 +20052,7 @@ } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$g.from([keyNum]))) { + if (!keyBuf.equals(Buffer$i.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -16804,13 +20271,13 @@ const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$g.from([0])] + ? [Buffer$i.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$g.allocUnsafe(5); + const header = Buffer$i.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$g.concat( + return Buffer$i.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -17104,11 +20571,11 @@ }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$g.from(data, 'base64'); + const buffer = Buffer$i.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$g.from(data, 'hex'); + const buffer = Buffer$i.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -17328,11 +20795,11 @@ dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$g.from(data, 'base64'); + const buffer = Buffer$i.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$g.from(data, 'hex'); + const buffer = Buffer$i.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -17856,7 +21323,7 @@ * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$g.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$i.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -17881,7 +21348,7 @@ } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$g.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -18056,7 +21523,7 @@ } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$g.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -18420,14 +21887,14 @@ return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$g.allocUnsafe(0); + let buffer = Buffer$i.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$g.concat([buffer, Buffer$g.from(slice)]); + buffer = Buffer$i.concat([buffer, Buffer$i.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$g.concat([buffer, Buffer$g.allocUnsafe(varintLen)]); + buffer = Buffer$i.concat([buffer, Buffer$i.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -18936,7 +22403,7 @@ const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$g.from('aa21a9ed', 'hex'); + const HEADER = Buffer$i.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -18952,7 +22419,7 @@ }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$g.allocUnsafe(36); + const buffer = Buffer$i.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -19228,7 +22695,7 @@ // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$g.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$i.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -20351,7 +23818,7 @@ }; var title = 'browser'; var platform = 'browser'; - var browser = true; + var browser$2 = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues @@ -20415,7 +23882,7 @@ var process = { nextTick: nextTick, title: title, - browser: browser, + browser: browser$2, env: env, argv: argv, version: version, @@ -23190,7 +26657,7 @@ this.bufs = []; } BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$g.alloc(alloc); + var b = Buffer$i.alloc(alloc); fn(b); this.bufs.push(b); }; @@ -23210,14 +26677,14 @@ this.bufs.push(varuintBitcoin.encode(i)); }; BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$g.from(slice)); + this.bufs.push(Buffer$i.from(slice)); }; BufferWriter.prototype.writeVarSlice = function (slice) { this.writeVarInt(slice.length); this.writeSlice(slice); }; BufferWriter.prototype.buffer = function () { - return Buffer$g.concat(this.bufs); + return Buffer$i.concat(this.bufs); }; return BufferWriter; }()); @@ -23299,14 +26766,14 @@ function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require$2 = require$$0__default$1["default"], - Buffer$c = _require$2.Buffer; + Buffer$e = _require$2.Buffer; var _require2 = require$$1__default["default"], inspect = _require2.inspect; @@ -23314,21 +26781,21 @@ var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { - Buffer$c.prototype.copy.call(src, target, offset); + Buffer$e.prototype.copy.call(src, target, offset); } var buffer_list = /*#__PURE__*/ function () { function BufferList() { - _classCallCheck$2(this, BufferList); + _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } - _createClass$2(BufferList, [{ + _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { @@ -23381,8 +26848,8 @@ }, { key: "concat", value: function concat(n) { - if (this.length === 0) return Buffer$c.alloc(0); - var ret = Buffer$c.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer$e.alloc(0); + var ret = Buffer$e.allocUnsafe(n >>> 0); var p = this.head; var i = 0; @@ -23456,7 +26923,7 @@ }, { key: "_getBuffer", value: function _getBuffer(n) { - var ret = Buffer$c.allocUnsafe(n); + var ret = Buffer$e.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); @@ -23791,16 +27258,16 @@ /**/ - var Buffer$b = require$$0__default$1["default"].Buffer; + var Buffer$d = require$$0__default$1["default"].Buffer; var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer$1(chunk) { - return Buffer$b.from(chunk); + return Buffer$d.from(chunk); } function _isUint8Array$1(obj) { - return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array$1; + return Buffer$d.isBuffer(obj) || obj instanceof OurUint8Array$1; } var destroyImpl$1 = destroy_1; @@ -23820,7 +27287,7 @@ var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - inherits$c.exports(Writable$1, Stream$1); + inherits$f.exports(Writable$1, Stream$1); function nop() {} @@ -24015,7 +27482,7 @@ var isBuf = !state.objectMode && _isUint8Array$1(chunk); - if (isBuf && !Buffer$b.isBuffer(chunk)) { + if (isBuf && !Buffer$d.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer$1(chunk); } @@ -24066,7 +27533,7 @@ function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$b.from(chunk, encoding); + chunk = Buffer$d.from(chunk, encoding); } return chunk; @@ -24440,7 +27907,7 @@ var Writable = _stream_writable; - inherits$c.exports(Duplex$2, Readable$1); + inherits$f.exports(Duplex$2, Readable$1); { // Allow the keys array to be GC'ed. @@ -24539,10 +28006,10 @@ /**/ - var Buffer$a = safeBuffer.exports.Buffer; + var Buffer$c = safeBuffer.exports.Buffer; /**/ - var isEncoding = Buffer$a.isEncoding || function (encoding) { + var isEncoding = Buffer$c.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': @@ -24583,15 +28050,15 @@ // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer$a.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + if (typeof nenc !== 'string' && (Buffer$c.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. - string_decoder.StringDecoder = StringDecoder$1; - function StringDecoder$1(encoding) { + string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { @@ -24616,10 +28083,10 @@ } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer$a.allocUnsafe(nb); + this.lastChar = Buffer$c.allocUnsafe(nb); } - StringDecoder$1.prototype.write = function (buf) { + StringDecoder$2.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; @@ -24635,13 +28102,13 @@ return r || ''; }; - StringDecoder$1.prototype.end = utf8End; + StringDecoder$2.prototype.end = utf8End; // Returns only complete characters in a Buffer - StringDecoder$1.prototype.text = utf8Text; + StringDecoder$2.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$1.prototype.fillLast = function (buf) { + StringDecoder$2.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); @@ -25119,7 +28586,7 @@ 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$3(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); }); }; } + 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); }); }; } 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; } @@ -25155,7 +28622,7 @@ } function _next2() { - _next2 = _asyncToGenerator$3(function* () { + _next2 = _asyncToGenerator(function* () { try { var _ref = yield iterator.next(), value = _ref.value, @@ -25189,7 +28656,7 @@ Readable.ReadableState = ReadableState; /**/ - require$$0__default$3["default"].EventEmitter; + EventEmitter__default["default"].EventEmitter; var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; @@ -25203,16 +28670,16 @@ /**/ - var Buffer$9 = require$$0__default$1["default"].Buffer; + var Buffer$b = require$$0__default$1["default"].Buffer; var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { - return Buffer$9.from(chunk); + return Buffer$b.from(chunk); } function _isUint8Array(obj) { - return Buffer$9.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ @@ -25243,11 +28710,11 @@ ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - var StringDecoder; + var StringDecoder$1; var createReadableStreamAsyncIterator; var from; - inherits$c.exports(Readable, Stream); + inherits$f.exports(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; @@ -25320,8 +28787,8 @@ this.encoding = null; if (options.encoding) { - if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; - this.decoder = new StringDecoder(options.encoding); + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); this.encoding = options.encoding; } } @@ -25388,7 +28855,7 @@ encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$9.from(chunk, encoding); + chunk = Buffer$b.from(chunk, encoding); encoding = ''; } @@ -25420,7 +28887,7 @@ if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$9.prototype) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$b.prototype) { chunk = _uint8ArrayToBuffer(chunk); } @@ -25482,8 +28949,8 @@ Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = string_decoder.StringDecoder; - var decoder = new StringDecoder(enc); + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: @@ -26282,7 +29749,7 @@ return -1; } - var _stream_transform = Transform$2; + var _stream_transform = Transform$3; var _require$codes$1 = errors.codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, @@ -26292,7 +29759,7 @@ var Duplex = _stream_duplex; - inherits$c.exports(Transform$2, Duplex); + inherits$f.exports(Transform$3, Duplex); function afterTransform(er, data) { var ts = this._transformState; @@ -26316,8 +29783,8 @@ } } - function Transform$2(options) { - if (!(this instanceof Transform$2)) return new Transform$2(options); + function Transform$3(options) { + if (!(this instanceof Transform$3)) return new Transform$3(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), @@ -26355,7 +29822,7 @@ } } - Transform$2.prototype.push = function (chunk, encoding) { + Transform$3.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! @@ -26370,11 +29837,11 @@ // never call cb(), then you'll never get another chunk. - Transform$2.prototype._transform = function (chunk, encoding, cb) { + Transform$3.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; - Transform$2.prototype._write = function (chunk, encoding, cb) { + Transform$3.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; @@ -26389,7 +29856,7 @@ // That we got here means that the readable side wants more data. - Transform$2.prototype._read = function (n) { + Transform$3.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { @@ -26403,7 +29870,7 @@ } }; - Transform$2.prototype._destroy = function (err, cb) { + Transform$3.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); @@ -26423,13 +29890,13 @@ var _stream_passthrough = PassThrough; - var Transform$1 = _stream_transform; + var Transform$2 = _stream_transform; - inherits$c.exports(PassThrough, Transform$1); + inherits$f.exports(PassThrough, Transform$2); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$1.call(this, options); + Transform$2.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { @@ -26545,20 +30012,20 @@ } }(readable, readable.exports)); - var Buffer$8 = safeBuffer.exports.Buffer; - var Transform = readable.exports.Transform; - var inherits$7 = inherits$c.exports; + var Buffer$a = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$a = inherits$f.exports; function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$8.isBuffer(val) && typeof val !== 'string') { + if (!Buffer$a.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer') } } - function HashBase$1 (blockSize) { - Transform.call(this); + function HashBase$2 (blockSize) { + Transform$1.call(this); - this._block = Buffer$8.allocUnsafe(blockSize); + this._block = Buffer$a.allocUnsafe(blockSize); this._blockSize = blockSize; this._blockOffset = 0; this._length = [0, 0, 0, 0]; @@ -26566,9 +30033,9 @@ this._finalized = false; } - inherits$7(HashBase$1, Transform); + inherits$a(HashBase$2, Transform$1); - HashBase$1.prototype._transform = function (chunk, encoding, callback) { + HashBase$2.prototype._transform = function (chunk, encoding, callback) { var error = null; try { this.update(chunk, encoding); @@ -26579,7 +30046,7 @@ callback(error); }; - HashBase$1.prototype._flush = function (callback) { + HashBase$2.prototype._flush = function (callback) { var error = null; try { this.push(this.digest()); @@ -26590,10 +30057,10 @@ callback(error); }; - HashBase$1.prototype.update = function (data, encoding) { + HashBase$2.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data'); if (this._finalized) throw new Error('Digest already called') - if (!Buffer$8.isBuffer(data)) data = Buffer$8.from(data, encoding); + if (!Buffer$a.isBuffer(data)) data = Buffer$a.from(data, encoding); // consume data var block = this._block; @@ -26615,11 +30082,11 @@ return this }; - HashBase$1.prototype._update = function () { + HashBase$2.prototype._update = function () { throw new Error('_update is not implemented') }; - HashBase$1.prototype.digest = function (encoding) { + HashBase$2.prototype.digest = function (encoding) { if (this._finalized) throw new Error('Digest already called') this._finalized = true; @@ -26634,17 +30101,17 @@ return digest }; - HashBase$1.prototype._digest = function () { + HashBase$2.prototype._digest = function () { throw new Error('_digest is not implemented') }; - var hashBase = HashBase$1; + var hashBase = HashBase$2; - var Buffer$7 = require$$0__default$1["default"].Buffer; - var inherits$6 = inherits$c.exports; - var HashBase = hashBase; + var Buffer$9 = require$$0__default$1["default"].Buffer; + var inherits$9 = inherits$f.exports; + var HashBase$1 = hashBase; - var ARRAY16 = new Array(16); + var ARRAY16$1 = new Array(16); var zl = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, @@ -26681,8 +30148,8 @@ var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - function RIPEMD160 () { - HashBase.call(this, 64); + function RIPEMD160$1 () { + HashBase$1.call(this, 64); // state this._a = 0x67452301; @@ -26692,10 +30159,10 @@ this._e = 0xc3d2e1f0; } - inherits$6(RIPEMD160, HashBase); + inherits$9(RIPEMD160$1, HashBase$1); - RIPEMD160.prototype._update = function () { - var words = ARRAY16; + RIPEMD160$1.prototype._update = function () { + var words = ARRAY16$1; for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); var al = this._a | 0; @@ -26733,13 +30200,13 @@ al = el; el = dl; - dl = rotl(cl, 10); + dl = rotl$1(cl, 10); cl = bl; bl = tl; ar = er; er = dr; - dr = rotl(cr, 10); + dr = rotl$1(cr, 10); cr = br; br = tr; } @@ -26753,7 +30220,7 @@ this._a = t; }; - RIPEMD160.prototype._digest = function () { + RIPEMD160$1.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80; if (this._blockOffset > 56) { @@ -26768,7 +30235,7 @@ this._update(); // produce result - var buffer = Buffer$7.alloc ? Buffer$7.alloc(20) : new Buffer$7(20); + var buffer = Buffer$9.alloc ? Buffer$9.alloc(20) : new Buffer$9(20); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -26777,48 +30244,48 @@ return buffer }; - function rotl (x, n) { + function rotl$1 (x, n) { return (x << n) | (x >>> (32 - n)) } function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - var ripemd160$1 = RIPEMD160; + var ripemd160$1 = RIPEMD160$1; var sha_js = {exports: {}}; - var Buffer$6 = safeBuffer.exports.Buffer; + var Buffer$8 = safeBuffer.exports.Buffer; // prototype class for hash functions - function Hash$6 (blockSize, finalSize) { - this._block = Buffer$6.alloc(blockSize); + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$8.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; } - Hash$6.prototype.update = function (data, enc) { + Hash$7.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8'; - data = Buffer$6.from(data, enc); + data = Buffer$8.from(data, enc); } var block = this._block; @@ -26846,7 +30313,7 @@ return this }; - Hash$6.prototype.digest = function (enc) { + Hash$7.prototype.digest = function (enc) { var rem = this._len % this._blockSize; this._block[rem] = 0x80; @@ -26881,11 +30348,11 @@ return enc ? hash.toString(enc) : hash }; - Hash$6.prototype._update = function () { + Hash$7.prototype._update = function () { throw new Error('_update must be implemented by subclass') }; - var hash = Hash$6; + var hash = Hash$7; /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -26895,9 +30362,9 @@ * operation was added. */ - var inherits$5 = inherits$c.exports; - var Hash$5 = hash; - var Buffer$5 = safeBuffer.exports.Buffer; + var inherits$8 = inherits$f.exports; + var Hash$6 = hash; + var Buffer$7 = safeBuffer.exports.Buffer; var K$3 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -26909,10 +30376,10 @@ this.init(); this._w = W$5; - Hash$5.call(this, 64, 56); + Hash$6.call(this, 64, 56); } - inherits$5(Sha, Hash$5); + inherits$8(Sha, Hash$6); Sha.prototype.init = function () { this._a = 0x67452301; @@ -26969,7 +30436,7 @@ }; Sha.prototype._hash = function () { - var H = Buffer$5.allocUnsafe(20); + var H = Buffer$7.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -26980,7 +30447,7 @@ return H }; - var sha$1 = Sha; + var sha$2 = Sha; /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -26991,9 +30458,9 @@ * See http://pajhome.org.uk/crypt/md5 for details. */ - var inherits$4 = inherits$c.exports; - var Hash$4 = hash; - var Buffer$4 = safeBuffer.exports.Buffer; + var inherits$7 = inherits$f.exports; + var Hash$5 = hash; + var Buffer$6 = safeBuffer.exports.Buffer; var K$2 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -27005,10 +30472,10 @@ this.init(); this._w = W$4; - Hash$4.call(this, 64, 56); + Hash$5.call(this, 64, 56); } - inherits$4(Sha1, Hash$4); + inherits$7(Sha1, Hash$5); Sha1.prototype.init = function () { this._a = 0x67452301; @@ -27069,7 +30536,7 @@ }; Sha1.prototype._hash = function () { - var H = Buffer$4.allocUnsafe(20); + var H = Buffer$6.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -27090,9 +30557,9 @@ * */ - var inherits$3 = inherits$c.exports; - var Hash$3 = hash; - var Buffer$3 = safeBuffer.exports.Buffer; + var inherits$6 = inherits$f.exports; + var Hash$4 = hash; + var Buffer$5 = safeBuffer.exports.Buffer; var K$1 = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, @@ -27120,10 +30587,10 @@ this._w = W$3; // new Array(64) - Hash$3.call(this, 64, 56); + Hash$4.call(this, 64, 56); } - inherits$3(Sha256$1, Hash$3); + inherits$6(Sha256$1, Hash$4); Sha256$1.prototype.init = function () { this._a = 0x6a09e667; @@ -27202,7 +30669,7 @@ }; Sha256$1.prototype._hash = function () { - var H = Buffer$3.allocUnsafe(32); + var H = Buffer$5.allocUnsafe(32); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -27226,10 +30693,10 @@ * */ - var inherits$2 = inherits$c.exports; + var inherits$5 = inherits$f.exports; var Sha256 = sha256$1; - var Hash$2 = hash; - var Buffer$2 = safeBuffer.exports.Buffer; + var Hash$3 = hash; + var Buffer$4 = safeBuffer.exports.Buffer; var W$2 = new Array(64); @@ -27238,10 +30705,10 @@ this._w = W$2; // new Array(64) - Hash$2.call(this, 64, 56); + Hash$3.call(this, 64, 56); } - inherits$2(Sha224, Sha256); + inherits$5(Sha224, Sha256); Sha224.prototype.init = function () { this._a = 0xc1059ed8; @@ -27257,7 +30724,7 @@ }; Sha224.prototype._hash = function () { - var H = Buffer$2.allocUnsafe(28); + var H = Buffer$4.allocUnsafe(28); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -27272,9 +30739,9 @@ var sha224 = Sha224; - var inherits$1 = inherits$c.exports; - var Hash$1 = hash; - var Buffer$1 = safeBuffer.exports.Buffer; + var inherits$4 = inherits$f.exports; + var Hash$2 = hash; + var Buffer$3 = safeBuffer.exports.Buffer; var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, @@ -27325,10 +30792,10 @@ this.init(); this._w = W$1; - Hash$1.call(this, 128, 112); + Hash$2.call(this, 128, 112); } - inherits$1(Sha512, Hash$1); + inherits$4(Sha512, Hash$2); Sha512.prototype.init = function () { this._ah = 0x6a09e667; @@ -27512,7 +30979,7 @@ }; Sha512.prototype._hash = function () { - var H = Buffer$1.allocUnsafe(64); + var H = Buffer$3.allocUnsafe(64); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -27533,10 +31000,10 @@ var sha512 = Sha512; - var inherits = inherits$c.exports; + var inherits$3 = inherits$f.exports; var SHA512 = sha512; - var Hash = hash; - var Buffer = safeBuffer.exports.Buffer; + var Hash$1 = hash; + var Buffer$2 = safeBuffer.exports.Buffer; var W = new Array(160); @@ -27544,10 +31011,10 @@ this.init(); this._w = W; - Hash.call(this, 128, 112); + Hash$1.call(this, 128, 112); } - inherits(Sha384, SHA512); + inherits$3(Sha384, SHA512); Sha384.prototype.init = function () { this._ah = 0xcbbb9d5d; @@ -27572,7 +31039,7 @@ }; Sha384.prototype._hash = function () { - var H = Buffer.allocUnsafe(48); + var H = Buffer$2.allocUnsafe(48); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -27600,20 +31067,20 @@ return new Algorithm() }; - exports$1.sha = sha$1; + exports$1.sha = sha$2; exports$1.sha1 = sha1; exports$1.sha224 = sha224; exports$1.sha256 = sha256$1; exports$1.sha384 = sha384; exports$1.sha512 = sha512; - var sha = sha_js.exports; + var sha$1 = sha_js.exports; function hashPublicKey(buffer) { - return new ripemd160$1().update(sha("sha256").update(buffer).digest()).digest(); + return new ripemd160$1().update(sha$1("sha256").update(buffer).digest()).digest(); } - var __extends$3 = (undefined && undefined.__extends) || (function () { + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -27641,7 +31108,7 @@ * and calls an abstract method to do the actual work. */ var SingleKeyAccount = /** @class */ (function (_super) { - __extends$3(SingleKeyAccount, _super); + __extends$4(SingleKeyAccount, _super); function SingleKeyAccount() { return _super !== null && _super.apply(this, arguments) || this; } @@ -27672,16 +31139,16 @@ return SingleKeyAccount; }(BaseAccount)); var p2pkh = /** @class */ (function (_super) { - __extends$3(p2pkh, _super); + __extends$4(p2pkh, _super); function p2pkh() { return _super !== null && _super.apply(this, arguments) || this; } p2pkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$g.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE])); buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$g.from([OP_EQUALVERIFY, OP_CHECKSIG])); + buf.writeSlice(Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG])); return { scriptPubKey: buf.buffer() }; }; p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { @@ -27700,7 +31167,7 @@ return p2pkh; }(SingleKeyAccount)); var p2tr = /** @class */ (function (_super) { - __extends$3(p2tr, _super); + __extends$4(p2tr, _super); function p2tr() { return _super !== null && _super.apply(this, arguments) || this; } @@ -27708,7 +31175,7 @@ var xonlyPubkey = pubkey.slice(1); // x-only pubkey var buf = new BufferWriter(); var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$g.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(Buffer$i.from([0x51, 32])); // push1, pubkeylen buf.writeSlice(outputKey); return { scriptPubKey: buf.buffer() }; }; @@ -27731,8 +31198,8 @@ p2tr.prototype.hashTapTweak = function (x) { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$g.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$g.concat([h, h, x])); + var h = crypto_1.sha256(Buffer$i.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$i.concat([h, h, x])); }; /** * Calculates a taproot output key from an internal key. This output key will be @@ -27751,13 +31218,13 @@ // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$g.concat([ - Buffer$g.from([0x02]), + var evenEcdsaPubkey = Buffer$i.concat([ + Buffer$i.from([0x02]), internalPubkey, ]); var tweak = this.hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$g.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); + var outputEcdsaKey = Buffer$i.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. var outputSchnorrKey = outputEcdsaKey.slice(1); // Create address @@ -27766,7 +31233,7 @@ return p2tr; }(SingleKeyAccount)); var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$3(p2wpkhWrapped, _super); + __extends$4(p2wpkhWrapped, _super); function p2wpkhWrapped() { return _super !== null && _super.apply(this, arguments) || this; } @@ -27774,7 +31241,7 @@ var buf = new BufferWriter(); var redeemScript = this.createRedeemScript(pubkey); var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$g.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$i.from([OP_HASH160, HASH_SIZE])); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; @@ -27804,19 +31271,19 @@ }; p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { var pubkeyHash = hashPublicKey(pubkey); - return Buffer$g.concat([Buffer$g.from("0014", "hex"), pubkeyHash]); + return Buffer$i.concat([Buffer$i.from("0014", "hex"), pubkeyHash]); }; return p2wpkhWrapped; }(SingleKeyAccount)); var p2wpkh = /** @class */ (function (_super) { - __extends$3(p2wpkh, _super); + __extends$4(p2wpkh, _super); function p2wpkh() { return _super !== null && _super.apply(this, arguments) || this; } p2wpkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$g.from([0, HASH_SIZE])); + buf.writeSlice(Buffer$i.from([0, HASH_SIZE])); buf.writeSlice(pubkeyHash); return { scriptPubKey: buf.buffer() }; }; @@ -27837,7 +31304,7 @@ return p2wpkh; }(SingleKeyAccount)); - var __read$2 = (undefined && undefined.__read) || function (o, n) { + var __read$3 = (undefined && undefined.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; @@ -27853,7 +31320,7 @@ } return ar; }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); @@ -27897,7 +31364,7 @@ var n = leaves.length; if (n == 0) { return { - root: new Node(undefined, undefined, Buffer$g.alloc(32, 0)), + root: new Node(undefined, undefined, Buffer$i.alloc(32, 0)), leaves: [] }; } @@ -27917,16 +31384,16 @@ return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; }; Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$g.concat([Buffer$g.from([1]), left, right])); + return this.h(Buffer$i.concat([Buffer$i.from([1]), left, right])); }; return Merkle; }()); function hashLeaf(buf, hashFunction) { if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$g.from([0]), buf, hashFunction); + return hashConcat(Buffer$i.from([0]), buf, hashFunction); } function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$g.concat([bufA, bufB])); + return hashFunction(Buffer$i.concat([bufA, bufB])); } var Node = /** @class */ (function () { function Node(left, right, hash) { @@ -27947,13 +31414,13 @@ if (!node.parent.rightChild) { throw new Error("Expected right child to exist"); } - return __spreadArray$2([node.parent.rightChild.hash], __read$2(proveNode(node.parent)), false); + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); } else { if (!node.parent.leftChild) { throw new Error("Expected left child to exist"); } - return __spreadArray$2([node.parent.leftChild.hash], __read$2(proveNode(node.parent)), false); + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); } } function highestPowerOf2LessThan(n) { @@ -27991,13 +31458,13 @@ }; WalletPolicy.prototype.serialize = function () { var keyBuffers = this.keys.map(function (k) { - return Buffer$g.from(k, "ascii"); + return Buffer$i.from(k, "ascii"); }); var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); var buf = new BufferWriter(); buf.writeUInt8(0x01); // wallet type (policy map) buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$g.from(this.descriptorTemplate, "ascii")); + buf.writeVarSlice(Buffer$i.from(this.descriptorTemplate, "ascii")); buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); return buf.buffer(); }; @@ -28020,7 +31487,7 @@ tx.writeUInt32(psbt.getGlobalTxVersion()); var isSegwit = !!psbt.getInputWitnessUtxo(0); if (isSegwit) { - tx.writeSlice(Buffer$g.from([0, 1])); + tx.writeSlice(Buffer$i.from([0, 1])); } var inputCount = psbt.getGlobalInputCount(); tx.writeVarInt(inputCount); @@ -28028,7 +31495,7 @@ for (var i = 0; i < inputCount; i++) { tx.writeSlice(psbt.getInputPreviousTxid(i)); tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$g.from([])); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$i.from([])); tx.writeUInt32(psbt.getInputSequence(i)); if (isSegwit) { witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); @@ -28045,7 +31512,7 @@ return tx.buffer(); } - var __extends$2 = (undefined && undefined.__extends) || (function () { + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -28060,8 +31527,8 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -28069,7 +31536,7 @@ } return t; }; - return __assign$4.apply(this, arguments); + return __assign$5.apply(this, arguments); }; var psbtGlobal; (function (psbtGlobal) { @@ -28104,9 +31571,9 @@ psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$g.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var PSBT_MAGIC_BYTES = Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { - __extends$2(NoSuchEntry, _super); + __extends$3(NoSuchEntry, _super); function NoSuchEntry() { return _super !== null && _super.apply(this, arguments) || this; } @@ -28330,11 +31797,11 @@ }); }; PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$g.from(v)); }); + from.forEach(function (v, k) { return to.set(k, Buffer$i.from(v)); }); }; PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - buf.writeSlice(Buffer$g.from([0x70, 0x73, 0x62, 0x74, 0xff])); + buf.writeSlice(Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff])); serializeMap(buf, this.globalMap); this.inputMaps.forEach(function (map) { serializeMap(buf, map); @@ -28378,17 +31845,17 @@ var result = []; map.forEach(function (_v, k) { if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$g.from(k.substring(2), "hex")); + result.push(Buffer$i.from(k.substring(2), "hex")); } }); return result; }; PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$g.from(hexKey.substring(0, 2), "hex").readUInt8(0); + var keyType = Buffer$i.from(hexKey.substring(0, 2), "hex").readUInt8(0); return keyTypes.some(function (k) { return k == keyType; }); }; PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$g.from([])); + var key = new Key(keyType, Buffer$i.from([])); this.globalMap.set(key.toString(), value); }; PsbtV2.prototype.getGlobal = function (keyType) { @@ -28458,7 +31925,7 @@ hashes.push(buf.readSlice(32)); } var deriv = this.readBip32Derivation(buf); - return __assign$4({ hashes: hashes }, deriv); + return __assign$5({ hashes: hashes }, deriv); }; return PsbtV2; }()); @@ -28474,7 +31941,7 @@ throw new NoSuchEntry(key.toString()); } // Make sure to return a copy, to protect the underlying data. - return Buffer$g.from(value); + return Buffer$i.from(value); } var Key = /** @class */ (function () { function Key(keyType, keyData) { @@ -28513,25 +31980,25 @@ function serializeMap(buf, map) { for (var k in map.keys) { var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$g.from(k, "hex")), value); + var keyPair = new KeyPair(createKey(Buffer$i.from(k, "hex")), value); keyPair.serialize(buf); } buf.writeUInt8(0); } function b() { - return Buffer$g.from([]); + return Buffer$i.from([]); } function set(map, keyType, keyData, value) { var key = new Key(keyType, keyData); map.set(key.toString(), value); } function uint32LE(n) { - var b = Buffer$g.alloc(4); + var b = Buffer$i.alloc(4); b.writeUInt32LE(n, 0); return b; } function uint64LE(n) { - var b = Buffer$g.alloc(8); + var b = Buffer$i.alloc(8); b.writeBigUInt64LE(BigInt(n), 0); return b; } @@ -28666,7 +32133,7 @@ } else if (data.length <= 256 * 256) { buf.writeUInt8(77); - var b = Buffer$g.alloc(2); + var b = Buffer$i.alloc(2); b.writeUInt16LE(data.length, 0); buf.writeSlice(b); } @@ -28693,18 +32160,18 @@ } function createVarint(value) { if (value < 0xfd) { - var buffer_1 = Buffer$g.alloc(1); + var buffer_1 = Buffer$i.alloc(1); buffer_1[0] = value; return buffer_1; } if (value <= 0xffff) { - var buffer_2 = Buffer$g.alloc(3); + var buffer_2 = Buffer$i.alloc(3); buffer_2[0] = 0xfd; buffer_2[1] = value & 0xff; buffer_2[2] = (value >> 8) & 0xff; return buffer_2; } - var buffer = Buffer$g.alloc(5); + var buffer = Buffer$i.alloc(5); buffer[0] = 0xfe; buffer[1] = value & 0xff; buffer[2] = (value >> 8) & 0xff; @@ -28720,11 +32187,11 @@ */ function serializeTransactionOutputs(_a) { var outputs = _a.outputs; - var outputBuffer = Buffer$g.alloc(0); + var outputBuffer = Buffer$i.alloc(0); if (typeof outputs !== "undefined") { - outputBuffer = Buffer$g.concat([outputBuffer, createVarint(outputs.length)]); + outputBuffer = Buffer$i.concat([outputBuffer, createVarint(outputs.length)]); outputs.forEach(function (output) { - outputBuffer = Buffer$g.concat([ + outputBuffer = Buffer$i.concat([ outputBuffer, output.amount, createVarint(output.script.length), @@ -28738,18 +32205,18 @@ if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$g.alloc(0); + var inputBuffer = Buffer$i.alloc(0); var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; transaction.inputs.forEach(function (input) { inputBuffer = isDecred || isBech32 - ? Buffer$g.concat([ + ? Buffer$i.concat([ inputBuffer, input.prevout, - Buffer$g.from([0x00]), + Buffer$i.from([0x00]), input.sequence, ]) - : Buffer$g.concat([ + : Buffer$i.concat([ inputBuffer, input.prevout, createVarint(input.script.length), @@ -28760,26 +32227,26 @@ var outputBuffer = serializeTransactionOutputs(transaction); if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$g.concat([ + outputBuffer = Buffer$i.concat([ outputBuffer, - (useWitness && transaction.witness) || Buffer$g.alloc(0), + (useWitness && transaction.witness) || Buffer$i.alloc(0), transaction.locktime, - transaction.nExpiryHeight || Buffer$g.alloc(0), - transaction.extraData || Buffer$g.alloc(0), + transaction.nExpiryHeight || Buffer$i.alloc(0), + transaction.extraData || Buffer$i.alloc(0), ]); } - return Buffer$g.concat([ + return Buffer$i.concat([ transaction.version, - timestamp ? timestamp : Buffer$g.alloc(0), - transaction.nVersionGroupId || Buffer$g.alloc(0), - useWitness ? Buffer$g.from("0001", "hex") : Buffer$g.alloc(0), + timestamp ? timestamp : Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), + useWitness ? Buffer$i.from("0001", "hex") : Buffer$i.alloc(0), createVarint(transaction.inputs.length), inputBuffer, outputBuffer, ]); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -28788,7 +32255,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -28869,9 +32336,9 @@ */ BtcNew.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, xpubComponents; - return __generator$b(this, function (_b) { + return __generator$e(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -28896,9 +32363,9 @@ */ BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$b(this, function (_c) { + return __generator$e(this, function (_c) { switch (_c.label) { case 0: pathElements = pathStringToArray(path); @@ -28910,7 +32377,7 @@ case 2: address = _c.sent(); components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$g.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); + uncompressedPubkey = Buffer$i.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); return [2 /*return*/, { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, @@ -28936,9 +32403,9 @@ * ourselves, but we don't at this time, and instead return an empty ("") address. */ BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$b(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: accountPath = hardenedPathOf(pathElements); @@ -28953,7 +32420,7 @@ masterFingerprint = _a.sent(); policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$g.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$i.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; } }); }); @@ -28967,9 +32434,9 @@ * transaction is returned. */ BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$b(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputCount = arg.inputs.length; @@ -29022,7 +32489,7 @@ i++; return [3 /*break*/, 2]; case 7: - outputsConcat = Buffer$g.from(arg.outputScriptHex, "hex"); + outputsConcat = Buffer$i.from(arg.outputScriptHex, "hex"); outputsBufferReader = new BufferReader(outputsConcat); outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); @@ -29080,9 +32547,9 @@ * properties depend on the accountType used. */ BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElems, i, xpub, pubkey, cond; - return __generator$b(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: if (!path) @@ -29111,14 +32578,14 @@ * public key and its derivation path. */ BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$b(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputTx = input[0]; spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$g.from(input[2], "hex") : undefined; + redeemScript = input[2] ? Buffer$i.from(input[2], "hex") : undefined; sequence = input[3]; if (sequence) { psbt.setInputSequence(i, sequence); @@ -29158,11 +32625,11 @@ * to the appropriate input fields of the PSBT. */ BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var sigs; - return __generator$b(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$g.alloc(32, 0), progressCallback)]; + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$i.alloc(32, 0), progressCallback)]; case 1: sigs = _a.sent(); sigs.forEach(function (v, k) { @@ -29211,17 +32678,17 @@ return new p2pkh(psbt, masterFp); } - var id$1 = 0; + var id$2 = 0; var subscribers$1 = []; /** * log something * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) * @param message a clear message of the log associated to the type */ - var log = function (type, message, data) { + var log$1 = function (type, message, data) { var obj = { type: type, - id: String(++id$1), + id: String(++id$2), date: new Date() }; if (message) @@ -29260,8 +32727,14 @@ window.__ledgerLogsListen = listen$1; } - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log$1, + listen: listen$1 + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -29269,9 +32742,9 @@ } return t; }; - return __assign$3.apply(this, arguments); + return __assign$4.apply(this, arguments); }; - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -29280,7 +32753,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -29314,12 +32787,12 @@ cashaddr: 3 }; function getWalletPublicKey(transport, options) { - return __awaiter$a(this, void 0, void 0, function () { + return __awaiter$d(this, void 0, void 0, function () { var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$a(this, function (_b) { + return __generator$d(this, function (_b) { switch (_b.label) { case 0: - _a = __assign$3({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; if (!(format in addressFormatMap)) { throw new Error("btc.getWalletPublicKey invalid format=" + format); } @@ -29378,7 +32851,7 @@ var invariant_1 = invariant; - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -29387,7 +32860,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -29414,7 +32887,7 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$5 = (undefined && undefined.__values) || function(o) { + var __values$7 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -29426,17 +32899,17 @@ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$9(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var data, firstRound, prefix, trustedInput, res; - return __generator$9(this, function (_a) { + return __generator$c(this, function (_a) { switch (_a.label) { case 0: firstRound = false; if (typeof indexLookup === "number") { firstRound = true; - prefix = Buffer$g.alloc(4); + prefix = Buffer$i.alloc(4); prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$g.concat([prefix, transactionData], transactionData.length + 4); + data = Buffer$i.concat([prefix, transactionData], transactionData.length + 4); } else { data = transactionData; @@ -29452,11 +32925,11 @@ } function getTrustedInput(transport, indexLookup, transaction, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$9(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; var e_1, _a, e_2, _b; var _this = this; - return __generator$9(this, function (_c) { + return __generator$c(this, function (_c) { switch (_c.label) { case 0: version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; @@ -29465,13 +32938,13 @@ } isDecred = additionals.includes("decred"); isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$9(_this, void 0, void 0, function () { + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; var e_3, _a; - return __generator$9(this, function (_b) { + return __generator$c(this, function (_b) { switch (_b.label) { case 0: - seq = sequence || Buffer$g.alloc(0); + seq = sequence || Buffer$i.alloc(0); scriptBlocks = []; offset = 0; while (offset !== script.length) { @@ -29482,7 +32955,7 @@ scriptBlocks.push(script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$g.concat([script.slice(offset, offset + blockSize), seq])); + scriptBlocks.push(Buffer$i.concat([script.slice(offset, offset + blockSize), seq])); } offset += blockSize; } @@ -29494,7 +32967,7 @@ _b.label = 1; case 1: _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); _b.label = 2; case 2: if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; @@ -29524,10 +32997,10 @@ processWholeScriptBlock = function (block) { return getTrustedInputRaw(transport, block); }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$g.concat([ + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$i.concat([ transaction.version, - transaction.timestamp || Buffer$g.alloc(0), - transaction.nVersionGroupId || Buffer$g.alloc(0), + transaction.timestamp || Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), createVarint(inputs.length), ]), indexLookup)]; case 1: @@ -29535,20 +33008,20 @@ _c.label = 2; case 2: _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); _c.label = 3; case 3: if (!!inputs_1_1.done) return [3 /*break*/, 7]; input = inputs_1_1.value; isXSTV2 = isXST && - Buffer$g.compare(version, Buffer$g.from([0x02, 0x00, 0x00, 0x00])) === 0; + Buffer$i.compare(version, Buffer$i.from([0x02, 0x00, 0x00, 0x00])) === 0; treeField = isDecred - ? input.tree || Buffer$g.from([0x00]) - : Buffer$g.alloc(0); - data = Buffer$g.concat([ + ? input.tree || Buffer$i.from([0x00]) + : Buffer$i.alloc(0); + data = Buffer$i.concat([ input.prevout, treeField, - isXSTV2 ? Buffer$g.from([0x00]) : createVarint(input.script.length), + isXSTV2 ? Buffer$i.from([0x00]) : createVarint(input.script.length), ]); return [4 /*yield*/, getTrustedInputRaw(transport, data)]; case 4: @@ -29558,7 +33031,7 @@ // deferred.notify("input"); // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$g.concat([input.script, input.sequence])) + ? processWholeScriptBlock(Buffer$i.concat([input.script, input.sequence])) : isXSTV2 ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence))]; @@ -29589,14 +33062,14 @@ _c.label = 12; case 12: _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); _c.label = 13; case 13: if (!!outputs_1_1.done) return [3 /*break*/, 16]; output = outputs_1_1.value; - data = Buffer$g.concat([ + data = Buffer$i.concat([ output.amount, - isDecred ? Buffer$g.from([0x00, 0x00]) : Buffer$g.alloc(0), + isDecred ? Buffer$i.from([0x00, 0x00]) : Buffer$i.alloc(0), createVarint(output.script.length), output.script, ]); @@ -29627,21 +33100,429 @@ endData.push(extraData); } if (endData.length) { - data = Buffer$g.concat(endData); + data = Buffer$i.concat(endData); extraPart = isDecred ? data - : Buffer$g.concat([createVarint(data.length), data]); + : Buffer$i.concat([createVarint(data.length), data]); } - return [4 /*yield*/, processScriptBlocks(Buffer$g.concat([locktime, extraPart || Buffer$g.alloc(0)]))]; + return [4 /*yield*/, processScriptBlocks(Buffer$i.concat([locktime, extraPart || Buffer$i.alloc(0)]))]; case 20: res = _c.sent(); invariant_1(res, "missing result in processScriptBlocks"); return [2 /*return*/, res]; } - }); + }); + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$i.concat([ + transaction.version, + transaction.timestamp || Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$i.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$i.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$i.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$i.from([0x00]); + } + } + data = Buffer$i.concat([ + prefix, + inputValue, + isDecred ? Buffer$i.from([0x00]) : Buffer$i.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$i.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha$1("sha256") + .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$i.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$i.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$i.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$i.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$i.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$i.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$i.from([0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([sigHashType]), + ]) + : Buffer$i.concat([ + pathsBuffer, + Buffer$i.from([0x00]), + lockTimeBuffer, + Buffer$i.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$i.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + invariant_1(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); } + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -29678,7 +33559,7 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$4 = (undefined && undefined.__values) || function(o) { + var __values$5 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -29689,213 +33570,463 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { return __awaiter$8(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$8(this, function (_e) { - switch (_e.label) { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { case 0: - data = Buffer$g.concat([ - transaction.version, - transaction.timestamp || Buffer$g.alloc(0), - transaction.nVersionGroupId || Buffer$g.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$4(transaction.inputs), _b = _a.next(); - _e.label = 3; + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$g.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$g.from([0x02]); - } + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; } else { - if (inputs[i].trustedInput) { - prefix = Buffer$g.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$g.from([0x00]); - } + throw e_1; } - data = Buffer$g.concat([ - prefix, - inputValue, - isDecred ? Buffer$g.from([0x00]) : Buffer$g.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + return [3 /*break*/, 4]; case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$g.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$i.alloc(0); + nullPrevout = Buffer$i.alloc(0); + defaultVersion = Buffer$i.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$i.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$i.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; case 7: - _e.sent(); - _e.label = 8; + trustedInput = _b.sent(); + log$1("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$i.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$i.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$i.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; + case 10: return [3 /*break*/, 13]; case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); } - finally { if (e_1) throw e_1.error; } + finally { if (e_2) throw e_2.error; } return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$i.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$i.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$i.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$i.concat([ + Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$i.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$i.concat([ + Buffer$i.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$i.alloc(1); + keySize = Buffer$i.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$i.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$i.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$i.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$i.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$i.concat([ + Buffer$i.from("02", "hex"), + Buffer$i.from([signatures[i].length]), + signatures[i], + Buffer$i.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$i.concat([witness, tmpScriptData]); + } + result = Buffer$i.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$i.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$i.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$i.alloc(0), + targetTransaction.extraData || Buffer$i.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$i.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$i.concat([ + decredWitness_1, + Buffer$i.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([0xff, 0xff, 0xff, 0xff]), + Buffer$i.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$i.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } + + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$i.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$i.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$i.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; } }); }); } - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); - } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); - } - var hash = sha("sha256") - .update(sha("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$g.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); - } - hash = Buffer$g.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$g.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$g.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$g.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$g.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$g.from([0x00, 0x00, 0x00, 0x00]), - Buffer$g.from([sigHashType]), - ]) - : Buffer$g.concat([ - pathsBuffer, - Buffer$g.from([0x00]), - lockTimeBuffer, - Buffer$g.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$g.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - return result; - }); - } - - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -29904,7 +34035,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -29931,45 +34062,169 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$7(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$7(this, function (_a) { - switch (_a.label) { + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$i.alloc(0); + nullPrevout = Buffer$i.alloc(0); + defaultVersion = Buffer$i.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$i.from(outputScriptHex, "hex"); + _c.label = 1; case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$i.from(trustedInput, "hex") + : Buffer$i.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$i.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; } }); }); } - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -29978,7 +34233,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -30005,86 +34260,384 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$6(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$6(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - invariant_1(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$i.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$i.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$i.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$i.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$i.concat([ + Buffer$i.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$i.concat([ + asBufferUInt32BE(version), + Buffer$i.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$i.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$1("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$1().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$i.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); } - return t; + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$i.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } + return to.concat(ar || Array.prototype.slice.call(from)); }; var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; @@ -30097,463 +34650,296 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$5(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$2(__assign$2({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$g.alloc(0); - nullPrevout = Buffer$g.alloc(0); - defaultVersion = Buffer$g.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$g.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$g.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$g.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$g.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$g.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$g.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$g.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$g.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$g.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$g.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$g.concat([ - Buffer$g.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$g.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$g.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$g.concat([ - Buffer$g.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer$g.alloc(1); - keySize = Buffer$g.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$g.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$g.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$g.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$g.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$g.concat([ - Buffer$g.from("02", "hex"), - Buffer$g.from([signatures[i].length]), - signatures[i], - Buffer$g.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$g.concat([witness, tmpScriptData]); - } - result = Buffer$g.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$g.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$g.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$g.alloc(0), - targetTransaction.extraData || Buffer$g.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$g.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$g.concat([ - decredWitness_1, - Buffer$g.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$g.from([0x00, 0x00, 0x00, 0x00]), - Buffer$g.from([0xff, 0xff, 0xff, 0xff]), - Buffer$g.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$g.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$i.from(request.subarray(1))); + this.progressCallback(); + return Buffer$i.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$i.from([known_preimage[i]])); + } + } + return Buffer$i.concat([ + preimage_len_varint, + Buffer$i.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$i.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$i.from([proof.length]), + Buffer$i.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; } - }); - }); - } - - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + } + return Buffer$i.concat([Buffer$i.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$i.concat(__spreadArray$1([ + Buffer$i.from([n_returned_elements]), + Buffer$i.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } } - }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$4(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$4(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$g.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$4(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$g.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$g.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$i.concat([Buffer$i.from([0]), el]); + this.addKnownPreimage(preimage); } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; } - return t; + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); + + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -30562,7 +34948,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -30600,158 +34986,375 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$3(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$3(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$1(__assign$1({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$g.alloc(0); - nullPrevout = Buffer$g.alloc(0); - defaultVersion = Buffer$g.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$g.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$g.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$g.from(trustedInput, "hex") - : Buffer$g.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$g.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$g.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$1(__assign$1({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$i.concat([ + Buffer$i.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$i.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$i.concat([ + Buffer$i.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$i.alloc(32, 0), + Buffer$i.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$i.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$i.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$i.from([]))]; + }); }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); }); + return str; } - var __assign = (undefined && undefined.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$i.alloc(0); + var nExpiryHeight = Buffer$i.alloc(0); + var nVersionGroupId = Buffer$i.alloc(0); + var extraData = Buffer$i.alloc(0); + var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); + var transaction = Buffer$i.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$i.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$i.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$i.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$i.from([0x02, 0x00, 0x00, 0x00])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; } - return t; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$i.alloc(0); + var tree = Buffer$i.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData }; - return __assign.apply(this, arguments); - }; - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } + + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -30760,7 +35363,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -30791,54 +35394,34 @@ * Bitcoin API. * * @example - * import Btc from "@ledgerhq/hw-app-btc"; + * import Btc from "@backpacker69/hw-app-btc"; * const btc = new Btc(transport) */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; this.transport = transport; - this.derivationsCache = {}; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$2(this, void 0, void 0, function () { - var res; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$2(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$2(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$g.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$g.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$g.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); }; /** * @param path a BIP 32 path @@ -30846,7 +35429,7 @@ * * - verify (boolean) will ask user to confirm the address on the device * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. * * NB The normal usage is to use: * @@ -30854,7 +35437,7 @@ * * - p2sh format with 49' paths * - * - bech32 format with 173' paths + * - bech32 format with 84' paths * * - cashaddr in case of Bitcoin Cash * @@ -30862,11 +35445,55 @@ * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; } - return getWalletPublicKey(this.transport, __assign(__assign({}, opts), { path: path })); + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); }; /** * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. @@ -30877,11 +35504,8 @@ console.log("Signature : " + signature); }).catch(function(ex) {console.log(ex);}); */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); }; /** * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters @@ -30893,20 +35517,21 @@ * * sequence is the sequence number to use for this input (when using RBF), or non present * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount * @param lockTime is the optional lockTime of the transaction to sign, or default (0) * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) * @param additionals list of additionnal options * * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs * - "abc" for bch * - "gold" for btg * - "bipxxx" for using BIPxxx * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. * @return the signed transaction ready to be broadcast * @example btc.createTransaction({ @@ -30915,232 +35540,597 @@ outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" }).then(res => ...); */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { + Btc.prototype.createPaymentTransactionNew = function (arg) { if (arguments.length > 1) { console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); } - return createTransaction(this.transport, arg); + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); - } - return signP2SHTransaction(this.transport, arg); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses$1 = {}; + var deserializers$1 = {}; + var addCustomErrorDeserializer$1 = function (name, deserializer) { + deserializers$1[name] = deserializer; + }; + var createCustomErrorClass$1 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$g.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$g.concat([ - Buffer$g.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); + C.prototype = new Error(); + errorClasses$1[name] = C; + return C; }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$g.concat([ - asBufferUInt32BE(version), - Buffer$g.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$g.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$1().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers$1[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass$1(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } } } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$g.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; } - return ar; + return value; }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; } } - return to.concat(ar || Array.prototype.slice.call(from)); - }; + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); + var AmountRequired = createCustomErrorClass$1("AmountRequired"); + var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass$1("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass$1("NetworkDown"); + var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); + var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass$1("FeeRequired"); + var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); + var SyncError = createCustomErrorClass$1("SyncError"); + var PairingFailed = createCustomErrorClass$1("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); + var DBNotReset = createCustomErrorClass$1("DBNotReset"); /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$1(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$1([], __read$1(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$1([], __read$1(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; + function TransportError$1(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); + var StatusCodes$1 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$1(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$1([], __read$1(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$g.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$1(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$1(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass$1, + addCustomErrorDeserializer: addCustomErrorDeserializer$1, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition$1, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError$1, + StatusCodes: StatusCodes$1, + getAltStatusMessage: getAltStatusMessage$1, + TransportStatusError: TransportStatusError$1 + }); + + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; var __read = (undefined && undefined.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; @@ -31166,7 +36156,7 @@ } return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$1 = (undefined && undefined.__values) || function(o) { + var __values = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -31177,294 +36167,449 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { - } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport$1 = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter__default["default"](); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$i.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$i.concat([ + Buffer$i.from([cla, ins, p1, p2]), + Buffer$i.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError$1(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$g.from(request.subarray(1))); - this.progressCallback(); - return Buffer$g.from(""); + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$g.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$g.from([known_preimage[i]])); - } - } - return Buffer$g.concat([ - preimage_len_varint, - Buffer$g.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; - } - GetMerkleLeafProofCommand.prototype.execute = function (request) { + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray([], __read(proof.slice(-n_leftover_elements)), false)); + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - return Buffer$g.concat(__spreadArray([ - mt.getLeafHash(leaf_index), - Buffer$g.from([proof.length]), - Buffer$g.from([n_response_elements]) - ], __read(proof.slice(0, n_response_elements)), false)); + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; - } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$g.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$g.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$g.concat([Buffer$g.from([found]), createVarint(leaf_index)]); + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; - } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); - } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); - } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$g.concat(__spreadArray([ - Buffer$g.from([n_returned_elements]), - Buffer$g.from([element_len]) - ], __read(returned_elements), false)); + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; try { - for (var commands_1 = __values$1(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); } finally { if (e_1) throw e_1.error; } } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$1(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$g.concat([Buffer$g.from([0]), el]); - this.addKnownPreimage(preimage); + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); + + var hidFraming$1 = {}; + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$i.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$i.alloc(0), + dataLength: 0, + sequence: 0 + }; + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$i.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$i.concat([ + data, + Buffer$i.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$i.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$i.concat([head, chunk])); } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$i.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; } - finally { if (e_2) throw e_2.error; } } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); + }; + exports["default"] = createHIDframing; + + }(hidFraming$1)); + + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + + var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); + return __assign.apply(this, arguments); + }; + var _a; + var DeviceModelId; + (function (DeviceModelId) { + DeviceModelId["blue"] = "blue"; + DeviceModelId["nanoS"] = "nanoS"; + DeviceModelId["nanoSP"] = "nanoSP"; + DeviceModelId["nanoX"] = "nanoX"; + })(DeviceModelId || (DeviceModelId = {})); + var devices = (_a = {}, + _a[DeviceModelId.blue] = { + id: DeviceModelId.blue, + productName: "Ledger Blue", + productIdMM: 0x00, + legacyUsbProductId: 0x0000, + usbOnly: true, + memorySize: 480 * 1024, + masks: [0x31000000, 0x31010000], + getBlockSize: function (_firwareVersion) { return 4 * 1024; } + }, + _a[DeviceModelId.nanoS] = { + id: DeviceModelId.nanoS, + productName: "Ledger Nano S", + productIdMM: 0x10, + legacyUsbProductId: 0x0001, + usbOnly: true, + memorySize: 320 * 1024, + masks: [0x31100000], + getBlockSize: function (firmwareVersion) { + var _a; + return semver.lt((_a = semver.coerce(firmwareVersion)) !== null && _a !== void 0 ? _a : "", "2.0.0") + ? 4 * 1024 + : 2 * 1024; } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); + }, + _a[DeviceModelId.nanoSP] = { + id: DeviceModelId.nanoSP, + productName: "Ledger Nano SP", + productIdMM: 0x50, + legacyUsbProductId: 0x0005, + usbOnly: true, + memorySize: 1533 * 1024, + masks: [0x33100000], + getBlockSize: function (_firmwareVersion) { return 32; } + }, + _a[DeviceModelId.nanoX] = { + id: DeviceModelId.nanoX, + productName: "Ledger Nano X", + productIdMM: 0x40, + legacyUsbProductId: 0x0004, + usbOnly: false, + memorySize: 2 * 1024 * 1024, + masks: [0x33000000], + getBlockSize: function (_firwareVersion) { return 4 * 1024; }, + bluetoothSpec: [ + { + // this is the legacy one (prototype version). we will eventually drop it. + serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", + notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", + writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66", + writeCmdUuid: "d973f2e3-b19e-11e2-9e96-0800200c9a66" + }, + { + serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", + notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", + writeUuid: "13d63400-2c97-0004-0002-4c6564676572", + writeCmdUuid: "13d63400-2c97-0004-0003-4c6564676572" + }, + ] + }, + _a); + ({ + Blue: DeviceModelId.blue, + "Nano S": DeviceModelId.nanoS, + "Nano X": DeviceModelId.nanoX + }); + var devicesList = Object.values(devices); + /** + * + */ + var ledgerUSBVendorId = 0x2c97; + /** + * + */ + var identifyUSBProductId = function (usbProductId) { + var legacy = devicesList.find(function (d) { return d.legacyUsbProductId === usbProductId; }); + if (legacy) + return legacy; + var mm = usbProductId >> 8; + var deviceModel = devicesList.find(function (d) { return d.productIdMM === mm; }); + return deviceModel; + }; + var bluetoothServices = []; + var serviceUuidToInfos = {}; + for (var id$1 in devices) { + var deviceModel = devices[id$1]; + var bluetoothSpec = deviceModel.bluetoothSpec; + if (bluetoothSpec) { + for (var i = 0; i < bluetoothSpec.length; i++) { + var spec = bluetoothSpec[i]; + bluetoothServices.push(spec.serviceUuid); + serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = __assign({ deviceModel: deviceModel }, spec); } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); + } + } var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -31502,385 +36647,75 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$1(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$1(this, void 0, void 0, function () { - var response; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$g.concat([ - Buffer$g.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$1(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$g.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$g.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$g.concat([ - Buffer$g.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$g.alloc(32, 0), - Buffer$g.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$1(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$1(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$g.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$g.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$g.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$1(this, void 0, void 0, function () { - return __generator$1(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$g.from([]))]; - }); + var ledgerDevices = [ + { + vendorId: ledgerUSBVendorId + }, + ]; + function requestLedgerDevice() { + return __awaiter$1(this, void 0, void 0, function () { + var device; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, navigator.usb.requestDevice({ + filters: ledgerDevices + })]; + case 1: + device = _a.sent(); + return [2 /*return*/, device]; + } }); - }; - return AppClient; - }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); }); - return str; } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$g.alloc(0); - var nExpiryHeight = Buffer$g.alloc(0); - var nVersionGroupId = Buffer$g.alloc(0); - var extraData = Buffer$g.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$g.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$g.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$g.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$g.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$g.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$g.alloc(0); - var tree = Buffer$g.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree + function getLedgerDevices() { + return __awaiter$1(this, void 0, void 0, function () { + var devices; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, navigator.usb.getDevices()]; + case 1: + devices = _a.sent(); + return [2 /*return*/, devices.filter(function (d) { return d.vendorId === ledgerUSBVendorId; })]; + } }); - } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script + }); + } + function getFirstLedgerDevice() { + return __awaiter$1(this, void 0, void 0, function () { + var existingDevices; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getLedgerDevices()]; + case 1: + existingDevices = _a.sent(); + if (existingDevices.length > 0) + return [2 /*return*/, existingDevices[0]]; + return [2 /*return*/, requestLedgerDevice()]; + } }); - } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } - else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } - } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; + }); } + var isSupported$1 = function () { + return Promise.resolve(!!navigator && + !!navigator.usb && + typeof navigator.usb.getDevices === "function"); + }; + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -31917,688 +36752,1171 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; + var configurationValue = 1; + var endpointNumber = 3; /** - * Bitcoin API. - * + * WebUSB Transport implementation * @example - * import Btc from "@backpacker69/hw-app-btc"; - * const btc = new Btc(transport) + * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + var TransportWebUSB = /** @class */ (function (_super) { + __extends(TransportWebUSB, _super); + function TransportWebUSB(device, interfaceNumber) { + var _this = _super.call(this) || this; + _this.channel = Math.floor(Math.random() * 0xffff); + _this.packetSize = 64; + _this._disconnectEmitted = false; + _this._emitDisconnect = function (e) { + if (_this._disconnectEmitted) + return; + _this._disconnectEmitted = true; + _this.emit("disconnect", e); + }; + _this.device = device; + _this.interfaceNumber = interfaceNumber; + _this.deviceModel = identifyUSBProductId(device.productId); + return _this; } /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } + TransportWebUSB.request = function () { + return __awaiter(this, void 0, void 0, function () { + var device; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, requestLedgerDevice()]; + case 1: + device = _a.sent(); + return [2 /*return*/, TransportWebUSB.open(device)]; + } + }); }); }; /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); + * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); + TransportWebUSB.openConnected = function () { + return __awaiter(this, void 0, void 0, function () { + var devices; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getLedgerDevices()]; + case 1: + devices = _a.sent(); + if (devices.length === 0) + return [2 /*return*/, null]; + return [2 /*return*/, TransportWebUSB.open(devices[0])]; + } + }); }); }; /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); + * Create a Ledger transport with a USBDevice */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); + TransportWebUSB.open = function (device) { + return __awaiter(this, void 0, void 0, function () { + var iface, interfaceNumber, e_1, transport, onDisconnect; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, device.open()]; + case 1: + _a.sent(); + if (!(device.configuration === null)) return [3 /*break*/, 3]; + return [4 /*yield*/, device.selectConfiguration(configurationValue)]; + case 2: + _a.sent(); + _a.label = 3; + case 3: return [4 /*yield*/, gracefullyResetDevice(device)]; + case 4: + _a.sent(); + iface = device.configurations[0].interfaces.find(function (_a) { + var alternates = _a.alternates; + return alternates.some(function (a) { return a.interfaceClass === 255; }); + }); + if (!iface) { + throw new TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); + } + interfaceNumber = iface.interfaceNumber; + _a.label = 5; + case 5: + _a.trys.push([5, 7, , 9]); + return [4 /*yield*/, device.claimInterface(interfaceNumber)]; + case 6: + _a.sent(); + return [3 /*break*/, 9]; + case 7: + e_1 = _a.sent(); + return [4 /*yield*/, device.close()]; + case 8: + _a.sent(); + throw new TransportInterfaceNotAvailable(e_1.message); + case 9: + transport = new TransportWebUSB(device, interfaceNumber); + onDisconnect = function (e) { + if (device === e.device) { + // $FlowFixMe + navigator.usb.removeEventListener("disconnect", onDisconnect); + transport._emitDisconnect(new DisconnectedDevice()); + } + }; + // $FlowFixMe + navigator.usb.addEventListener("disconnect", onDisconnect); + return [2 /*return*/, transport]; + } + }); + }); }; /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + * Release the transport device */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { + TransportWebUSB.prototype.close = function () { return __awaiter(this, void 0, void 0, function () { - var _lazyImpl, impl; return __generator(this, function (_a) { switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; + case 0: return [4 /*yield*/, this.exchangeBusyPromise]; case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; + _a.sent(); + return [4 /*yield*/, this.device.releaseInterface(this.interfaceNumber)]; + case 2: + _a.sent(); + return [4 /*yield*/, gracefullyResetDevice(this.device)]; + case 3: + _a.sent(); + return [4 /*yield*/, this.device.close()]; + case 4: + _a.sent(); + return [2 /*return*/]; } }); }); }; - Btc.prototype.inferCorrectImpl = function () { + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + TransportWebUSB.prototype.exchange = function (apdu) { return __awaiter(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; + var b; + var _this = this; return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { + var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = this, channel = _a.channel, packetSize = _a.packetSize; + log$1("apdu", "=> " + apdu.toString("hex")); + framing = hidFraming(channel, packetSize); + blocks = framing.makeBlocks(apdu); + i = 0; + _b.label = 1; + case 1: + if (!(i < blocks.length)) return [3 /*break*/, 4]; + return [4 /*yield*/, this.device.transferOut(endpointNumber, blocks[i])]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: + if (!!(result = framing.getReducedResult(acc))) return [3 /*break*/, 6]; + return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; + case 5: + r = _b.sent(); + buffer = Buffer$i.from(r.data.buffer); + acc = framing.reduceResponse(acc, buffer); + return [3 /*break*/, 4]; + case 6: + log$1("apdu", "<= " + result.toString("hex")); + return [2 /*return*/, result]; + } + }); + }); })["catch"](function (e) { + if (e && e.message && e.message.includes("disconnected")) { + _this._emitDisconnect(e); + throw new DisconnectedDeviceDuringOperation(e.message); + } + throw e; + })]; case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } + b = _a.sent(); + return [2 /*return*/, b]; } }); }); }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); + TransportWebUSB.prototype.setScrambleKey = function () { }; + /** + * Check if WebUSB transport is supported. + */ + TransportWebUSB.isSupported = isSupported$1; + /** + * List the WebUSB devices that was previously authorized by the user. + */ + TransportWebUSB.list = getLedgerDevices; + /** + * Actively listen to WebUSB devices and emit ONE device + * that was either accepted before, if not it will trigger the native permission UI. + * + * Important: it must be called in the context of a UI click! + */ + TransportWebUSB.listen = function (observer) { + var unsubscribed = false; + getFirstLedgerDevice().then(function (device) { + if (!unsubscribed) { + var deviceModel = identifyUSBProductId(device.productId); + observer.next({ + type: "add", + descriptor: device, + deviceModel: deviceModel + }); + observer.complete(); + } + }, function (error) { + if (window.DOMException && + error instanceof window.DOMException && + error.code === 18) { + observer.error(new TransportWebUSBGestureRequired(error.message)); + } + else { + observer.error(new TransportOpenUserCancelled(error.message)); + } + }); + function unsubscribe() { + unsubscribed = true; + } + return { + unsubscribe: unsubscribe + }; }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; - } - return false; + return TransportWebUSB; + }(Transport$1)); + function gracefullyResetDevice(device) { + return __awaiter(this, void 0, void 0, function () { + var err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, device.reset()]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + err_1 = _a.sent(); + console.warn(err_1); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); } - var Btc$1 = /*#__PURE__*/Object.freeze({ + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ __proto__: null, - 'default': Btc + 'default': TransportWebUSB }); - var TransportWebUSB$2 = {}; + /** Namespace for the U2F api. + * @type {Object} + */ + var u2f = u2f || {}; - var Transport$1 = {}; + var googleU2fApi = u2f; // Adaptation for u2f-api package - var lib$2 = {}; + /** + * The U2F extension id + * @type {string} + * @const + */ + u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; - var helpers = {}; + /** + * Message types for messsages to/from the extension + * @const + * @enum {string} + */ + u2f.MessageTypes = { + 'U2F_REGISTER_REQUEST': 'u2f_register_request', + 'U2F_SIGN_REQUEST': 'u2f_sign_request', + 'U2F_REGISTER_RESPONSE': 'u2f_register_response', + 'U2F_SIGN_RESPONSE': 'u2f_sign_response' + }; - Object.defineProperty(helpers, "__esModule", { - value: true - }); + /** + * Response status codes + * @const + * @enum {number} + */ + u2f.ErrorCodes = { + 'OK': 0, + 'OTHER_ERROR': 1, + 'BAD_REQUEST': 2, + 'CONFIGURATION_UNSUPPORTED': 3, + 'DEVICE_INELIGIBLE': 4, + 'TIMEOUT': 5 + }; - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + /** + * A message type for registration requests + * @typedef {{ + * type: u2f.MessageTypes, + * signRequests: Array., + * registerRequests: ?Array., + * timeoutSeconds: ?number, + * requestId: ?number + * }} + */ + u2f.Request; - /* eslint-disable no-continue */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ + /** + * A message for registration responses + * @typedef {{ + * type: u2f.MessageTypes, + * responseData: (u2f.Error | u2f.RegisterResponse | u2f.SignResponse), + * requestId: ?number + * }} + */ + u2f.Response; - var errorClasses = {}; - var deserializers = {}; + /** + * An error object for responses + * @typedef {{ + * errorCode: u2f.ErrorCodes, + * errorMessage: ?string + * }} + */ + u2f.Error; - helpers.addCustomErrorDeserializer = function addCustomErrorDeserializer(name, deserializer) { - deserializers[name] = deserializer; - }; + /** + * Data object for a single sign request. + * @typedef {{ + * version: string, + * challenge: string, + * keyHandle: string, + * appId: string + * }} + */ + u2f.SignRequest; - var createCustomErrorClass = helpers.createCustomErrorClass = function createCustomErrorClass(name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - // $FlowFixMe - C.prototype = new Error(); + /** + * Data object for a sign response. + * @typedef {{ + * keyHandle: string, + * signatureData: string, + * clientData: string + * }} + */ + u2f.SignResponse; + + /** + * Data object for a registration request. + * @typedef {{ + * version: string, + * challenge: string, + * appId: string + * }} + */ + u2f.RegisterRequest; - errorClasses[name] = C; - // $FlowFixMe we can't easily type a subset of Error for now... - return C; + /** + * Data object for a registration response. + * @typedef {{ + * registrationData: string, + * clientData: string + * }} + */ + u2f.RegisterResponse; + + + // Low level MessagePort API support + + /** + * Call MessagePort disconnect + */ + u2f.disconnect = function() { + if (u2f.port_ && u2f.port_.port_) { + u2f.port_.port_.disconnect(); + u2f.port_ = null; + } }; - // inspired from https://github.com/programble/errio/blob/master/index.js - helpers.deserializeError = function deserializeError(object) { - if ((typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; + /** + * Sets up a MessagePort to the U2F extension using the + * available mechanisms. + * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback + */ + u2f.getMessagePort = function(callback) { + if (typeof chrome != 'undefined' && chrome.runtime) { + // The actual message here does not matter, but we need to get a reply + // for the callback to run. Thus, send an empty signature request + // in order to get a failure response. + var msg = { + type: u2f.MessageTypes.U2F_SIGN_REQUEST, + signRequests: [] + }; + chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { + if (!chrome.runtime.lastError) { + // We are on a whitelisted origin and can talk directly + // with the extension. + u2f.getChromeRuntimePort_(callback); + } else { + // chrome.runtime was available, but we couldn't message + // the extension directly, use iframe + u2f.getIframePort_(callback); } - } catch (e) { - // nothing - } + }); + } else { + // chrome.runtime was not available at all, which is normal + // when this origin doesn't have access to any extensions. + u2f.getIframePort_(callback); + } + }; - var error = void 0; - if (typeof object.name === "string") { - var _object = object, - name = _object.name; + /** + * Connects directly to the extension via chrome.runtime.connect + * @param {function(u2f.WrappedChromeRuntimePort_)} callback + * @private + */ + u2f.getChromeRuntimePort_ = function(callback) { + var port = chrome.runtime.connect(u2f.EXTENSION_ID, + {'includeTlsChannelId': true}); + setTimeout(function() { + callback(null, new u2f.WrappedChromeRuntimePort_(port)); + }, 0); + }; - var des = deserializers[name]; - if (des) { - error = des(object); - } else { - var _constructor = name === "Error" ? Error : errorClasses[name]; + /** + * A wrapper for chrome.runtime.Port that is compatible with MessagePort. + * @param {Port} port + * @constructor + * @private + */ + u2f.WrappedChromeRuntimePort_ = function(port) { + this.port_ = port; + }; - if (!_constructor) { - console.warn("deserializing an unknown class '" + name + "'"); - _constructor = createCustomErrorClass(name); - } + /** + * Posts a message on the underlying channel. + * @param {Object} message + */ + u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { + this.port_.postMessage(message); + }; - error = Object.create(_constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } catch (e) { - // sometimes setting a property can fail (e.g. .name) - } + /** + * Emulates the HTML 5 addEventListener interface. Works only for the + * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. + * @param {string} eventName + * @param {function({data: Object})} handler + */ + u2f.WrappedChromeRuntimePort_.prototype.addEventListener = + function(eventName, handler) { + var name = eventName.toLowerCase(); + if (name == 'message' || name == 'onmessage') { + this.port_.onMessage.addListener(function(message) { + // Emulate a minimal MessageEvent object + handler({'data': message}); + }); + } else { + console.error('WrappedChromeRuntimePort only supports onMessage'); + } + }; + + /** + * Sets up an embedded trampoline iframe, sourced from the extension. + * @param {function(MessagePort)} callback + * @private + */ + u2f.getIframePort_ = function(callback) { + // Create the iframe + var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; + var iframe = document.createElement('iframe'); + iframe.src = iframeOrigin + '/u2f-comms.html'; + iframe.setAttribute('style', 'display:none'); + document.body.appendChild(iframe); + + var hasCalledBack = false; + + var channel = new MessageChannel(); + var ready = function(message) { + if (message.data == 'ready') { + channel.port1.removeEventListener('message', ready); + if (!hasCalledBack) + { + hasCalledBack = true; + callback(null, channel.port1); } } else { - error = new Error(object.message); + console.error('First event on iframe port was not "ready"'); } + }; + channel.port1.addEventListener('message', ready); + channel.port1.start(); + + iframe.addEventListener('load', function() { + // Deliver the port to the iframe and initialize + iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); + }); - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); + // Give this 200ms to initialize, after that, we treat this method as failed + setTimeout(function() { + if (!hasCalledBack) + { + hasCalledBack = true; + callback(new Error("IFrame extension not supported")); } - return error; - } - return new Error(String(object)); + }, 200); }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - helpers.serializeError = function serializeError(value) { - if (!value) return value; - if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + // High-level JS API - try { - for (var _iterator = Object.keys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var key = _step.value; + /** + * Default extension response timeout in seconds. + * @const + */ + u2f.EXTENSION_TIMEOUT_SEC = 30; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || (typeof value === "undefined" ? "undefined" : _typeof(value)) !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } + /** + * A singleton instance for a MessagePort to the extension. + * @type {MessagePort|u2f.WrappedChromeRuntimePort_} + * @private + */ + u2f.port_ = null; + + /** + * Callbacks waiting for a port + * @type {Array.} + * @private + */ + u2f.waitingForPort_ = []; + + /** + * A counter for requestIds. + * @type {number} + * @private + */ + u2f.reqCounter_ = 0; + + /** + * A map from requestIds to client callbacks + * @type {Object.} + * @private + */ + u2f.callbackMap_ = {}; + + /** + * Creates or retrieves the MessagePort singleton to use. + * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback + * @private + */ + u2f.getPortSingleton_ = function(callback) { + if (u2f.port_) { + callback(null, u2f.port_); + } else { + if (u2f.waitingForPort_.length == 0) { + u2f.getMessagePort(function(err, port) { + if (!err) { + u2f.port_ = port; + u2f.port_.addEventListener('message', + /** @type {function(Event)} */ (u2f.responseHandler_)); + } + + // Careful, here be async callbacks. Maybe. + while (u2f.waitingForPort_.length) + u2f.waitingForPort_.shift()(err, port); + }); } + u2f.waitingForPort_.push(callback); } + }; - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; + /** + * Handles response messages from the extension. + * @param {MessageEvent.} message + * @private + */ + u2f.responseHandler_ = function(message) { + var response = message.data; + var reqId = response['requestId']; + if (!reqId || !u2f.callbackMap_[reqId]) { + console.error('Unknown or missing requestId in response.'); + return; } - return to; - } + var cb = u2f.callbackMap_[reqId]; + delete u2f.callbackMap_[reqId]; + cb(null, response['responseData']); + }; - Object.defineProperty(lib$2, "__esModule", { - value: true - }); - lib$2.StatusCodes = lib$2.DBNotReset = lib$2.DBWrongPassword = lib$2.NoDBPathGiven = lib$2.FirmwareOrAppUpdateRequired = lib$2.LedgerAPI5xx = lib$2.LedgerAPI4xx = lib$2.GenuineCheckFailed = lib$2.PairingFailed = lib$2.SyncError = lib$2.FeeTooHigh = lib$2.FeeRequired = lib$2.FeeNotLoaded = lib$2.CantScanQRCode = lib$2.ETHAddressNonEIP = lib$2.WrongAppForCurrency = lib$2.WrongDeviceForAccount = lib$2.WebsocketConnectionFailed = lib$2.WebsocketConnectionError = lib$2.DeviceShouldStayInApp = lib$2.TransportWebUSBGestureRequired = lib$2.TransportInterfaceNotAvailable = lib$2.TransportOpenUserCancelled = lib$2.UserRefusedOnDevice = lib$2.UserRefusedAllowManager = lib$2.UserRefusedFirmwareUpdate = lib$2.UserRefusedAddress = lib$2.UserRefusedDeviceNameChange = lib$2.UpdateYourApp = lib$2.UnavailableTezosOriginatedAccountSend = lib$2.UnavailableTezosOriginatedAccountReceive = lib$2.RecipientRequired = lib$2.MCUNotGenuineToDashboard = lib$2.UnexpectedBootloader = lib$2.TimeoutTagged = lib$2.RecommendUndelegation = lib$2.RecommendSubAccountsToEmpty = lib$2.PasswordIncorrectError = lib$2.PasswordsDontMatchError = lib$2.GasLessThanEstimate = lib$2.NotSupportedLegacyAddress = lib$2.NotEnoughGas = lib$2.NoAccessToCamera = lib$2.NotEnoughBalanceBecauseDestinationNotCreated = lib$2.NotEnoughSpendableBalance = lib$2.NotEnoughBalanceInParentAccount = lib$2.NotEnoughBalanceToDelegate = lib$2.NotEnoughBalance = lib$2.NoAddressesFound = lib$2.NetworkDown = lib$2.ManagerUninstallBTCDep = lib$2.ManagerNotEnoughSpaceError = lib$2.ManagerFirmwareNotEnoughSpaceError = lib$2.ManagerDeviceLockedError = lib$2.ManagerAppDepUninstallRequired = lib$2.ManagerAppDepInstallRequired = lib$2.ManagerAppRelyOnBTCError = lib$2.ManagerAppAlreadyInstalledError = lib$2.LedgerAPINotAvailable = lib$2.LedgerAPIErrorWithMessage = lib$2.LedgerAPIError = lib$2.UnknownMCU = lib$2.LatestMCUInstalledError = lib$2.InvalidAddressBecauseDestinationIsAlsoSource = lib$2.InvalidAddress = lib$2.InvalidXRPTag = lib$2.HardResetFail = lib$2.FeeEstimationFailed = lib$2.EthAppPleaseEnableContractData = lib$2.EnpointConfigError = lib$2.DisconnectedDeviceDuringOperation = lib$2.DisconnectedDevice = lib$2.DeviceSocketNoBulkStatus = lib$2.DeviceSocketFail = lib$2.DeviceNameInvalid = lib$2.DeviceHalted = lib$2.DeviceInOSUExpected = lib$2.DeviceOnDashboardUnexpected = lib$2.DeviceOnDashboardExpected = lib$2.DeviceNotGenuineError = lib$2.DeviceGenuineSocketEarlyClose = lib$2.DeviceAppVerifyNotSupported = lib$2.CurrencyNotSupported = lib$2.CashAddrNotSupported = lib$2.CantOpenDevice = lib$2.BtcUnmatchedApp = lib$2.BluetoothRequired = lib$2.AmountRequired = lib$2.AccountNotSupported = lib$2.AccountNameRequiredError = lib$2.addCustomErrorDeserializer = lib$2.createCustomErrorClass = lib$2.deserializeError = lib$2.serializeError = undefined; - lib$2.TransportError = TransportError; - lib$2.getAltStatusMessage = getAltStatusMessage; - lib$2.TransportStatusError = TransportStatusError; - - var _helpers = helpers; - - lib$2.serializeError = _helpers.serializeError; - lib$2.deserializeError = _helpers.deserializeError; - lib$2.createCustomErrorClass = _helpers.createCustomErrorClass; - lib$2.addCustomErrorDeserializer = _helpers.addCustomErrorDeserializer; - lib$2.AccountNameRequiredError = (0, _helpers.createCustomErrorClass)("AccountNameRequired"); - lib$2.AccountNotSupported = (0, _helpers.createCustomErrorClass)("AccountNotSupported"); - lib$2.AmountRequired = (0, _helpers.createCustomErrorClass)("AmountRequired"); - lib$2.BluetoothRequired = (0, _helpers.createCustomErrorClass)("BluetoothRequired"); - lib$2.BtcUnmatchedApp = (0, _helpers.createCustomErrorClass)("BtcUnmatchedApp"); - lib$2.CantOpenDevice = (0, _helpers.createCustomErrorClass)("CantOpenDevice"); - lib$2.CashAddrNotSupported = (0, _helpers.createCustomErrorClass)("CashAddrNotSupported"); - lib$2.CurrencyNotSupported = (0, _helpers.createCustomErrorClass)("CurrencyNotSupported"); - lib$2.DeviceAppVerifyNotSupported = (0, _helpers.createCustomErrorClass)("DeviceAppVerifyNotSupported"); - lib$2.DeviceGenuineSocketEarlyClose = (0, _helpers.createCustomErrorClass)("DeviceGenuineSocketEarlyClose"); - lib$2.DeviceNotGenuineError = (0, _helpers.createCustomErrorClass)("DeviceNotGenuine"); - lib$2.DeviceOnDashboardExpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardExpected"); - lib$2.DeviceOnDashboardUnexpected = (0, _helpers.createCustomErrorClass)("DeviceOnDashboardUnexpected"); - lib$2.DeviceInOSUExpected = (0, _helpers.createCustomErrorClass)("DeviceInOSUExpected"); - lib$2.DeviceHalted = (0, _helpers.createCustomErrorClass)("DeviceHalted"); - lib$2.DeviceNameInvalid = (0, _helpers.createCustomErrorClass)("DeviceNameInvalid"); - lib$2.DeviceSocketFail = (0, _helpers.createCustomErrorClass)("DeviceSocketFail"); - lib$2.DeviceSocketNoBulkStatus = (0, _helpers.createCustomErrorClass)("DeviceSocketNoBulkStatus"); - lib$2.DisconnectedDevice = (0, _helpers.createCustomErrorClass)("DisconnectedDevice"); - lib$2.DisconnectedDeviceDuringOperation = (0, _helpers.createCustomErrorClass)("DisconnectedDeviceDuringOperation"); - lib$2.EnpointConfigError = (0, _helpers.createCustomErrorClass)("EnpointConfig"); - lib$2.EthAppPleaseEnableContractData = (0, _helpers.createCustomErrorClass)("EthAppPleaseEnableContractData"); - lib$2.FeeEstimationFailed = (0, _helpers.createCustomErrorClass)("FeeEstimationFailed"); - lib$2.HardResetFail = (0, _helpers.createCustomErrorClass)("HardResetFail"); - lib$2.InvalidXRPTag = (0, _helpers.createCustomErrorClass)("InvalidXRPTag"); - lib$2.InvalidAddress = (0, _helpers.createCustomErrorClass)("InvalidAddress"); - lib$2.InvalidAddressBecauseDestinationIsAlsoSource = (0, _helpers.createCustomErrorClass)("InvalidAddressBecauseDestinationIsAlsoSource"); - lib$2.LatestMCUInstalledError = (0, _helpers.createCustomErrorClass)("LatestMCUInstalledError"); - lib$2.UnknownMCU = (0, _helpers.createCustomErrorClass)("UnknownMCU"); - lib$2.LedgerAPIError = (0, _helpers.createCustomErrorClass)("LedgerAPIError"); - lib$2.LedgerAPIErrorWithMessage = (0, _helpers.createCustomErrorClass)("LedgerAPIErrorWithMessage"); - lib$2.LedgerAPINotAvailable = (0, _helpers.createCustomErrorClass)("LedgerAPINotAvailable"); - lib$2.ManagerAppAlreadyInstalledError = (0, _helpers.createCustomErrorClass)("ManagerAppAlreadyInstalled"); - lib$2.ManagerAppRelyOnBTCError = (0, _helpers.createCustomErrorClass)("ManagerAppRelyOnBTC"); - lib$2.ManagerAppDepInstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepInstallRequired"); - lib$2.ManagerAppDepUninstallRequired = (0, _helpers.createCustomErrorClass)("ManagerAppDepUninstallRequired"); - lib$2.ManagerDeviceLockedError = (0, _helpers.createCustomErrorClass)("ManagerDeviceLocked"); - lib$2.ManagerFirmwareNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerFirmwareNotEnoughSpace"); - lib$2.ManagerNotEnoughSpaceError = (0, _helpers.createCustomErrorClass)("ManagerNotEnoughSpace"); - lib$2.ManagerUninstallBTCDep = (0, _helpers.createCustomErrorClass)("ManagerUninstallBTCDep"); - lib$2.NetworkDown = (0, _helpers.createCustomErrorClass)("NetworkDown"); - lib$2.NoAddressesFound = (0, _helpers.createCustomErrorClass)("NoAddressesFound"); - lib$2.NotEnoughBalance = (0, _helpers.createCustomErrorClass)("NotEnoughBalance"); - lib$2.NotEnoughBalanceToDelegate = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceToDelegate"); - lib$2.NotEnoughBalanceInParentAccount = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceInParentAccount"); - lib$2.NotEnoughSpendableBalance = (0, _helpers.createCustomErrorClass)("NotEnoughSpendableBalance"); - lib$2.NotEnoughBalanceBecauseDestinationNotCreated = (0, _helpers.createCustomErrorClass)("NotEnoughBalanceBecauseDestinationNotCreated"); - lib$2.NoAccessToCamera = (0, _helpers.createCustomErrorClass)("NoAccessToCamera"); - lib$2.NotEnoughGas = (0, _helpers.createCustomErrorClass)("NotEnoughGas"); - lib$2.NotSupportedLegacyAddress = (0, _helpers.createCustomErrorClass)("NotSupportedLegacyAddress"); - lib$2.GasLessThanEstimate = (0, _helpers.createCustomErrorClass)("GasLessThanEstimate"); - lib$2.PasswordsDontMatchError = (0, _helpers.createCustomErrorClass)("PasswordsDontMatch"); - lib$2.PasswordIncorrectError = (0, _helpers.createCustomErrorClass)("PasswordIncorrect"); - lib$2.RecommendSubAccountsToEmpty = (0, _helpers.createCustomErrorClass)("RecommendSubAccountsToEmpty"); - lib$2.RecommendUndelegation = (0, _helpers.createCustomErrorClass)("RecommendUndelegation"); - lib$2.TimeoutTagged = (0, _helpers.createCustomErrorClass)("TimeoutTagged"); - lib$2.UnexpectedBootloader = (0, _helpers.createCustomErrorClass)("UnexpectedBootloader"); - lib$2.MCUNotGenuineToDashboard = (0, _helpers.createCustomErrorClass)("MCUNotGenuineToDashboard"); - lib$2.RecipientRequired = (0, _helpers.createCustomErrorClass)("RecipientRequired"); - lib$2.UnavailableTezosOriginatedAccountReceive = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountReceive"); - lib$2.UnavailableTezosOriginatedAccountSend = (0, _helpers.createCustomErrorClass)("UnavailableTezosOriginatedAccountSend"); - lib$2.UpdateYourApp = (0, _helpers.createCustomErrorClass)("UpdateYourApp"); - lib$2.UserRefusedDeviceNameChange = (0, _helpers.createCustomErrorClass)("UserRefusedDeviceNameChange"); - lib$2.UserRefusedAddress = (0, _helpers.createCustomErrorClass)("UserRefusedAddress"); - lib$2.UserRefusedFirmwareUpdate = (0, _helpers.createCustomErrorClass)("UserRefusedFirmwareUpdate"); - lib$2.UserRefusedAllowManager = (0, _helpers.createCustomErrorClass)("UserRefusedAllowManager"); - lib$2.UserRefusedOnDevice = (0, _helpers.createCustomErrorClass)("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - lib$2.TransportOpenUserCancelled = (0, _helpers.createCustomErrorClass)("TransportOpenUserCancelled"); - lib$2.TransportInterfaceNotAvailable = (0, _helpers.createCustomErrorClass)("TransportInterfaceNotAvailable"); - lib$2.TransportWebUSBGestureRequired = (0, _helpers.createCustomErrorClass)("TransportWebUSBGestureRequired"); - lib$2.DeviceShouldStayInApp = (0, _helpers.createCustomErrorClass)("DeviceShouldStayInApp"); - lib$2.WebsocketConnectionError = (0, _helpers.createCustomErrorClass)("WebsocketConnectionError"); - lib$2.WebsocketConnectionFailed = (0, _helpers.createCustomErrorClass)("WebsocketConnectionFailed"); - lib$2.WrongDeviceForAccount = (0, _helpers.createCustomErrorClass)("WrongDeviceForAccount"); - lib$2.WrongAppForCurrency = (0, _helpers.createCustomErrorClass)("WrongAppForCurrency"); - lib$2.ETHAddressNonEIP = (0, _helpers.createCustomErrorClass)("ETHAddressNonEIP"); - lib$2.CantScanQRCode = (0, _helpers.createCustomErrorClass)("CantScanQRCode"); - lib$2.FeeNotLoaded = (0, _helpers.createCustomErrorClass)("FeeNotLoaded"); - lib$2.FeeRequired = (0, _helpers.createCustomErrorClass)("FeeRequired"); - lib$2.FeeTooHigh = (0, _helpers.createCustomErrorClass)("FeeTooHigh"); - lib$2.SyncError = (0, _helpers.createCustomErrorClass)("SyncError"); - lib$2.PairingFailed = (0, _helpers.createCustomErrorClass)("PairingFailed"); - lib$2.GenuineCheckFailed = (0, _helpers.createCustomErrorClass)("GenuineCheckFailed"); - lib$2.LedgerAPI4xx = (0, _helpers.createCustomErrorClass)("LedgerAPI4xx"); - lib$2.LedgerAPI5xx = (0, _helpers.createCustomErrorClass)("LedgerAPI5xx"); - lib$2.FirmwareOrAppUpdateRequired = (0, _helpers.createCustomErrorClass)("FirmwareOrAppUpdateRequired"); + /** + * Calls the callback with true or false as first and only argument + * @param {Function} callback + */ + u2f.isSupported = function(callback) { + u2f.getPortSingleton_(function(err, port) { + callback(!err); + }); + }; - // db stuff, no need to translate - lib$2.NoDBPathGiven = (0, _helpers.createCustomErrorClass)("NoDBPathGiven"); - lib$2.DBWrongPassword = (0, _helpers.createCustomErrorClass)("DBWrongPassword"); - lib$2.DBNotReset = (0, _helpers.createCustomErrorClass)("DBNotReset"); + /** + * Dispatches an array of sign requests to available U2F tokens. + * @param {Array.} signRequests + * @param {function((u2f.Error|u2f.SignResponse))} callback + * @param {number=} opt_timeoutSeconds + */ + u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { + u2f.getPortSingleton_(function(err, port) { + if (err) + return callback(err); + + var reqId = ++u2f.reqCounter_; + u2f.callbackMap_[reqId] = callback; + var req = { + type: u2f.MessageTypes.U2F_SIGN_REQUEST, + signRequests: signRequests, + timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? + opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), + requestId: reqId + }; + port.postMessage(req); + }); + }; /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + * Dispatches register requests to available U2F tokens. An array of sign + * requests identifies already registered tokens. + * @param {Array.} registerRequests + * @param {Array.} signRequests + * @param {function((u2f.Error|u2f.RegisterResponse))} callback + * @param {number=} opt_timeoutSeconds */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - //$FlowFixMe - TransportError.prototype = new Error(); + u2f.register = function(registerRequests, signRequests, + callback, opt_timeoutSeconds) { + u2f.getPortSingleton_(function(err, port) { + if (err) + return callback(err); + + var reqId = ++u2f.reqCounter_; + u2f.callbackMap_[reqId] = callback; + var req = { + type: u2f.MessageTypes.U2F_REGISTER_REQUEST, + signRequests: signRequests, + registerRequests: registerRequests, + timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? + opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), + requestId: reqId + }; + port.postMessage(req); + }); + }; - (0, _helpers.addCustomErrorDeserializer)("TransportError", function (e) { - return new TransportError(e.message, e.id); - }); + var u2fApi$1 = API; - var StatusCodes = lib$2.StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } + var chromeApi = googleU2fApi; + + // Feature detection (yes really) + var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; + var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) + && !navigator.userAgent.match( /Chrome\// ); + var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); + + var _backend = null; + function getBackend( Promise ) + { + if ( !_backend ) + _backend = new Promise( function( resolve, reject ) + { + function notSupported( ) + { + // Note; {native: true} means *not* using Google's hack + resolve( { u2f: null, native: true } ); + } + + if ( !isBrowser ) + return notSupported( ); + + if ( isSafari ) + // Safari doesn't support U2F, and the Safari-FIDO-U2F + // extension lacks full support (Multi-facet apps), so we + // block it until proper support. + return notSupported( ); + + var hasNativeSupport = + ( typeof window.u2f !== 'undefined' ) && + ( typeof window.u2f.sign === 'function' ); + + if ( hasNativeSupport ) + resolve( { u2f: window.u2f, native: true } ); + + if ( isEDGE ) + // We don't want to check for Google's extension hack on EDGE + // as it'll cause trouble (popups, etc) + return notSupported( ); + + if ( location.protocol === 'http:' ) + // U2F isn't supported over http, only https + return notSupported( ); + + if ( typeof MessageChannel === 'undefined' ) + // Unsupported browser, the chrome hack would throw + return notSupported( ); + + // Test for google extension support + chromeApi.isSupported( function( ok ) + { + if ( ok ) + resolve( { u2f: chromeApi, native: false } ); + else + notSupported( ); + } ); + } ); + + return _backend; } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { - return StatusCodes[k] === statusCode; - }) || "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - //$FlowFixMe - TransportStatusError.prototype = new Error(); - - (0, _helpers.addCustomErrorDeserializer)("TransportStatusError", function (e) { - return new TransportStatusError(e.statusCode); - }); + function API( Promise ) + { + return { + isSupported : isSupported.bind( Promise ), + ensureSupport : ensureSupport.bind( Promise ), + register : register.bind( Promise ), + sign : sign.bind( Promise ), + ErrorCodes : API.ErrorCodes, + ErrorNames : API.ErrorNames + }; + } + + API.ErrorCodes = { + CANCELLED: -1, + OK: 0, + OTHER_ERROR: 1, + BAD_REQUEST: 2, + CONFIGURATION_UNSUPPORTED: 3, + DEVICE_INELIGIBLE: 4, + TIMEOUT: 5 + }; + API.ErrorNames = { + "-1": "CANCELLED", + "0": "OK", + "1": "OTHER_ERROR", + "2": "BAD_REQUEST", + "3": "CONFIGURATION_UNSUPPORTED", + "4": "DEVICE_INELIGIBLE", + "5": "TIMEOUT" + }; + + function makeError( msg, err ) + { + var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR + var type = API.ErrorNames[ '' + code ]; + var error = new Error( msg ); + error.metaData = { + type: type, + code: code + }; + return error; + } - Object.defineProperty(Transport$1, "__esModule", { - value: true - }); - Transport$1.getAltStatusMessage = Transport$1.StatusCodes = Transport$1.TransportStatusError = Transport$1.TransportError = undefined; + function deferPromise( Promise, promise ) + { + var ret = { }; + ret.promise = new Promise( function( resolve, reject ) { + ret.resolve = resolve; + ret.reject = reject; + promise.then( resolve, reject ); + } ); + /** + * Reject request promise and disconnect port if 'disconnect' flag is true + * @param {string} msg + * @param {boolean} disconnect + */ + ret.promise.cancel = function( msg, disconnect ) + { + getBackend( Promise ) + .then( function( backend ) + { + if ( disconnect && !backend.native ) + backend.u2f.disconnect( ); + + ret.reject( makeError( msg, { errorCode: -1 } ) ); + } ); + }; + return ret; + } + + function isSupported( ) + { + var Promise = this; + + return getBackend( Promise ) + .then( function( backend ) + { + return !!backend.u2f; + } ); + } + + function _ensureSupport( backend ) + { + if ( !backend.u2f ) + { + if ( location.protocol === 'http:' ) + throw new Error( "U2F isn't supported over http, only https" ); + throw new Error( "U2F not supported" ); + } + } - var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + function ensureSupport( ) + { + var Promise = this; - var _events2 = require$$0__default$3["default"]; + return getBackend( Promise ) + .then( _ensureSupport ); + } - var _events3 = _interopRequireDefault$1(_events2); + function register( registerRequests, signRequests /* = null */, timeout ) + { + var Promise = this; - var _errors$2 = lib$2; + if ( !Array.isArray( registerRequests ) ) + registerRequests = [ registerRequests ]; - function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) + { + timeout = signRequests; + signRequests = null; + } - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + if ( !signRequests ) + signRequests = [ ]; + + return deferPromise( Promise, getBackend( Promise ) + .then( function( backend ) + { + _ensureSupport( backend ); + + var native = backend.native; + var u2f = backend.u2f; + + return new Promise( function( resolve, reject ) + { + function cbNative( response ) + { + if ( response.errorCode ) + reject( makeError( "Registration failed", response ) ); + else + { + delete response.errorCode; + resolve( response ); + } + } - function _asyncToGenerator$2(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + function cbChrome( err, response ) + { + if ( err ) + reject( err ); + else if ( response.errorCode ) + reject( makeError( "Registration failed", response ) ); + else + resolve( response ); + } - function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if ( native ) + { + var appId = registerRequests[ 0 ].appId; - Transport$1.TransportError = _errors$2.TransportError; - Transport$1.TransportStatusError = _errors$2.TransportStatusError; - Transport$1.StatusCodes = _errors$2.StatusCodes; - Transport$1.getAltStatusMessage = _errors$2.getAltStatusMessage; + u2f.register( + appId, registerRequests, signRequests, cbNative, timeout ); + } + else + { + u2f.register( + registerRequests, signRequests, cbChrome, timeout ); + } + } ); + } ) ).promise; + } - /** - */ + function sign( signRequests, timeout ) + { + var Promise = this; + + if ( !Array.isArray( signRequests ) ) + signRequests = [ signRequests ]; + + return deferPromise( Promise, getBackend( Promise ) + .then( function( backend ) + { + _ensureSupport( backend ); + + var native = backend.native; + var u2f = backend.u2f; + + return new Promise( function( resolve, reject ) + { + function cbNative( response ) + { + if ( response.errorCode ) + reject( makeError( "Sign failed", response ) ); + else + { + delete response.errorCode; + resolve( response ); + } + } + function cbChrome( err, response ) + { + if ( err ) + reject( err ); + else if ( response.errorCode ) + reject( makeError( "Sign failed", response ) ); + else + resolve( response ); + } - /** - */ + if ( native ) + { + var appId = signRequests[ 0 ].appId; + var challenge = signRequests[ 0 ].challenge; + u2f.sign( appId, challenge, signRequests, cbNative, timeout ); + } + else + { + u2f.sign( signRequests, cbChrome, timeout ); + } + } ); + } ) ).promise; + } - /** - * type: add or remove event - * descriptor: a parameter that can be passed to open(descriptor) - * deviceModel: device info on the model (is it a nano s, nano x, ...) - * device: transport specific device info - */ + function makeDefault( func ) + { + API[ func ] = function( ) + { + if ( !commonjsGlobal.Promise ) + // This is very unlikely to ever happen, since browsers + // supporting U2F will most likely support Promises. + throw new Error( "The platform doesn't natively support promises" ); + + var args = [ ].slice.call( arguments ); + return API( commonjsGlobal.Promise )[ func ].apply( null, args ); + }; + } + + // Provide default functions using the built-in Promise if available. + makeDefault( 'isSupported' ); + makeDefault( 'ensureSupport' ); + makeDefault( 'register' ); + makeDefault( 'sign' ); + + var u2fApi = u2fApi$1; + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; + }; + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; + }; + + createCustomErrorClass("AccountNameRequired"); + createCustomErrorClass("AccountNotSupported"); + createCustomErrorClass("AmountRequired"); + createCustomErrorClass("BluetoothRequired"); + createCustomErrorClass("BtcUnmatchedApp"); + createCustomErrorClass("CantOpenDevice"); + createCustomErrorClass("CashAddrNotSupported"); + createCustomErrorClass("CurrencyNotSupported"); + createCustomErrorClass("DeviceAppVerifyNotSupported"); + createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + createCustomErrorClass("DeviceNotGenuine"); + createCustomErrorClass("DeviceOnDashboardExpected"); + createCustomErrorClass("DeviceOnDashboardUnexpected"); + createCustomErrorClass("DeviceInOSUExpected"); + createCustomErrorClass("DeviceHalted"); + createCustomErrorClass("DeviceNameInvalid"); + createCustomErrorClass("DeviceSocketFail"); + createCustomErrorClass("DeviceSocketNoBulkStatus"); + createCustomErrorClass("DisconnectedDevice"); + createCustomErrorClass("DisconnectedDeviceDuringOperation"); + createCustomErrorClass("EnpointConfig"); + createCustomErrorClass("EthAppPleaseEnableContractData"); + createCustomErrorClass("FeeEstimationFailed"); + createCustomErrorClass("FirmwareNotRecognized"); + createCustomErrorClass("HardResetFail"); + createCustomErrorClass("InvalidXRPTag"); + createCustomErrorClass("InvalidAddress"); + createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + createCustomErrorClass("LatestMCUInstalledError"); + createCustomErrorClass("UnknownMCU"); + createCustomErrorClass("LedgerAPIError"); + createCustomErrorClass("LedgerAPIErrorWithMessage"); + createCustomErrorClass("LedgerAPINotAvailable"); + createCustomErrorClass("ManagerAppAlreadyInstalled"); + createCustomErrorClass("ManagerAppRelyOnBTC"); + createCustomErrorClass("ManagerAppDepInstallRequired"); + createCustomErrorClass("ManagerAppDepUninstallRequired"); + createCustomErrorClass("ManagerDeviceLocked"); + createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + createCustomErrorClass("ManagerNotEnoughSpace"); + createCustomErrorClass("ManagerUninstallBTCDep"); + createCustomErrorClass("NetworkDown"); + createCustomErrorClass("NoAddressesFound"); + createCustomErrorClass("NotEnoughBalance"); + createCustomErrorClass("NotEnoughBalanceToDelegate"); + createCustomErrorClass("NotEnoughBalanceInParentAccount"); + createCustomErrorClass("NotEnoughSpendableBalance"); + createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + createCustomErrorClass("NoAccessToCamera"); + createCustomErrorClass("NotEnoughGas"); + createCustomErrorClass("NotSupportedLegacyAddress"); + createCustomErrorClass("GasLessThanEstimate"); + createCustomErrorClass("PasswordsDontMatch"); + createCustomErrorClass("PasswordIncorrect"); + createCustomErrorClass("RecommendSubAccountsToEmpty"); + createCustomErrorClass("RecommendUndelegation"); + createCustomErrorClass("TimeoutTagged"); + createCustomErrorClass("UnexpectedBootloader"); + createCustomErrorClass("MCUNotGenuineToDashboard"); + createCustomErrorClass("RecipientRequired"); + createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + createCustomErrorClass("UpdateFetchFileFail"); + createCustomErrorClass("UpdateIncorrectHash"); + createCustomErrorClass("UpdateIncorrectSig"); + createCustomErrorClass("UpdateYourApp"); + createCustomErrorClass("UserRefusedDeviceNameChange"); + createCustomErrorClass("UserRefusedAddress"); + createCustomErrorClass("UserRefusedFirmwareUpdate"); + createCustomErrorClass("UserRefusedAllowManager"); + createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + createCustomErrorClass("TransportOpenUserCancelled"); + createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + createCustomErrorClass("TransportWebUSBGestureRequired"); + createCustomErrorClass("DeviceShouldStayInApp"); + createCustomErrorClass("WebsocketConnectionError"); + createCustomErrorClass("WebsocketConnectionFailed"); + createCustomErrorClass("WrongDeviceForAccount"); + createCustomErrorClass("WrongAppForCurrency"); + createCustomErrorClass("ETHAddressNonEIP"); + createCustomErrorClass("CantScanQRCode"); + createCustomErrorClass("FeeNotLoaded"); + createCustomErrorClass("FeeRequired"); + createCustomErrorClass("FeeTooHigh"); + createCustomErrorClass("SyncError"); + createCustomErrorClass("PairingFailed"); + createCustomErrorClass("GenuineCheckFailed"); + createCustomErrorClass("LedgerAPI4xx"); + createCustomErrorClass("LedgerAPI5xx"); + createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + createCustomErrorClass("NoDBPathGiven"); + createCustomErrorClass("DBWrongPassword"); + createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa, + }; + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); /** */ @@ -32608,161 +37926,64 @@ * A **Descriptor** is a parametric type that is up to be determined for the implementation. * it can be for instance an ID, an file path, a URL,... */ - var Transport = function () { - function Transport() { - var _this = this; - - _classCallCheck$1(this, Transport); - + class Transport { + constructor() { this.exchangeTimeout = 30000; - this._events = new _events3.default(); - - this.send = function () { - var _ref = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee(cla, ins, p1, p2) { - var data = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Buffer$g.alloc(0); - var statusList = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [_errors$2.StatusCodes.OK]; - var response, sw; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(data.length >= 256)) { - _context.next = 2; - break; - } - - throw new _errors$2.TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - - case 2: - _context.next = 4; - return _this.exchange(Buffer$g.concat([Buffer$g.from([cla, ins, p1, p2]), Buffer$g.from([data.length]), data])); + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter__default["default"](); - case 4: - response = _context.sent; - sw = response.readUInt16BE(response.length - 2); - - if (statusList.some(function (s) { - return s === sw; - })) { - _context.next = 8; - break; - } - - throw new _errors$2.TransportStatusError(sw); - - case 8: - return _context.abrupt("return", response); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee, _this); - })); + this.send = async (cla, ins, p1, p2, data = Buffer$i.alloc(0), statusList = [StatusCodes.OK]) => { + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - }(); - - this.exchangeAtomicImpl = function () { - var _ref2 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(f) { - var resolveBusy, busyPromise, res; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!_this.exchangeBusyPromise) { - _context2.next = 2; - break; - } + const response = await this.exchange(Buffer$i.concat([Buffer$i.from([cla, ins, p1, p2]), Buffer$i.from([data.length]), data])); + const sw = response.readUInt16BE(response.length - 2); - throw new _errors$2.TransportError("Transport race condition", "RaceCondition"); + if (!statusList.some(s => s === sw)) { + throw new TransportStatusError(sw); + } - case 2: - resolveBusy = void 0; - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); + return response; + }; - _this.exchangeBusyPromise = busyPromise; - _context2.prev = 5; - _context2.next = 8; - return f(); + this.exchangeBusyPromise = void 0; - case 8: - res = _context2.sent; - return _context2.abrupt("return", res); + this.exchangeAtomicImpl = async f => { + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } - case 10: - _context2.prev = 10; + let resolveBusy; + const busyPromise = new Promise(r => { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + let unresponsiveReached = false; + const timeout = setTimeout(() => { + unresponsiveReached = true; + this.emit("unresponsive"); + }, this.unresponsiveTimeout); - if (resolveBusy) resolveBusy(); - _this.exchangeBusyPromise = null; - return _context2.finish(10); + try { + const res = await f(); - case 14: - case "end": - return _context2.stop(); - } - } - }, _callee2, _this, [[5,, 10, 14]]); - })); + if (unresponsiveReached) { + this.emit("responsive"); + } - return function (_x7) { - return _ref2.apply(this, arguments); - }; - }(); + return res; + } finally { + clearTimeout(timeout); + if (resolveBusy) resolveBusy(); + this.exchangeBusyPromise = null; + } + }; this._appAPIlock = null; } - /** - * Statically check if a transport is supported on the user's platform/browser. - */ - - - /** - * List once all available descriptors. For a better granularity, checkout `listen()`. - * @return a promise of descriptors - * @example - * TransportFoo.list().then(descriptors => ...) - */ - - - /** - * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) - * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. - * each listen() call will first emit all potential device already connected and then will emit events can come over times, - * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. - * @param observer is an object with a next, error and complete function (compatible with observer pattern) - * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. - * @example - const sub = TransportFoo.listen({ - next: e => { - if (e.type==="add") { - sub.unsubscribe(); - const transport = await TransportFoo.open(e.descriptor); - ... - } - }, - error: error => {}, - complete: () => {} - }) - */ - - - /** - * attempt to create a Transport instance with potentially a descriptor. - * @param descriptor: the descriptor to open the transport with. - * @param timeout: an optional timeout - * @return a Promise of Transport instance - * @example - TransportFoo.open(descriptor).then(transport => ...) - */ - - /** * low level api to communicate with the device * This method is for implementations to implement but should not be directly called. @@ -32770,8 +37991,9 @@ * @param apdu the data to send * @return a Promise of response data */ - - + exchange(_apdu) { + throw new Error("exchange not implemented"); + } /** * set the "scramble key" for the next exchanges with the device. * Each App can have a different scramble key and they internally will set it at instanciation. @@ -32779,485 +38001,175 @@ */ + setScrambleKey(_key) {} /** * close the exchange with the device. * @return a Promise that ends when the transport is closed. */ - _createClass$1(Transport, [{ - key: "on", - + close() { + return Promise.resolve(); + } - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - value: function on(eventName, cb) { - this._events.on(eventName, cb); - } + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + on(eventName, cb) { + this._events.on(eventName, cb); + } + /** + * Stop listening to an event on an instance of transport. + */ - /** - * Stop listening to an event on an instance of transport. - */ - }, { - key: "off", - value: function off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - }, { - key: "emit", - value: function emit(event) { - var _events; + off(eventName, cb) { + this._events.removeListener(eventName, cb); + } - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } + emit(event, ...args) { + this._events.emit(event, ...args); + } + /** + * Enable or not logs of the binary exchange + */ - (_events = this._events).emit.apply(_events, [event].concat(_toConsumableArray(args))); - } - /** - * Enable or not logs of the binary exchange - */ + setDebugMode() { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + } + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ - }, { - key: "setDebugMode", - value: function setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ + setExchangeTimeout(exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + } + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ - }, { - key: "setExchangeTimeout", - value: function setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ + setExchangeUnresponsiveTimeout(unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + } + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ - }, { - key: "decorateAppAPIMethods", - value: function decorateAppAPIMethods(self, methods, scrambleKey) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - try { - for (var _iterator = methods[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var methodName = _step.value; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + static create(openTimeout = 3000, listenTimeout) { + return new Promise((resolve, reject) => { + let found = false; + const sub = this.listen({ + next: e => { + found = true; + if (sub) sub.unsubscribe(); + if (listenTimeoutId) clearTimeout(listenTimeoutId); + this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: e => { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + reject(e); + }, + complete: () => { + if (listenTimeoutId) clearTimeout(listenTimeoutId); - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; + if (!found) { + reject(new TransportError(this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); } } - } - } - }, { - key: "decorateAppAPIMethod", - value: function decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - var _this2 = this; - - return function () { - var _ref3 = _asyncToGenerator$2( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var _appAPIlock; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _appAPIlock = _this2._appAPIlock; - - if (!_appAPIlock) { - _context3.next = 3; - break; - } - - return _context3.abrupt("return", Promise.reject(new _errors$2.TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))); - - case 3: - _context3.prev = 3; - - _this2._appAPIlock = methodName; - _this2.setScrambleKey(scrambleKey); - _context3.next = 8; - return f.apply(ctx, args); - - case 8: - return _context3.abrupt("return", _context3.sent); - - case 9: - _context3.prev = 9; - - _this2._appAPIlock = null; - return _context3.finish(9); - - case 12: - case "end": - return _context3.stop(); - } - } - }, _callee3, _this2, [[3,, 9, 12]]); - })); - - return function () { - return _ref3.apply(this, arguments); - }; - }(); - } - }], [{ - key: "create", - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - value: function create() { - var _this3 = this; - - var openTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3000; - var listenTimeout = arguments[1]; - - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this3.listen({ - next: function next(e) { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - _this3.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function error(e) { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function complete() { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - if (!found) { - reject(new _errors$2.TransportError(_this3.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout ? setTimeout(function () { - sub.unsubscribe(); - reject(new _errors$2.TransportError(_this3.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; }); - } - - // $FlowFixMe - - }]); - - return Transport; - }(); - - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - Transport$1.default = Transport; - - var hidFraming = {}; - - Object.defineProperty(hidFraming, "__esModule", { - value: true - }); - - var _errors$1 = lib$2; - - var Tag = 0x05; - - function asUInt16BE(value) { - var b = Buffer$g.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - - var initialAcc = { - data: Buffer$g.alloc(0), - dataLength: 0, - sequence: 0 - }; + const listenTimeoutId = listenTimeout ? setTimeout(() => { + sub.unsubscribe(); + reject(new TransportError(this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) : null; + }); + } - /** - * - */ - var createHIDframing = function createHIDframing(channel, packetSize) { - return { - makeBlocks: function makeBlocks(apdu) { - var data = Buffer$g.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$g.concat([data, // fill data with padding - Buffer$g.alloc(nbBlocks * blockSize - data.length + 1).fill(0)]); - - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$g.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$g.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function reduceResponse(acc, chunk) { - var _ref = acc || initialAcc, - data = _ref.data, - dataLength = _ref.dataLength, - sequence = _ref.sequence; + decorateAppAPIMethods(self, methods, scrambleKey) { + for (let methodName of methods) { + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } - if (chunk.readUInt16BE(0) !== channel) { - throw new _errors$1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new _errors$1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new _errors$1.TransportError("Invalid sequence", "InvalidSequence"); - } + decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { + return async (...args) => { + const { + _appAPIlock + } = this; - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$g.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); + if (_appAPIlock) { + return Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked")); } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function getReducedResult(acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; + try { + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return await f.apply(ctx, args); + } finally { + this._appAPIlock = null; } - } - }; - }; - - hidFraming.default = createHIDframing; - - var lib$1 = {}; - - Object.defineProperty(lib$1, "__esModule", { - value: true - }); - - var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; - - /** - * The USB product IDs will be defined as MMII, encoding a model (MM) and an interface bitfield (II) - * - ** Model - * Ledger Nano S : 0x10 - * Ledger Blue : 0x00 - * Ledger Nano X : 0x40 - * - ** Interface support bitfield - * Generic HID : 0x01 - * Keyboard HID : 0x02 - * U2F : 0x04 - * CCID : 0x08 - * WebUSB : 0x10 - */ - - lib$1.IIGenericHID = 0x01; - lib$1.IIKeyboardHID = 0x02; - lib$1.IIU2F = 0x04; - lib$1.IICCID = 0x08; - lib$1.IIWebUSB = 0x10; - - var devices = { - blue: { - id: "blue", - productName: "Ledger Blue", - productIdMM: 0x00, - legacyUsbProductId: 0x0000, - usbOnly: true, - memorySize: 480 * 1024, - blockSize: 4 * 1024 - }, - nanoS: { - id: "nanoS", - productName: "Ledger Nano S", - productIdMM: 0x10, - legacyUsbProductId: 0x0001, - usbOnly: true, - memorySize: 320 * 1024, - blockSize: 4 * 1024 - }, - nanoX: { - id: "nanoX", - productName: "Ledger Nano X", - productIdMM: 0x40, - legacyUsbProductId: 0x0004, - usbOnly: false, - memorySize: 2 * 1024 * 1024, - blockSize: 4 * 1024, - bluetoothSpec: [{ - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66" - }, { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572" - }] - } - }; - - var productMap = { - Blue: "blue", - "Nano S": "nanoS", - "Nano X": "nanoX" - }; - - // $FlowFixMe - var devicesList = Object.values(devices); - - /** - * - */ - lib$1.ledgerUSBVendorId = 0x2c97; - - /** - * - */ - lib$1.getDeviceModel = function getDeviceModel(id) { - var info = devices[id]; - if (!info) throw new Error("device '" + id + "' does not exist"); - return info; - }; - - /** - * - */ - lib$1.identifyUSBProductId = function identifyUSBProductId(usbProductId) { - var legacy = devicesList.find(function (d) { - return d.legacyUsbProductId === usbProductId; - }); - if (legacy) return legacy; - - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { - return d.productIdMM === mm; - }); - return deviceModel; - }; - - lib$1.identifyProductName = function identifyProductName(productName) { - var productId = productMap[productName]; - var deviceModel = devicesList.find(function (d) { - return d.id === productId; - }); - - return deviceModel; - }; - - var bluetoothServices = []; - var serviceUuidToInfos = {}; - - for (var _id in devices) { - var _deviceModel = devices[_id]; - var _bluetoothSpec = _deviceModel.bluetoothSpec; - - if (_bluetoothSpec) { - for (var i = 0; i < _bluetoothSpec.length; i++) { - var spec = _bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = _extends({ deviceModel: _deviceModel }, spec); - } + }; } - } - - /** - * - */ - lib$1.getBluetoothServiceUuids = function getBluetoothServiceUuids() { - return bluetoothServices; - }; - - /** - * - */ - lib$1.getInfosForServiceUuid = function getInfosForServiceUuid(uuid) { - return serviceUuidToInfos[uuid.toLowerCase()]; - }; - - var lib = {}; - - Object.defineProperty(lib, "__esModule", { - value: true - }); + } + Transport.isSupported = void 0; + Transport.list = void 0; + Transport.listen = void 0; + Transport.open = void 0; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; /** * A Log object */ - var id = 0; - var subscribers = []; - + let id = 0; + const subscribers = []; /** * log something * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) * @param message a clear message of the log associated to the type */ - lib.log = function log(type, message, data) { - var obj = { type: type, id: String(++id), date: new Date() }; + + const log = (type, message, data) => { + const obj = { + type, + id: String(++id), + date: new Date() + }; if (message) obj.message = message; if (data) obj.data = data; dispatch(obj); }; - /** * listen to logs. * @param cb that is called for each future log() with the Log object * @return a function that can be called to unsubscribe the listener */ - var listen = lib.listen = function listen(cb) { + + const listen = cb => { subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); + return () => { + const i = subscribers.indexOf(cb); + if (i !== -1) { // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 subscribers[i] = subscribers[subscribers.length - 1]; @@ -33267,565 +38179,486 @@ }; function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { + for (let i = 0; i < subscribers.length; i++) { try { subscribers[i](log); } catch (e) { console.error(e); } } - } - - // for debug purpose - commonjsGlobal.__ledgerLogsListen = listen; - - var webusb = {}; - - Object.defineProperty(webusb, "__esModule", { - value: true - }); - webusb.isSupported = webusb.getFirstLedgerDevice = webusb.getLedgerDevices = webusb.requestLedgerDevice = undefined; - - var requestLedgerDevice = webusb.requestLedgerDevice = function () { - var _ref = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var device; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return navigator.usb.requestDevice({ filters: ledgerDevices }); - - case 2: - device = _context.sent; - return _context.abrupt("return", device); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function requestLedgerDevice() { - return _ref.apply(this, arguments); - }; - }(); - - var getLedgerDevices = webusb.getLedgerDevices = function () { - var _ref2 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var devices; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return navigator.usb.getDevices(); - - case 2: - devices = _context2.sent; - return _context2.abrupt("return", devices.filter(function (d) { - return d.vendorId === _devices$1.ledgerUSBVendorId; - })); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function getLedgerDevices() { - return _ref2.apply(this, arguments); - }; - }(); - - webusb.getFirstLedgerDevice = function () { - var _ref3 = _asyncToGenerator$1( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var existingDevices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return getLedgerDevices(); - - case 2: - existingDevices = _context3.sent; - - if (!(existingDevices.length > 0)) { - _context3.next = 5; - break; - } - - return _context3.abrupt("return", existingDevices[0]); - - case 5: - return _context3.abrupt("return", requestLedgerDevice()); - - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function getFirstLedgerDevice() { - return _ref3.apply(this, arguments); - }; - }(); - - var _devices$1 = lib$1; - - function _asyncToGenerator$1(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + } // for debug purpose - var ledgerDevices = [{ vendorId: _devices$1.ledgerUSBVendorId }]; - webusb.isSupported = function isSupported() { - return Promise.resolve(!!navigator && - // $FlowFixMe - !!navigator.usb && typeof navigator.usb.getDevices === "function"); - }; - - Object.defineProperty(TransportWebUSB$2, "__esModule", { - value: true - }); - - var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - - var _hwTransport = Transport$1; + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; + } - var _hwTransport2 = _interopRequireDefault(_hwTransport); + function wrapU2FTransportError(originalError, message, id) { + const err = new TransportError(message, id); // $FlowFixMe - var _hidFraming = hidFraming; + err.originalError = originalError; + return err; + } - var _hidFraming2 = _interopRequireDefault(_hidFraming); + function wrapApdu(apdu, key) { + const result = Buffer$i.alloc(apdu.length); - var _devices = lib$1; + for (let i = 0; i < apdu.length; i++) { + result[i] = apdu[i] ^ key[i % key.length]; + } - var _logs = lib; + return result; + } // Convert from normal to web-safe, strip trailing "="s - var _errors = lib$2; - var _webusb = webusb; + const webSafe64 = base64 => base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Convert from web-safe to normal, add trailing "="s - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } + const normal64 = base64 => base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { + const keyHandle = wrapApdu(apdu, scrambleKey); + const challenge = Buffer$i.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const signRequest = { + version: "U2F_V2", + keyHandle: webSafe64(keyHandle.toString("base64")), + challenge: webSafe64(challenge.toString("base64")), + appId: location.origin + }; + log("apdu", "=> " + apdu.toString("hex")); + return u2fApi.sign(signRequest, timeoutMillis / 1000).then(response => { + const { + signatureData + } = response; + + if (typeof signatureData === "string") { + const data = Buffer$i.from(normal64(signatureData), "base64"); + let result; + + if (!unwrap) { + result = data; + } else { + result = data.slice(5); + } - function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + log("apdu", "<= " + result.toString("hex")); + return result; + } else { + throw response; + } + }); + } - function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + let transportInstances = []; - var configurationValue = 1; - var endpointNumber = 3; + function emitDisconnect() { + transportInstances.forEach(t => t.emit("disconnect")); + transportInstances = []; + } + function isTimeoutU2FError(u2fError) { + return u2fError.metaData.code === 5; + } /** - * WebUSB Transport implementation + * U2F web Transport implementation * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * import TransportU2F from "@ledgerhq/hw-transport-u2f"; * ... - * TransportWebUSB.create().then(transport => ...) + * TransportU2F.create().then(transport => ...) */ - var TransportWebUSB = function (_Transport) { - _inherits(TransportWebUSB, _Transport); - - function TransportWebUSB(device, interfaceNumber) { - _classCallCheck(this, TransportWebUSB); - - var _this = _possibleConstructorReturn(this, (TransportWebUSB.__proto__ || Object.getPrototypeOf(TransportWebUSB)).call(this)); - - _initialiseProps.call(_this); - _this.device = device; - _this.interfaceNumber = interfaceNumber; - _this.deviceModel = (0, _devices.identifyUSBProductId)(device.productId); - return _this; - } - - /** - * Check if WebUSB transport is supported. + class TransportU2F extends Transport { + /* */ + /* + */ /** - * List the WebUSB devices that was previously authorized by the user. + * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) */ + static async open(_, _openTimeout = 5000) { + return new TransportU2F(); + } - + constructor() { + super(); + this.scrambleKey = void 0; + this.unwrap = true; + transportInstances.push(this); + } /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response */ - _createClass(TransportWebUSB, [{ - key: "close", + async exchange(apdu) { + try { + return await attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); + } catch (e) { + const isU2FError = typeof e.metaData === "object"; + if (isU2FError) { + if (isTimeoutU2FError(e)) { + emitDisconnect(); + } // the wrapping make error more usable and "printable" to the end user. - /** - * Release the transport device - */ - value: function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.exchangeBusyPromise; - - case 2: - _context.next = 4; - return this.device.releaseInterface(this.interfaceNumber); - - case 4: - _context.next = 6; - return this.device.reset(); - - case 6: - _context.next = 8; - return this.device.close(); - - case 8: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - function close() { - return _ref.apply(this, arguments); + throw wrapU2FTransportError(e, "Failed to sign with Ledger device: U2F " + e.metaData.type, "U2F_" + e.metaData.code); + } else { + throw e; } + } + } + /** + */ - return close; - }() - - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - }, { - key: "setScrambleKey", - value: function setScrambleKey() {} - }], [{ - key: "request", + setScrambleKey(scrambleKey) { + this.scrambleKey = Buffer$i.from(scrambleKey, "ascii"); + } + /** + */ - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - value: function () { - var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var device; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return (0, _webusb.requestLedgerDevice)(); - - case 2: - device = _context2.sent; - return _context2.abrupt("return", TransportWebUSB.open(device)); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - function request() { - return _ref2.apply(this, arguments); - } + setUnwrap(unwrap) { + this.unwrap = unwrap; + } - return request; - }() + close() { + // u2f have no way to clean things up + return Promise.resolve(); + } - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ + } + TransportU2F.isSupported = u2fApi.isSupported; - }, { - key: "openConnected", - value: function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var devices; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return (0, _webusb.getLedgerDevices)(); - - case 2: - devices = _context3.sent; - - if (!(devices.length === 0)) { - _context3.next = 5; - break; - } + TransportU2F.list = () => // this transport is not discoverable but we are going to guess if it is here with isSupported() + u2fApi.isSupported().then(supported => supported ? [null] : []); - return _context3.abrupt("return", null); + TransportU2F.listen = observer => { + let unsubscribed = false; + u2fApi.isSupported().then(supported => { + if (unsubscribed) return; - case 5: - return _context3.abrupt("return", TransportWebUSB.open(devices[0])); + if (supported) { + observer.next({ + type: "add", + descriptor: null + }); + observer.complete(); + } else { + observer.error(new TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); + } + }); + return { + unsubscribe: () => { + unsubscribed = true; + } + }; + }; - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + var TransportU2F$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': TransportU2F + }); - function openConnected() { - return _ref3.apply(this, arguments); - } + var inherits$2 = inherits$f.exports; + var HashBase = hashBase; + var Buffer$1 = safeBuffer.exports.Buffer; - return openConnected; - }() + var ARRAY16 = new Array(16); - /** - * Create a Ledger transport with a USBDevice - */ + function MD5$1 () { + HashBase.call(this, 64); - }, { - key: "open", - value: function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(device) { - var iface, interfaceNumber, transport, onDisconnect; - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return device.open(); - - case 2: - if (!(device.configuration === null)) { - _context4.next = 5; - break; - } + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } - _context4.next = 5; - return device.selectConfiguration(configurationValue); + inherits$2(MD5$1, HashBase); + + MD5$1.prototype._update = function () { + var M = ARRAY16; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; + + MD5$1.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - case 5: - _context4.next = 7; - return device.reset(); + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - case 7: - iface = device.configurations[0].interfaces.find(function (_ref5) { - var alternates = _ref5.alternates; - return alternates.some(function (a) { - return a.interfaceClass === 255; - }); - }); + // produce result + var buffer = Buffer$1.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - if (iface) { - _context4.next = 10; - break; - } + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - throw new _errors.TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); + function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } - case 10: - interfaceNumber = iface.interfaceNumber; - _context4.prev = 11; - _context4.next = 14; - return device.claimInterface(interfaceNumber); + function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - case 14: - _context4.next = 21; - break; + function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } - case 16: - _context4.prev = 16; - _context4.t0 = _context4["catch"](11); - _context4.next = 20; - return device.close(); + function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - case 20: - throw new _errors.TransportInterfaceNotAvailable(_context4.t0.message); + var md5_js = MD5$1; - case 21: - transport = new TransportWebUSB(device, interfaceNumber); + var Buffer = safeBuffer.exports.Buffer; + var Transform = require$$0__default$2["default"].Transform; + var StringDecoder = require$$2__default["default"].StringDecoder; + var inherits$1 = inherits$f.exports; - onDisconnect = function onDisconnect(e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new _errors.DisconnectedDevice()); - } - }; - // $FlowFixMe + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits$1(CipherBase, Transform); + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc); + } - navigator.usb.addEventListener("disconnect", onDisconnect); - return _context4.abrupt("return", transport); + var outData = this._update(data); + if (this.hashMode) return this - case 25: - case "end": - return _context4.stop(); - } - } - }, _callee4, this, [[11, 16]]); - })); + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } - function open(_x) { - return _ref4.apply(this, arguments); - } + return outData + }; - return open; - }() - }]); + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; - return TransportWebUSB; - }(_hwTransport2.default); + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; - TransportWebUSB.isSupported = _webusb.isSupported; - TransportWebUSB.list = _webusb.getLedgerDevices; + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - (0, _webusb.getFirstLedgerDevice)().then(function (device) { - if (!unsubscribed) { - var deviceModel = (0, _devices.identifyUSBProductId)(device.productId); - observer.next({ type: "add", descriptor: device, deviceModel: deviceModel }); - observer.complete(); - } - }, function (error) { - if (window.DOMException && error instanceof window.DOMException && error.code === 18) { - observer.error(new _errors.TransportWebUSBGestureRequired(error.message)); + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); } else { - observer.error(new _errors.TransportOpenUserCancelled(error.message)); + this.push(this._update(data)); } - }); - function unsubscribe() { - unsubscribed = true; + } catch (e) { + err = e; + } finally { + next(err); } - return { unsubscribe: unsubscribe }; }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } - var _initialiseProps = function _initialiseProps() { - var _this2 = this; - - this.channel = Math.floor(Math.random() * 0xffff); - this.packetSize = 64; - this._disconnectEmitted = false; - - this._emitDisconnect = function (e) { - if (_this2._disconnectEmitted) return; - _this2._disconnectEmitted = true; - _this2.emit("disconnect", e); - }; - - this.exchange = function (apdu) { - return _this2.exchangeAtomicImpl(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - channel = _this2.channel, packetSize = _this2.packetSize; - - (0, _logs.log)("apdu", "=> " + apdu.toString("hex")); - - framing = (0, _hidFraming2.default)(channel, packetSize); - - // Write... + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; - blocks = framing.makeBlocks(apdu); - i = 0; + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } - case 5: - if (!(i < blocks.length)) { - _context5.next = 12; - break; - } + if (this._encoding !== enc) throw new Error('can\'t switch encodings') - (0, _logs.log)("hid-frame", "=> " + blocks[i].toString("hex")); - _context5.next = 9; - return _this2.device.transferOut(endpointNumber, blocks[i]); + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } - case 9: - i++; - _context5.next = 5; - break; + return out + }; - case 12: + var cipherBase = CipherBase; - // Read... - result = void 0; - acc = void 0; + var inherits = inherits$f.exports; + var MD5 = md5_js; + var RIPEMD160 = ripemd160$1; + var sha = sha_js.exports; + var Base = cipherBase; - case 14: - if (result = framing.getReducedResult(acc)) { - _context5.next = 23; - break; - } + function Hash (hash) { + Base.call(this, 'digest'); - _context5.next = 17; - return _this2.device.transferIn(endpointNumber, packetSize); + this._hash = hash; + } - case 17: - r = _context5.sent; - buffer = Buffer$g.from(r.data.buffer); + inherits(Hash, Base); - (0, _logs.log)("hid-frame", "<= " + buffer.toString("hex")); - acc = framing.reduceResponse(acc, buffer); - _context5.next = 14; - break; + Hash.prototype._update = function (data) { + this._hash.update(data); + }; - case 23: + Hash.prototype._final = function () { + return this._hash.digest() + }; - (0, _logs.log)("apdu", "<= " + result.toString("hex")); - return _context5.abrupt("return", result); + var browser = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5, _this2); - }))).catch(function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this2._emitDisconnect(e); - throw new _errors.DisconnectedDeviceDuringOperation(e.message); - } - throw e; - }); - }; + return new Hash(sha(alg)) }; - var _default = TransportWebUSB$2.default = TransportWebUSB; - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ __proto__: null, - 'default': _default - }, [TransportWebUSB$2])); + 'default': browser + }, [browser])); exports.Btc = Btc$1; + exports.Log = index; + exports.TransportU2F = TransportU2F$1; exports.TransportWebUSB = TransportWebUSB$1; - exports.createHash = index; + exports.createHash = browser$1; Object.defineProperty(exports, '__esModule', { value: true }); })); window.Btc = NewLedger.Btc.default; -window.TransportWebUSB = NewLedger.TransportWebUSB.default; \ No newline at end of file +window.TransportWebUSB = NewLedger.TransportWebUSB.default; +window.TransportU2F = NewLedger.TransportU2F.default; +window.Log = NewLedger.Log.default; +window.createHash = NewLedger.createHash.default; From 038a2e5d5887237c5dac4b9de3e8d5ac04bd839c Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 21:39:29 +1100 Subject: [PATCH 16/78] in sunny's name --- js/ledger.js | 38657 +------------------------------------------------ 1 file changed, 3 insertions(+), 38654 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index c310956e..f145aaf8 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,38660 +2,9 @@ window.global = window; window.Buffer = buffer.Buffer; -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util'), require('string_decoder')) : - typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util', 'string_decoder'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.EventEmitter, global.require$$1, global.require$$2)); -})(this, (function (exports, require$$0$2, require$$0$3, require$$0$4, EventEmitter, require$$1, require$$2) { 'use strict'; - - function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - - function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { - if (k !== 'default' && !(k in n)) { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - }); - return Object.freeze(n); - } - - var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); - var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); - var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); - var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); - var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); - var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; - } - - var runtime = {exports: {}}; - - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - (function (module) { - var runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function define(obj, key, value) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - return obj[key]; - } - try { - // IE 8 has a broken Object.defineProperty that only works on DOM objects. - define({}, ""); - } catch (err) { - define = function(obj, key, value) { - return obj[key] = value; - }; - } - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - define(IteratorPrototype, iteratorSymbol, function () { - return this; - }); - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = GeneratorFunctionPrototype; - define(Gp, "constructor", GeneratorFunctionPrototype); - define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); - GeneratorFunction.displayName = define( - GeneratorFunctionPrototype, - toStringTagSymbol, - "GeneratorFunction" - ); - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - define(prototype, method, function(arg) { - return this._invoke(method, arg); - }); - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - define(genFun, toStringTagSymbol, "GeneratorFunction"); - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - define(AsyncIterator.prototype, asyncIteratorSymbol, function () { - return this; - }); - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList), - PromiseImpl - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - define(Gp, toStringTagSymbol, "Generator"); - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - define(Gp, iteratorSymbol, function() { - return this; - }); - - define(Gp, "toString", function() { - return "[object Generator]"; - }); - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined$1, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined$1; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - - }( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports - )); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, in modern engines - // we can explicitly access globalThis. In older engines we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - if (typeof globalThis === "object") { - globalThis.regeneratorRuntime = runtime; - } else { - Function("r", "regeneratorRuntime = r")(runtime); - } - } - }(runtime)); - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } - - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - 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]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') - } - - function read (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) - } - - function write (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; - } - - var toString = {}.toString; - - var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use 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+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$i.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; - - function kMaxLength () { - return Buffer$i.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$i.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$i(length); - } - that.length = length; - } - - return that - } - - /** - * 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$i (arg, encodingOrOffset, length) { - if (!Buffer$i.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$i)) { - return new Buffer$i(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from$2(this, arg, encodingOrOffset, length) - } - - Buffer$i.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$i._augment = function (arr) { - arr.__proto__ = Buffer$i.prototype; - return arr - }; - - function from$2 (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, 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$i.from = function (value, encodingOrOffset, length) { - return from$2(null, value, encodingOrOffset, length) - }; - - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - Buffer$i.prototype.__proto__ = Uint8Array.prototype; - Buffer$i.__proto__ = Uint8Array; - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$i.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$i.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$i.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$i.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - var actual = that.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') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$i.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that - } - - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - Buffer$i.isBuffer = isBuffer; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer$i.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var 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$i.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$i.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer$i.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$i.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - 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 utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer$i.byteLength = byteLength; - - function slowToString (encoding, start, end) { - var 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 coersion 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; - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$i.prototype._isBuffer = true; - - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$i.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this - }; - - Buffer$i.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this - }; - - Buffer$i.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var 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$i.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; - - Buffer$i.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$i.compare(this, b) === 0 - }; - - Buffer$i.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' - }; - - Buffer$i.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - 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 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var 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 (isNaN(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$i.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(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 (Buffer$i.TYPED_ARRAY_SUPPORT && - 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) { - var indexSize = 1; - var arrLength = arr.length; - var 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) - } - } - - var i; - if (dir) { - var 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--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer$i.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$i.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer$i.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(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 latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, 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$i.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; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var 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'; - - var 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': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(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$i.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 fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var 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 - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray (codePoints) { - var 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". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex$1(buf[i]); - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res - } - - Buffer$i.prototype.slice = function slice (start, end) { - var 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; - - var newBuf; - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$i.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$i(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - 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$i.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val - }; - - Buffer$i.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val - }; - - Buffer$i.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; - - Buffer$i.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer$i.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer$i.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer$i.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer$i.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var 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$i.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var 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$i.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer$i.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$i.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$i.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer$i.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer$i.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer$i.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer$i.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer$i.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(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$i.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$i.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$i.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$i.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$i.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer$i.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$i.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer$i.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var 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$i.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var 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$i.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer$i.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$i.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - Buffer$i.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$i.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; - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - 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) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer$i.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; - - Buffer$i.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer$i.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; - - Buffer$i.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$i.prototype.copy = function copy (target, targetStart, start, end) { - 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('sourceStart out of bounds') - 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; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$i.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$i.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 (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$i.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // 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; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$i(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).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 stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex$1 (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var 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) { - var byteArray = []; - for (var 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) { - var c, hi, lo; - var byteArray = []; - for (var 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 toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } - - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } - - /* - * Bitcoin BIP32 path helpers - * (C) 2016 Alex Beregszaszi - */ - - const HARDENED = 0x80000000; - - var BIPPath = function (path) { - if (!Array.isArray(path)) { - throw new Error('Input must be an Array') - } - if (path.length === 0) { - throw new Error('Path must contain at least one level') - } - for (var i = 0; i < path.length; i++) { - if (typeof path[i] !== 'number') { - throw new Error('Path element is not a number') - } - } - this.path = path; - }; - - BIPPath.validatePathArray = function (path) { - try { - BIPPath.fromPathArray(path); - return true - } catch (e) { - return false - } - }; - - BIPPath.validateString = function (text, reqRoot) { - try { - BIPPath.fromString(text, reqRoot); - return true - } catch (e) { - return false - } - }; - - BIPPath.fromPathArray = function (path) { - return new BIPPath(path) - }; - - BIPPath.fromString = function (text, reqRoot) { - // skip the root - if (/^m\//i.test(text)) { - text = text.slice(2); - } else if (reqRoot) { - throw new Error('Root element is required') - } - - var path = text.split('/'); - var ret = new Array(path.length); - for (var i = 0; i < path.length; i++) { - var tmp = /(\d+)([hH\']?)/.exec(path[i]); - if (tmp === null) { - throw new Error('Invalid input') - } - ret[i] = parseInt(tmp[1], 10); - - if (ret[i] >= HARDENED) { - throw new Error('Invalid child index') - } - - if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { - ret[i] += HARDENED; - } else if (tmp[2].length != 0) { - throw new Error('Invalid modifier') - } - } - return new BIPPath(ret) - }; - - BIPPath.prototype.toPathArray = function () { - return this.path - }; - - BIPPath.prototype.toString = function (noRoot, oldStyle) { - var ret = new Array(this.path.length); - for (var i = 0; i < this.path.length; i++) { - var tmp = this.path[i]; - if (tmp & HARDENED) { - ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); - } else { - ret[i] = tmp; - } - } - return (noRoot ? '' : 'm/') + ret.join('/') - }; - - BIPPath.prototype.inspect = function () { - return 'BIPPath <' + this.toString() + '>' - }; - - var bip32Path = BIPPath; - - var createHash$3 = require$$0__default["default"].createHash; - - var safeBuffer = {exports: {}}; - - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - - (function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0__default$1["default"]; - 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) - }; - }(safeBuffer, safeBuffer.exports)); - - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; - } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; - } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; - } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str - } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; - } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; - } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } - } - var src$2 = base$2; - - var basex = src$2; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - - var bs58 = basex(ALPHABET$1); - - var base58 = bs58; - var Buffer$h = safeBuffer.exports.Buffer; - - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); - - return base58.encode(Buffer$h.concat([ - payload, - checksum - ], payload.length + 4)) - } - - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); - - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return - - return payload - } - - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return - - return decodeRaw(buffer) - } - - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload - } - - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } - }; - - var createHash$2 = createHash$3; - var bs58checkBase = base$1; - - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$2('sha256').update(buffer).digest(); - return createHash$2('sha256').update(tmp).digest() - } - - var bs58check$5 = bs58checkBase(sha256x2); - - function pathElementsToBuffer(paths) { - var buffer = Buffer$i.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; - } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); - } - } - return []; - } - - var src$1 = {}; - - var src = {}; - - var bip32$1 = {}; - - var crypto$4 = {}; - - var createHmac$2 = require$$0__default["default"].createHmac; - - Object.defineProperty(crypto$4, "__esModule", { value: true }); - const createHash$1 = createHash$3; - const createHmac$1 = createHmac$2; - function hash160$2(buffer) { - const sha256Hash = createHash$1('sha256') - .update(buffer) - .digest(); - try { - return createHash$1('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$1('ripemd160') - .update(sha256Hash) - .digest(); - } - } - crypto$4.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); - } - crypto$4.hmacSHA512 = hmacSHA512; - - var tinySecp256k1 = {exports: {}}; - - var bn$1 = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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 = require('buffer').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) ; 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); - }; - })(module, commonjsGlobal); - }(bn$1)); - - var elliptic = {}; - - var name = "elliptic"; - var version$1 = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0$1 = { - name: name, - version: version$1, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; - - var utils$n = {}; - - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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 = require('buffer').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) ; 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); - }; - })(module, commonjsGlobal); - }(bn)); - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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; - }; - }(utils$m)); - - (function (exports) { - - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; - - 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; - }(utils$n)); - - var brorand = {exports: {}}; - - var r$1; - - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); - }; - - function Rand(rand) { - this.rand = rand; - } - brorand.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$3 = require('crypto'); - if (typeof crypto$3.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto$3.randomBytes(n); - }; - } catch (e) { - } - } - - var curve = {}; - - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; - - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN$8(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); - } - } - var base = 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$e(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$e(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]; - 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(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$l.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; - }; - - var inherits$f = {exports: {}}; - - var inherits_browser = {exports: {}}; - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - inherits_browser.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; - } - }; - } - - try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - inherits$f.exports = util.inherits; - } catch (e) { - /* istanbul ignore next */ - inherits$f.exports = inherits_browser.exports; - } - - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$e = inherits$f.exports; - var Base$3 = base; - - var assert$d = utils$k.assert; - - function ShortCurve(conf) { - Base$3.call(this, 'short', conf); - - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(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$e(ShortCurve, Base$3); - var short = 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$7(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$7(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$d(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$7(vec.a, 16), - b: new BN$7(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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN$7(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$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { - Base$3.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$e(Point$2, Base$3.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$3.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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$e(JPoint, Base$3.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$7(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; - }; - - var BN$6 = bn.exports; - var inherits$d = inherits$f.exports; - var Base$2 = base; - - var utils$j = utils$n; - - function MontCurve(conf) { - Base$2.call(this, 'mont', conf); - - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); - } - inherits$d(MontCurve, Base$2); - var mont = 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$1(curve, x, z) { - Base$2.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$6(x, 16); - this.z = new BN$6(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$d(Point$1, Base$2.BasePoint); - - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; - - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; - - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; - - Point$1.prototype.precompute = function precompute() { - // No-op - }; - - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; - - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; - - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; - - Point$1.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$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; - - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; - }; - - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); - }; - - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$c = inherits$f.exports; - var Base$1 = base; - - var assert$c = utils$i.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$1.call(this, 'edwards', conf); - - this.a = new BN$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits$c(EdwardsCurve, Base$1); - var edwards = 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$5(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$5(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$1.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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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$c(Point, Base$1.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; - - (function (exports) { - - var curve = exports; - - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); - - var curves$2 = {}; - - var hash$3 = {}; - - var utils$h = {}; - - var assert$b = minimalisticAssert; - var inherits$b = inherits$f.exports; - - utils$h.inherits = inherits$b; - - 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; - } - utils$h.toArray = toArray; - - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils$h.toHex = toHex; - - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.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; - } - utils$h.toHex32 = toHex32; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils$h.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; - } - utils$h.zero8 = zero8; - - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.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; - } - utils$h.split32 = split32; - - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); - } - utils$h.rotr32 = rotr32$1; - - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; - - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; - - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; - - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; - - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - utils$h.sum32_5 = sum32_5$2; - - function sum64$1(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; - } - utils$h.sum64 = sum64$1; - - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - utils$h.sum64_hi = sum64_hi$1; - - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - utils$h.sum64_lo = sum64_lo$1; - - function sum64_4_hi$1(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; - } - utils$h.sum64_4_hi = sum64_4_hi$1; - - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; - - function sum64_5_hi$1(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; - } - utils$h.sum64_5_hi = sum64_5_hi$1; - - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; - } - utils$h.sum64_5_lo = sum64_5_lo$1; - - function rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - utils$h.rotr64_hi = rotr64_hi$1; - - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.rotr64_lo = rotr64_lo$1; - - function shr64_hi$1(ah, al, num) { - return ah >>> num; - } - utils$h.shr64_hi = shr64_hi$1; - - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.shr64_lo = shr64_lo$1; - - var common$5 = {}; - - var utils$g = utils$h; - var assert$a = minimalisticAssert; - - function BlockHash$4() { - 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; - } - common$5.BlockHash = BlockHash$4; - - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); - - return this._digest(enc); - }; - - BlockHash$4.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; - }; - - var sha$3 = {}; - - var common$4 = {}; - - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; - - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; - - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; - - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; - - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; - - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; - - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; - - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; - - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - common$4.g1_256 = g1_256$1; - - var utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; - - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; - - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; - - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); - } - - utils$e.inherits(SHA1, BlockHash$3); - var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); - }; - - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); - }; - - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; - - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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$2 = common$2.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$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$1; - - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; - - SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; - - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); - else - return utils$d.split32(this.h, 'big'); - }; - - var utils$c = utils$h; - var SHA256 = _256; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils$c.inherits(SHA224, SHA256); - var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); - }; - - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; - - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; - - var BlockHash$1 = common$1.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$2() { - if (!(this instanceof SHA512$2)) - return new SHA512$2(); - - BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); - var _512 = SHA512$2; - - SHA512$2.blockSize = 1024; - SHA512$2.outSize = 512; - SHA512$2.hmacStrength = 192; - SHA512$2.padLength = 128; - - SHA512$2.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$2.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$8(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); - 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); - 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$2.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.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; - } - - var utils$a = utils$h; - - var SHA512$1 = _512; - - function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512$1.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; - } - utils$a.inherits(SHA384, SHA512$1); - var _384 = SHA384; - - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; - - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); - }; - - sha$3.sha1 = _1; - sha$3.sha224 = _224; - sha$3.sha256 = _256; - sha$3.sha384 = _384; - sha$3.sha512 = _512; - - var ripemd = {}; - - var utils$9 = utils$h; - var common = common$5; - - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; - var BlockHash = common.BlockHash; - - function RIPEMD160$2() { - if (!(this instanceof RIPEMD160$2)) - return new RIPEMD160$2(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils$9.inherits(RIPEMD160$2, BlockHash); - ripemd.ripemd160 = RIPEMD160$2; - - RIPEMD160$2.blockSize = 512; - RIPEMD160$2.outSize = 160; - RIPEMD160$2.hmacStrength = 192; - RIPEMD160$2.padLength = 64; - - RIPEMD160$2.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$4(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$2.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); - else - return utils$9.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$4(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 - ]; - - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; - - 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$8.toArray(key, enc)); - } - var hmac = Hmac; - - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(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); - }; - - (function (exports) { - var hash = exports; - - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha$3; - hash.ripemd = ripemd; - hash.hmac = hmac; - - // 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; - }(hash$3)); - - (function (exports) { - - var curves = exports; - - var hash = hash$3; - var curve$1 = curve; - var utils = utils$n; - - var assert = utils.assert; - - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.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 = require('./precomputed/secp256k1'); - } 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, - ], - }); - }(curves$2)); - - var hash$2 = hash$3; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; - - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; - - HmacDRBG$1.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$1.prototype._hmac = function hmac() { - return new hash$2.hmac(this.hash, this.K); - }; - - HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); - - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; - }; - - HmacDRBG$1.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$7.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$7.encode(res, enc); - }; - - var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; - - function KeyPair$4(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); - } - var key$1 = KeyPair$4; - - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; - - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); - }; - - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; - - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); - }; - - KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; - - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(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$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); - }; - - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); - }; - - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); - }; - - KeyPair$4.prototype.inspect = function inspect() { - return ''; - }; - - var BN$3 = bn.exports; - - var utils$5 = utils$n; - var assert$4 = utils$5.assert; - - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; - - if (this._importDER(options, enc)) - return; - - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; - - 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$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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$3(r); - this.s = new BN$3(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$3.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$5.encode(res, enc); - }; - - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; - - var KeyPair$3 = key$1; - var Signature$2 = signature$1; - - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); - - options = curves$1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.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; - } - var ec = EC$1; - - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); - }; - - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); - }; - - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); - }; - - EC$1.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(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; - - EC$1.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$1.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$2(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$2(1)); - - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); - } - }; - - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); - - var n = this.n; - var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(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'); - }; - - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes$2(params.pub); - } - - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); - }; - - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); - }; - - KeyPair$2.prototype.secret = function secret() { - return this._secret; - }; - - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); - - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); - - cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); - - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); - - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); - - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); - }; - - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; - - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); - }; - - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); - }; - - var key = KeyPair$2; - - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.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$1(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; - } - - assert$1(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - 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$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); - - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); - - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); - - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); - - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; - - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; - - var signature = Signature$1; - - var hash$1 = hash$3; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; - - 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$1.sha512; - } - - var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); - }; - - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; - - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); - }; - - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; - - (function (exports) { - - var elliptic = exports; - - elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; - - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); - - const createHmac = createHmac$2; - - const ONE1 = Buffer$i.alloc(1, 1); - const ZERO1 = Buffer$i.alloc(1, 0); - - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer$i.alloc(32, 0); - let v = Buffer$i.alloc(32, 1); - - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step E - v = createHmac('sha256', k).update(v).digest(); - - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step G - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); - - let T = v; - - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); - - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; - } - - return T - } - - var rfc6979 = deterministicGenerateK$1; - - const BN = bn$1.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; - - const ZERO32 = Buffer$i.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$i.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$i.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); - - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; - - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; - - function isScalar (x) { - return isBuffer(x) && x.length === 32 - } - - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isPoint (p) { - if (!isBuffer(p)) return false - if (p.length < 33) return false - - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } - - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false - } - - function __isPointCompressed (p) { - return p[0] !== 0x04 - } - - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) - } - - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 - } - - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value - } - - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$i, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$i.from(P._encode(compressed)) } - - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) - - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) - } - - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) - - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null - - return getEncoded(uu, compressed) - } - - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - - const compressed = assumeCompression(__compressed, p); - - return getEncoded(pp, compressed) - } - - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } - - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null - - return getEncoded(qq, compressed) - } - - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function sign$1 (hash, x) { - return __sign(hash, x) - } - - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) - } - - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) - - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); - - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); - - if (Q.isInfinity()) return false - - r = Q.x.umod(n); - if (r.isZero() === 0) return false - - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false - - return true - }; - - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); - - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); - } - - const buffer = Buffer$i.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer - } - - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) - - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); - - if (strict && s.cmp(nDiv2) > 0) { - return false - } - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false - - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); - - // Compute s^-1 - const sInv = s.invm(n); - - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); - - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); - - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false - - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; - - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); - - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } - - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign: sign$1, - signWithEntropy, - verify - }; - - try { - tinySecp256k1.exports = require('./native'); - } catch (err) { - tinySecp256k1.exports = js; - } - - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } - }; - - // TODO: deprecate - types$c.Null = types$c.Nil; - - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); - } - - var native$1 = types$c; - - var native = native$1; - - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] - } - - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) - } - - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value - } - - function captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } - } - - function tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' - - return type !== undefined ? type : '' - } - - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); - - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') - } - - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); - - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; - - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; - - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) - } - - function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } - - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; - - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) - } - - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; - - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); - - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } - - captureStackTrace(e); - return e - } - - var errors$1 = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 - }; - - var NATIVE$1 = native$1; - var ERRORS$1 = errors$1; - - function _Buffer (value) { - return isBuffer(value) - } - - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } - - function _LengthN (type, length) { - var name = type.toJSON(); - - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true - - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; - - return Length - } - - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); - - function Range$b (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) - } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - }; - return _range - } - - var INT53_MAX = Math.pow(2, 53) - 1; - - function Finite (value) { - return typeof value === 'number' && isFinite(value) - } - function Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value - } - function UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value - } - - var types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$b, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; - - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); - } - - var extra = types$b; - - var ERRORS = errors$1; - var NATIVE = native$1; - - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; - - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; - - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false - - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; - - return _arrayOf - }, - - maybe: function maybe (type) { - type = compile(type); - - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; - - return _maybe - }, - - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); - - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } - - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } - } - - return true - } - - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; - } - - return _map - }, - - object: function object (uncompiled) { - var type = {}; - - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } - - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - var propertyName; - - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; - - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } - - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue - - throw new TfPropertyTypeError(undefined, propertyName) - } - } - - return true - } - _object.toJSON = function () { return tfJSON(type) }; - - return _object - }, - - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); - - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - - return _anyOf - }, - - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); - - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - - return _allOf - }, - - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type }; - - return _quacksLike - }, - - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); - - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false - - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; - - return _tuple - }, - - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected }; - - return _value - } - }; - - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; - - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) - - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } - - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } - - return TYPES.value(type) - } - - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true - - throw new TfTypeError(surrogate || type, value) - } - - // JIT - return typeforce$b(compile(type), value, strict) - } - - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } - - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } - - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } - - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; - - var typeforce_1 = typeforce$b; - - var bs58check$4 = bs58check$5; - - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') - - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false - } - } - - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') - - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') - - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } - - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$i(compressed ? 34 : 33); - - result.writeUInt8(version, 0); - privateKey.copy(result, 1); - - if (compressed) { - result[33] = 0x01; - } - - return result - } - - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) - } - - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) - - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } - - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw - }; - - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$2 = crypto$4; - const bs58check$3 = bs58check$5; - const ecc$6 = tinySecp256k1.exports; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; - } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$2.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer$i.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); - } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer$i.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$2.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; - } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); - } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); - } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); - } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$i.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } - } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); - } - return hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); - } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); - } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); - } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); - } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$2.hmacSHA512(Buffer$i.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); - } - bip32$1.fromSeed = fromSeed; - - Object.defineProperty(src, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; - - var address$1 = {}; - - var networks$3 = {}; - - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - - var payments$4 = {}; - - var embed = {}; - - var script$1 = {}; - - var script_number = {}; - - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); - } - } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; - } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); - } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer$i.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; - } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; - } - return buffer; - } - script_number.encode = encode$g; - - var script_signature = {}; - - var types$a = {}; - - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; - }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, - }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; - - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use - - var Buffer$g = safeBuffer.exports.Buffer; - - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false - - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false - - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false - - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true - } - - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } - } - - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer$g.allocUnsafe(6 + lenR + lenS); - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); - - return signature - } - - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f - }; - - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$i.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer$i.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$i.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer$i.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$i.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer$i.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; - - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE - }; - - var OPS$9 = require$$7; - - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 - } - - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); - - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); - - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); - - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); - - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); - } - - return size - } - - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; - - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; - - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; - - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; - - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - - number = buffer.readUInt32LE(offset + 1); - size = 5; - } - - return { - opcode: opcode, - number: number, - size: size - } - } - - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c - }; - - var OPS$8 = require$$7; - - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } - - var map_1 = map; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = tinySecp256k1.exports; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer$i.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; - } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; - } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode - } else { - chunks.push(opcode); - i += 1; - } - } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); - } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer$i.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$i.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); - - var lazy$7 = {}; - - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; - }; - } - lazy$7.value = value; - - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } - } - return Object.assign(o, a); - } - embed.p2data = p2data; - - var p2ms$3 = {}; - - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = tinySecp256k1.exports; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); - } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); - } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); - } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); - } - } - return Object.assign(o, a); - } - p2ms$3.p2ms = p2ms$2; - - var p2pk$3 = {}; - - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = tinySecp256k1.exports; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); - } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); - } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); - } - } - return Object.assign(o, a); - } - p2pk$3.p2pk = p2pk$2; - - var p2pkh$4 = {}; - - var crypto$1 = {}; - - Object.defineProperty(crypto$1, '__esModule', { value: true }); - const createHash = createHash$3; - function ripemd160$2(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); - } - } - crypto$1.ripemd160 = ripemd160$2; - function sha1$1(buffer) { - return createHash('sha1') - .update(buffer) - .digest(); - } - crypto$1.sha1 = sha1$1; - function sha256$2(buffer) { - return createHash('sha256') - .update(buffer) - .digest(); - } - crypto$1.sha256 = sha256$2; - function hash160$1(buffer) { - return ripemd160$2(sha256$2(buffer)); - } - crypto$1.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$2(sha256$2(buffer)); - } - crypto$1.hash256 = hash256$1; - - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); - const bcrypto$6 = crypto$1; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = tinySecp256k1.exports; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - } - if (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2pkh$4.p2pkh = p2pkh$3; - - var p2sh$1 = {}; - - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$1; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } - } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); - } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - } - } - return Object.assign(o, a); - } - p2sh$1.p2sh = p2sh; - - var p2wpkh$2 = {}; - - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; - - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; - } - - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) - } - - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' - - chk = polymodStep(chk) ^ (c >> 5); - } - chk = polymodStep(chk); - - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk - } - - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - - prefix = prefix.toLowerCase(); - - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) - - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') - - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } - - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; - - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } - - return result - } - - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' - - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; - - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str - - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' - - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk - - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; - - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); - } - - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } - } - - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - } - - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - - throw new Error(res) - } - - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; - - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } - - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' - } - - return result - } - - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - } - - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - } - - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords - }; - - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); - const bcrypto$4 = crypto$1; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = tinySecp256k1.exports; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$i.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$i.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2wpkh$2.p2wpkh = p2wpkh$1; - - var p2wsh$1 = {}; - - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$1; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = tinySecp256k1.exports; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$i.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - function chunkHasUncompressedPubkey(chunk) { - if ( - isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; - } else { - return false; - } - } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$i.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; - } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), - }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); - } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); - } - } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); - } - } - return Object.assign(o, a); - } - p2wsh$1.p2wsh = p2wsh; - - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; - - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer$i.from(data), - }; - } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); - } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); - } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); - } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; - } - } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; - - var ecpair = {}; - - var randombytes = require$$0__default["default"].randomBytes; - - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = tinySecp256k1.exports; - const randomBytes = randombytes; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$i.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; - - var block = {}; - - var bufferutils = {}; - - var Buffer$f = safeBuffer.exports.Buffer; - - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; - - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') - } - - function encode$b (number, buffer, offset) { - checkUInt53$1(number); - - if (!buffer) buffer = Buffer$f.allocUnsafe(encodingLength$1(number)); - if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; - - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; - - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; - - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } - - return buffer - } - - function decode$a (buffer, offset) { - if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - var first = buffer.readUInt8(offset); - - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first - - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) - - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) - - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); - - return number - } - } - - function encodingLength$1 (number) { - checkUInt53$1(number); - - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } - - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; - - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer$i.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; - } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); - } - } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); - } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); - } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; - } - } - bufferutils.BufferReader = BufferReader$1; - - var transaction = {}; - - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$1; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; - } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); - } - const EMPTY_SCRIPT = Buffer$i.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer$i.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer$i.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer$i.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, - }; - function isOutput(out) { - return out.value !== undefined; - } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; - } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); - } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); - } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); - } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); - } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer$i.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; - } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; - } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; - } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); - } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; - } - // serialize and hash - const buffer = Buffer$i.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer$i.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$i.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); - } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer$i.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); - } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer$i.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer$i.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); - } - tbuffer = Buffer$i.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$i.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$i.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); - } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); - } else { - bufferWriter.writeSlice(txOut.valueBuffer); - } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); - } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; - } - } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; - - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') - - var length = values.length; - var results = values.concat(); - - while (length > 1) { - var j = 0; - - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$i.concat([left, right]); - - results[j] = digestFn(data); - } - - length = j; - } - - return results[0] - }; - - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$1; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); - } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer$i.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer$i.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer$i.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer$i.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$i && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer$i && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer$i.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; - } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); - } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); - } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; - } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; - } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; - } - } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { - return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 - ); - } - function anyTxHasWitness(transactions) { - return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) - ); - } - - var psbt$1 = {}; - - var psbt = {}; - - var combiner = {}; - - var parser = {}; - - var fromBuffer = {}; - - var converter = {}; - - var typeFields = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); - - var globalXpub$1 = {}; - - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer$i.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$i.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$i.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); - } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 - ); - } - globalXpub$1.canAddToArray = canAddToArray$1; - - var unsignedTx$1 = {}; - - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer$i.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), - }; - } - unsignedTx$1.encode = encode$9; - - var finalScriptSig$1 = {}; - - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer$i.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, - }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; - - var finalScriptWitness$1 = {}; - - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer$i.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); - return { - key, - value: data, - }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); - } - finalScriptWitness$1.canAdd = canAdd$4; - - var nonWitnessUtxo$1 = {}; - - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer$i.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, - }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; - } - nonWitnessUtxo$1.canAdd = canAdd$3; - - var partialSig$1 = {}; - - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, - }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer$i.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer$i.concat([head, pSig.pubkey]), - value: pSig.signature, - }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) - ); - } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; - - var porCommitment$1 = {}; - - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer$i.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); - return { - key, - value: Buffer$i.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; - } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; - } - porCommitment$1.canAdd = canAdd$2; - - var sighashType$1 = {}; - - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.readUInt32LE(0); - } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer$i.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$i.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; - } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; - } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; - } - sighashType$1.canAdd = canAdd$1; - - var witnessUtxo$1 = {}; - - var tools = {}; - - var varint$1 = {}; - - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) - throw new RangeError('value out of range'); - } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer$i.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } - return buffer; - } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; - } - } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; - } - varint$1.encodingLength = encodingLength; - - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$i.from([0])); - return Buffer$i.concat(buffers); - } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$i.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, - ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; - } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; - } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - tools.writeUInt64LE = writeUInt64LE; - - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); - } - return { - script, - value, - }; - } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$i.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer$i.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, - }; - } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; - } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; - } - witnessUtxo$1.canAdd = canAdd; - - var bip32Derivation$1 = {}; - - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); - } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - function encode(data) { - const head = Buffer$i.from([TYPE_BYTE]); - const key = Buffer$i.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$i.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - return { - decode, - encode, - check, - expected, - canAddToArray, - }; - } - bip32Derivation$1.makeConverter = makeConverter$2; - - var checkPubkey$1 = {}; - - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); - if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } - } - return pubkey; - } - } - checkPubkey$1.makeChecker = makeChecker; - - var redeemScript$1 = {}; - - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$i.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - redeemScript$1.makeConverter = makeConverter$1; - - var witnessScript$1 = {}; - - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$i.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - witnessScript$1.makeConverter = makeConverter; - - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), - }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), - }; - converter.outputs = outputs; - - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; - } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); - return { - key, - value, - }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); - } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; - } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', - ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); - } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); - } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); - } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); - } - inputKeyVals.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); - } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); - } - outputKeyVals.push(output); - } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); - } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$i.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); - } - } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; - } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); - } - } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - } - } - inputs.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - } - } - outputs.push(output); - } - return { globalMap, inputs, outputs }; - } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - - var toBuffer = {}; - - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer$i.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$i.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$i.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); - } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); - }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); - } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along - return { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), - }; - } - toBuffer.psbtToKeyVals = psbtToKeyVals; - - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); - - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); - } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); - } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); - } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, - }); - } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); - }; - } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; - } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); - }); - return set; - } - - var utils = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; - } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); - } - if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 - ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); - } - } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } - }); - return count; - } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; - } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); - } - } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, - ); - } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; - } - } - } - }; - } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); - } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); - } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); - } - txBuf.writeUInt32LE(version, 0); - return txBuf; - } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); - } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; - } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); - - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, - }; - } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer$i.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer$i.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); - } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); - return this; - } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); - return this; - } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - return this; - } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); - return this; - } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; - } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } - return this; - } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; - } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); - } - } - psbt.Psbt = Psbt$1; - - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$1; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, - }; - /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. - */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); - } - static fromBase64(data, opts = {}) { - const buffer = Buffer$i.from(data, 'base64'); - return this.fromBuffer(buffer, opts); - } - static fromHex(data, opts = {}) { - const buffer = Buffer$i.from(data, 'hex'); - return this.fromBuffer(buffer, opts); - } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; - } - get inputCount() { - return this.data.inputs.length; - } - get version() { - return this.__CACHE.__TX.version; - } - set version(version) { - this.setVersion(version); - } - get locktime() { - return this.__CACHE.__TX.locktime; - } - set locktime(locktime) { - this.setLocktime(locktime); - } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); - } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); - } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; - } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; - } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; - } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; - } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; - } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); - } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; - } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; - } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); - } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; - } - addOutput(outputData) { - if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) - ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); - } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); - } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); - return tx; - } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); - } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); - return this; - } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, - ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); - return this; - } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), - ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); - } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) - ); - } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); - } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); - } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), - ); - return results.reduce((final, res) => res === true && final, true); - } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); - } - return results.every(res => res === true); - } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$1(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; - } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); - } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; - } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - }); - }); - } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); - } - toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); - } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); - } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; - } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); - } - return this; - } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; - } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; - } - } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer$i.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); - } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; - } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); - } - addOutput(output) { - if ( - output.script === undefined || - output.value === undefined || - !isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); - } - toBuffer() { - return this.tx.toBuffer(); - } - } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; - } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); - } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; - } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); - } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, - ); - } - } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } - }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } - }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } - }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, - ); - } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); - } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); - } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); - } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; - } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, - ); - } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } - } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, - ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; - } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); - throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, - ); - } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); - } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, - ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, - ); - } - return { - script: meaningfulScript, - sighashType, - hash, - }; - } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - } - return payment; - } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); - } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, - }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } - } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; - } - return res; - } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); - } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { - throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', - ); - } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; - } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); - } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); - } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; - } - function readVarSlice() { - return readSlice(readVarInt()); - } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; - } - return readVector(); - } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; - } - return text; - } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer$i.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer$i.concat([buffer, Buffer$i.from(slice)]); - } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer$i.concat([buffer, Buffer$i.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); - } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); - } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); - } - writeVector(witness); - return buffer; - } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, - }); - } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; - } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); - } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); - } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); - } - return c[inputIndex]; - } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); - } - } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; - if ( - !isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); - } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); - } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) - throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', - ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; - } - return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', - }; - } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); - } - } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); - } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; - } - function range$1(n) { - return [...Array(n).keys()]; - } - - var transaction_builder = {}; - - var classify$1 = {}; - - var multisig$1 = {}; - - var input$b = {}; - - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); - } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); - } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); - } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - - var output$e = {}; - - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); - } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; - - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; - - var nulldata = {}; - - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; - } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - - var pubkey = {}; - - var input$9 = {}; - - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); - } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; - - var output$b = {}; - - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG - ); - } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; - - var pubkeyhash = {}; - - var input$7 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); - } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; - - var output$9 = {}; - - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG - ); - } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; - - var scripthash = {}; - - var input$5 = {}; - - var output$7 = {}; - - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 - ); - } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; - }; - - var output$6 = {}; - - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); - } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; - }; - - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), - ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) - ); - } - // match types - if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; - } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; - }; - - var output$5 = {}; - - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL - ); - } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; - }; - - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; - - var witnesscommitment = {}; - - var output$3 = {}; - - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer$i.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); - } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$i.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); - } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); - } - output$3.decode = decode; - - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; - - var witnesspubkeyhash = {}; - - var input$3 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; - } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); - } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; - - var witnessscripthash = {}; - - var input$1 = {}; - - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; - if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; - } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; - - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; - } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; - } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; - } - classify$1.witness = classifyWitness; - - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$1; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); - } - } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; - } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; - } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); - } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; - } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; - } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; - } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; - } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$i.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); - } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); - } - build() { - return this.__build(false); - } - buildIncomplete() { - return this.__build(true); - } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), - ); - } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); - } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; - } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; - } - prevOutType = expanded.type; - } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); - } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, - ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; - } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); - } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; - } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); - }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); - } - } - return tx; - } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); - }); - }); - } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; - } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); - }) - ); - } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; - } - return false; - }); - }); - } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; - } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; - } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); - return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, - }; - } - } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); - } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; - } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); - } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); - return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, - }; - } - } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, - }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); - } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); - } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, - ); - } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - } - } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); - } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); - } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, - ); - } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; - } - } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', - ); - } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; - } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', - ); - } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); - } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); - } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, - ); - // updates inline - Object.assign(input, prepared); - } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); - } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); - } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); - } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; - } - - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; - const address = address$1; - src$1.address = address; - const crypto = crypto$1; - var crypto_1 = src$1.crypto = crypto; - const ECPair = ecpair; - src$1.ECPair = ECPair; - const networks = networks$3; - src$1.networks = networks; - const payments = payments$4; - src$1.payments = payments; - const script = script$1; - src$1.script = script; - var block_1 = block; - src$1.Block = block_1.Block; - var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$1.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - - var re$5 = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; - - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; - - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; - - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser$2 = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop$2() {} - - var on = noop$2; - var addListener = noop$2; - var once$2 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; - - function binding(name) { - throw new Error('process.binding is not supported'); - } - - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - - var process = { - nextTick: nextTick, - title: title, - browser: browser$2, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once$2, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - const debug$4 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$4; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; - - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers - }; - - const debug$3 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; - - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); - - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) - } - - debug$3('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); - } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug$3('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } - } - - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; - - var parse_1 = parse$5; - - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; - - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; - - const SemVer$c = semver$1; - - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - - const parse$2 = parse_1; - const eq$1 = eq_1; - - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } - }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; - - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; - - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; - - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1 = prerelease; - - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; - - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1 = compareBuild$2; - - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; - - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; - - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; - - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; - - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; - - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; - - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; - - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; - - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt$2(a, b, loose) - - case '>=': - return gte$1(a, b, loose) - - case '<': - return lt$1(a, b, loose) - - case '<=': - return lte$1(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1 = coerce; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); - } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); - } - } - - return self - } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; - } - - if (prev) { - prev.next = next; - } - - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } - - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; - } - - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; - - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; - - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; - - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; - - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res - }; - - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } - - return acc - }; - - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } - - return acc - }; - - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; - - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr - }; - - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } - - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; - - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this - }; - - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); - - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } - - self.length++; - - return inserted - } - - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; - } - self.length++; - } - - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; - } - - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } - - this.list = list; - this.value = value; - - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } - - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } - } - - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); - - const naiveLength = () => 1; - - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; - - if (!options) - options = {}; - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; - - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA; - trim(this); - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); - } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } - } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); - } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true - } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false - } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) - } - - get (key) { - return get$1(this, key, true) - } - - peek (key) { - return get$1(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null - - del(this, node); - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)); - } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); - } - } - - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); - } - } - return hit.value - } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; - - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; - } - } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); - } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; - } - } - - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; - - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } - } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this - } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } - } - } - } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$2('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } - } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$2 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$2('comp', comp, options); - comp = replaceCarets(comp, options); - debug$2('caret', comp); - comp = replaceTildes(comp, options); - debug$2('tildes', comp); - comp = replaceXRanges(comp, options); - debug$2('xrange', comp); - comp = replaceStars(comp, options); - debug$2('stars', comp); - return comp - }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$2('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; - } - - debug$2('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$2('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$2('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$2('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$2('caret return', ret); - return ret - }) - }; - - const replaceXRanges = (comp, options) => { - debug$2('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') - }; - - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$2('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; - } - - debug$2('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$2('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; - - const replaceGTE0 = (comp, options) => { - debug$2('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$2(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 - } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } - } - - debug$1('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } - - debug$1('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); - } - } - - toString () { - return this.value - } - - test (version) { - debug$1('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) - } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } - } - - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug$1 = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; - - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } - } - }); - return max - }; - var maxSatisfying_1 = maxSatisfying; - - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); - } - } - }); - return min - }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null - }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true - }; - - var outside_1 = outside$2; - - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; - - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; - - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) - }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false - } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; - - var subset_1 = subset; - - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$i.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$i.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer$i.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - var readable = {exports: {}}; - - var stream = require$$0__default$2["default"]; - - function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - var _require$2 = require$$0__default$1["default"], - Buffer$e = _require$2.Buffer; - - var _require2 = require$$1__default["default"], - inspect = _require2.inspect; - - var custom = inspect && inspect.custom || 'inspect'; - - function copyBuffer(src, target, offset) { - Buffer$e.prototype.copy.call(src, target, offset); - } - - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$e.alloc(0); - var ret = Buffer$e.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$e.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread$1({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); - } else { - nextTick(emitCloseNT, _this); - } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); - } else { - nextTick(emitCloseNT, _this); - } - }); - - return this; - } - - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); - } - - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.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(self, err) { - self.emit('error', err); - } - - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); - } - - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - - var errors = {}; - - const codes = {}; - - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; - } - - // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - - errors.codes = codes; - - var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; - - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; - } - - var state = { - getHighWaterMark: getHighWaterMark$2 - }; - - /** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - - var node = require$$1__default["default"].deprecate; - - var _stream_writable = Writable$1; - // there will be only 2 of these for each stream - - - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; - } - /* */ - - /**/ - - - var Duplex$3; - /**/ - - Writable$1.WritableState = WritableState; - /**/ - - var internalUtil = { - deprecate: node - }; - /**/ - - /**/ - - var Stream$1 = stream; - /**/ - - - var Buffer$d = require$$0__default$1["default"].Buffer; - - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$d.from(chunk); - } - - function _isUint8Array$1(obj) { - return Buffer$d.isBuffer(obj) || obj instanceof OurUint8Array$1; - } - - var destroyImpl$1 = destroy_1; - - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; - - var _require$codes$3 = errors.codes, - ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - - inherits$f.exports(Writable$1, Stream$1); - - function nop() {} - - function WritableState(options, stream, isDuplex) { - Duplex$3 = Duplex$3 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; - }; - - (function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. - - - var realHasInstance; - - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$1, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$1) return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; - } - - function Writable$1(options) { - Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$3; - if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream$1.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. - - - Writable$1.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; - - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. - - - function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } - - return true; - } - - Writable$1.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array$1(chunk); - - if (isBuf && !Buffer$d.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; - - Writable$1.prototype.cork = function () { - this._writableState.corked++; - }; - - Writable$1.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - - Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - Object.defineProperty(Writable$1.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$d.from(chunk, encoding); - } - - return chunk; - } - - Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } - } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } - } - - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - - - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it - - - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable$1.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; - - Writable$1.prototype._writev = null; - - Writable$1.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; - }; - - Object.defineProperty(Writable$1.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy$1(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); - } - - function prefinish$1(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish$1(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; - } - - Object.defineProperty(Writable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } - }); - Writable$1.prototype.destroy = destroyImpl$1.destroy; - Writable$1.prototype._undestroy = destroyImpl$1.undestroy; - - Writable$1.prototype._destroy = function (err, cb) { - cb(err); - }; - - /**/ - - var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; - }; - /**/ - - - var _stream_duplex = Duplex$2; - - var Readable$1 = _stream_readable; - - var Writable = _stream_writable; - - inherits$f.exports(Duplex$2, Readable$1); - - { - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; - } - } - - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$1.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } - } - - Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); // the no-half-open enforcer - - function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - nextTick(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - Object.defineProperty(Duplex$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - - var string_decoder = {}; - - /**/ - - var Buffer$c = safeBuffer.exports.Buffer; - /**/ - - var isEncoding = Buffer$c.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$c.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. - string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(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$c.allocUnsafe(nb); - } - - StringDecoder$2.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$2.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.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); - 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) : ''; - } - - var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; - - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; - } - - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; - } - - var endOfStream = eos$1; - - var _Object$setPrototypeO; - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var finished = endOfStream; - - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); - - function createIterResult(value, done) { - return { - value: value, - done: done - }; - } - - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } - } - - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } - - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty$1(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty$1(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; - - var async_iterator = createReadableStreamAsyncIterator$1; - - 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); }); }; } - - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; - - function from$1(Readable, iterable, opts) { - var iterator; - - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); - - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. - - var reading = false; - - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; - - function next() { - return _next2.apply(this, arguments); - } - - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; - - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - - return readable; - } - - var from_1 = from$1; - - var _stream_readable = Readable; - /**/ - - var Duplex$1; - /**/ - - Readable.ReadableState = ReadableState; - /**/ - - EventEmitter__default["default"].EventEmitter; - - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ - - /**/ - - - var Stream = stream; - /**/ - - - var Buffer$b = require$$0__default$1["default"].Buffer; - - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer(chunk) { - return Buffer$b.from(chunk); - } - - function _isUint8Array(obj) { - return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ - - - var debugUtil = require$$1__default["default"]; - - var debug; - - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); - } else { - debug = function debug() {}; - } - /**/ - - - var BufferList = buffer_list; - - var destroyImpl = destroy_1; - - var _require = state, - getHighWaterMark = _require.getHighWaterMark; - - var _require$codes$2 = errors.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - - var StringDecoder$1; - var createReadableStreamAsyncIterator; - var from; - - inherits$f.exports(Readable, Stream); - - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } - - function ReadableState(options, stream, isDuplex) { - Duplex$1 = Duplex$1 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } - - function Readable(options) { - Duplex$1 = Duplex$1 || _stream_duplex; - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$1; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); - } - - Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - - Readable.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - - - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer$b.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() - - - Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$b.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); - } - - function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; - } - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. - - - Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB - - - var MAX_HWM = 0x40000000; - - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; - } // you can override either this method, or the async _read(n) below. - - - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; - }; - - function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - - - function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_, stream); - } - } - - function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - - - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } - } - - function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - - - Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something - - - Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - nextTick(nReadingNextTick, this); - } - } - } - - return res; - }; - - Readable.prototype.addListener = Readable.prototype.on; - - Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } - - return res; - }; - - Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } - - return res; - }; - - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } - } - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - - - Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } - } - - function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - - - Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; - }; - - if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } - - return createReadableStreamAsyncIterator(this); - }; - } - - Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); // exposed for testing purposes only. - - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } - - function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } - - if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = from_1; - } - - return from(Readable, iterable, opts); - }; - } - - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; - } - - var _stream_transform = Transform$3; - - var _require$codes$1 = errors.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - - var Duplex = _stream_duplex; - - inherits$f.exports(Transform$3, Duplex); - - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } - - function Transform$3(options) { - if (!(this instanceof Transform$3)) return new Transform$3(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); - } - - function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } - } - - Transform$3.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - - - Transform$3.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); - }; - - Transform$3.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - - - Transform$3.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - Transform$3.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; - - function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } - - var _stream_passthrough = PassThrough; - - var Transform$2 = _stream_transform; - - inherits$f.exports(PassThrough, Transform$2); - - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$2.call(this, options); - } - - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - var eos; - - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } - - var _require$codes = errors.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } - - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; - } - - function call(fn) { - fn(); - } - - function pipe(from, to) { - return from.pipe(to); - } - - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); - } - - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } - - var pipeline_1 = pipeline; - - (function (module, exports) { - var Stream = require$$0__default$2["default"]; - { - exports = module.exports = _stream_readable; - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - } - }(readable, readable.exports)); - - var Buffer$a = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$a = inherits$f.exports; - - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$a.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } - - function HashBase$2 (blockSize) { - Transform$1.call(this); - - this._block = Buffer$a.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; - - this._finalized = false; - } - - inherits$a(HashBase$2, Transform$1); - - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } - - callback(error); - }; - - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$a.isBuffer(data)) data = Buffer$a.from(data, encoding); - - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } - - return this - }; - - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; - - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); - - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; - - return digest - }; - - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; - - var hashBase = HashBase$2; - - var Buffer$9 = require$$0__default$1["default"].Buffer; - var inherits$9 = inherits$f.exports; - var HashBase$1 = hashBase; - - var ARRAY16$1 = new Array(16); - - var zl = [ - 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 zr = [ - 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 sl = [ - 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 sr = [ - 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 - ]; - - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - - function RIPEMD160$1 () { - HashBase$1.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } - - inherits$9(RIPEMD160$1, HashBase$1); - - RIPEMD160$1.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; - - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; - - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } - - al = el; - el = dl; - dl = rotl$1(cl, 10); - cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; - } - - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$9.alloc ? Buffer$9.alloc(20) : new Buffer$9(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer - }; - - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } - - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } - - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } - - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } - - var ripemd160$1 = RIPEMD160$1; - - var sha_js = {exports: {}}; - - var Buffer$8 = safeBuffer.exports.Buffer; - - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$8.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } - - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$8.from(data, enc); - } - - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); - } - } - - this._len += length; - return this - }; - - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); - - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } - - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; - - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } - - this._update(this._block); - var hash = this._hash(); - - return enc ? hash.toString(enc) : hash - }; - - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; - - var hash = Hash$7; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - - var inherits$8 = inherits$f.exports; - var Hash$6 = hash; - var Buffer$7 = safeBuffer.exports.Buffer; - - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$5 = new Array(80); - - function Sha () { - this.init(); - this._w = W$5; - - Hash$6.call(this, 64, 56); - } - - inherits$8(Sha, Hash$6); - - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } - - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha$2 = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - - var inherits$7 = inherits$f.exports; - var Hash$5 = hash; - var Buffer$6 = safeBuffer.exports.Buffer; - - var K$2 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$4 = new Array(80); - - function Sha1 () { - this.init(); - this._w = W$4; - - Hash$5.call(this, 64, 56); - } - - inherits$7(Sha1, Hash$5); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this - }; - - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } - - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } - - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } - - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - - Sha1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; - - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha1 = Sha1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - var inherits$6 = inherits$f.exports; - var Hash$4 = hash; - var Buffer$5 = safeBuffer.exports.Buffer; - - var K$1 = [ - 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 W$3 = new Array(64); - - function Sha256$1 () { - this.init(); - - this._w = W$3; // new Array(64) - - Hash$4.call(this, 64, 56); - } - - inherits$6(Sha256$1, Hash$4); - - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this - }; - - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } - - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } - - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } - - Sha256$1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256$1.prototype._hash = function () { - var H = Buffer$5.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); - - return H - }; - - var sha256$1 = Sha256$1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - var inherits$5 = inherits$f.exports; - var Sha256 = sha256$1; - var Hash$3 = hash; - var Buffer$4 = safeBuffer.exports.Buffer; - - var W$2 = new Array(64); - - function Sha224 () { - this.init(); - - this._w = W$2; // new Array(64) - - Hash$3.call(this, 64, 56); - } - - inherits$5(Sha224, Sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this - }; - - Sha224.prototype._hash = function () { - var H = Buffer$4.allocUnsafe(28); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - - return H - }; - - var sha224 = Sha224; - - var inherits$4 = inherits$f.exports; - var Hash$2 = hash; - var Buffer$3 = safeBuffer.exports.Buffer; - - 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 W$1 = new Array(160); - - function Sha512 () { - this.init(); - this._w = W$1; - - Hash$2.call(this, 128, 112); - } - - inherits$4(Sha512, Hash$2); - - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; - - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - - return this - }; - - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } - - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } - - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } - - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } - - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } - - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } - - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } - - Sha512.prototype._update = function (M) { - var W = this._w; - - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; - - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - - W[i] = Wih; - W[i + 1] = Wil; - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); - - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j]; - var Kil = K[j + 1]; - - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function () { - var H = Buffer$3.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; - - var sha512 = Sha512; - - var inherits$3 = inherits$f.exports; - var SHA512 = sha512; - var Hash$1 = hash; - var Buffer$2 = safeBuffer.exports.Buffer; - - var W = new Array(160); - - function Sha384 () { - this.init(); - this._w = W; - - Hash$1.call(this, 128, 112); - } - - inherits$3(Sha384, SHA512); - - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; - - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - - return this - }; - - Sha384.prototype._hash = function () { - var H = Buffer$2.allocUnsafe(48); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; - - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); - - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() - }; - - exports$1.sha = sha$2; - exports$1.sha1 = sha1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$1; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; - - var sha$1 = sha_js.exports; - - function hashPublicKey(buffer) { - return new ripemd160$1().update(sha$1("sha256").update(buffer).digest()).digest(); - } - - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); - }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); - }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); - }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; - }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; - }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$i.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; - }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); - }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; - }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$i.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$i.concat([h, h, x])); - }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$i.concat([ - Buffer$i.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$i.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$i.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; - }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); - } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; - }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$i.concat([Buffer$i.from("0014", "hex"), pubkeyHash]); - }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$i.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; - }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; - }; - return p2wpkh; - }(SingleKeyAccount)); - - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; - }; - Merkle.prototype.size = function () { - return this.leaves.length; - }; - Merkle.prototype.getLeaves = function () { - return this.leaves; - }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; - }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); - }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$i.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; - }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$i.concat([Buffer$i.from([1]), left, right])); - }; - return Merkle; - }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$i.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$i.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; - } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; - } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); - } - } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; - } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; - } - - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md - */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; - } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$i.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$i.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; - } - - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$i.from([0, 1])); - } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$i.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } - } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); - } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); - } - - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); - }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; - } - return NoSuchEntry; - }(Error)); - /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. - * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. - */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; - } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$i.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); - } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; - } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; - } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; - } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; - }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$i.from(k.substring(2), "hex")); - } - }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$i.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$i.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); - }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); - }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer$i.from(value); - } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; - } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$i.from(k, "hex")), value); - keyPair.serialize(buf); - } - buf.writeUInt8(0); - } - function b() { - return Buffer$i.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$i.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer$i.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); - } - - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); - } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); - } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$i.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); - } - - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$i.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer$i.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer$i.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$i.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$i.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$i.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$i.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$i.concat([ - inputBuffer, - input.prevout, - Buffer$i.from([0x00]), - input.sequence, - ]) - : Buffer$i.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$i.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$i.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$i.alloc(0), - transaction.extraData || Buffer$i.alloc(0), - ]); - } - return Buffer$i.concat([ - transaction.version, - timestamp ? timestamp : Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), - useWitness ? Buffer$i.from("0001", "hex") : Buffer$i.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); - } - - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver.major(appAndVersion.version) >= 2); - } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$i.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$i.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$i.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$i.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$i.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); - }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); - } - - var id$2 = 0; - var subscribers$1 = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log$1 = function (type, message, data) { - var obj = { - type: type, - id: String(++id$2), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch$1(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen$1 = function (cb) { - subscribers$1.push(cb); - return function () { - var i = subscribers$1.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; - subscribers$1.pop(); - } - }; - }; - function dispatch$1(log) { - for (var i = 0; i < subscribers$1.length; i++) { - try { - subscribers$1[i](log); - } - catch (e) { - console.error(e); - } - } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen$1; - } - - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log$1, - listen: listen$1 - }); - - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$4.apply(this, arguments); - }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 - }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); - } - - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; - } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } - }; - - var invariant_1 = invariant; - - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$7 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$i.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$i.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$i.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$i.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$i.concat([ - transaction.version, - transaction.timestamp || Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$i.compare(version, Buffer$i.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$i.from([0x00]) - : Buffer$i.alloc(0); - data = Buffer$i.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$i.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$i.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$i.concat([ - output.amount, - isDecred ? Buffer$i.from([0x00, 0x00]) : Buffer$i.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$i.concat(endData); - extraPart = isDecred - ? data - : Buffer$i.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$i.concat([locktime, extraPart || Buffer$i.alloc(0)]))]; - case 20: - res = _c.sent(); - invariant_1(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$6 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$i.concat([ - transaction.version, - transaction.timestamp || Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$i.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$i.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$i.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$i.from([0x00]); - } - } - data = Buffer$i.concat([ - prefix, - inputValue, - isDecred ? Buffer$i.from([0x00]) : Buffer$i.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$i.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); - } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); - } - var hash = sha$1("sha256") - .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$i.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); - } - hash = Buffer$i.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$i.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$i.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$i.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$i.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$i.from([0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([sigHashType]), - ]) - : Buffer$i.concat([ - pathsBuffer, - Buffer$i.from([0x00]), - lockTimeBuffer, - Buffer$i.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$i.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - invariant_1(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } - - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$i.alloc(0); - nullPrevout = Buffer$i.alloc(0); - defaultVersion = Buffer$i.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$i.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$i.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$i.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$i.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$i.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$i.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$i.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$i.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$i.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$i.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$i.concat([ - Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$i.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$i.concat([ - Buffer$i.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer$i.alloc(1); - keySize = Buffer$i.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$i.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$i.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$i.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$i.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$i.concat([ - Buffer$i.from("02", "hex"), - Buffer$i.from([signatures[i].length]), - signatures[i], - Buffer$i.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$i.concat([witness, tmpScriptData]); - } - result = Buffer$i.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$i.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$i.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$i.alloc(0), - targetTransaction.extraData || Buffer$i.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$i.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$i.concat([ - decredWitness_1, - Buffer$i.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([0xff, 0xff, 0xff, 0xff]), - Buffer$i.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$i.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } - }); - }); - } - - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$i.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$i.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$i.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$i.alloc(0); - nullPrevout = Buffer$i.alloc(0); - defaultVersion = Buffer$i.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$i.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$i.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$i.from(trustedInput, "hex") - : Buffer$i.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$i.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$i.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$i.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$i.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$i.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); - } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); - } - return signP2SHTransaction(this.transport, arg); - }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$i.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$i.concat([ - Buffer$i.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); - }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$i.concat([ - asBufferUInt32BE(version), - Buffer$i.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$i.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$1("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$1().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); - } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$i.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; - } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$i.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { - } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; - } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$i.from(request.subarray(1))); - this.progressCallback(); - return Buffer$i.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$i.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$i.from([known_preimage[i]])); - } - } - return Buffer$i.concat([ - preimage_len_varint, - Buffer$i.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; - } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$i.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$i.from([proof.length]), - Buffer$i.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; - } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$i.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$i.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$i.concat([Buffer$i.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; - } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); - } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); - } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$i.concat(__spreadArray$1([ - Buffer$i.from([n_returned_elements]), - Buffer$i.from([element_len]) - ], __read$1(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } - } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$i.concat([Buffer$i.from([0]), el]); - this.addKnownPreimage(preimage); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); - } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); - } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); - - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$i.concat([ - Buffer$i.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$i.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$i.concat([ - Buffer$i.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$i.alloc(32, 0), - Buffer$i.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$i.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$i.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$i.from([]))]; - }); - }); - }; - return AppClient; - }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$i.alloc(0); - var nExpiryHeight = Buffer$i.alloc(0); - var nVersionGroupId = Buffer$i.alloc(0); - var extraData = Buffer$i.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$i.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$i.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$i.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$i.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$i.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$i.alloc(0); - var tree = Buffer$i.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); - } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); - } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } - else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } - } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; - } - - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@backpacker69/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); - } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); - }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; - } - return false; - } - - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses$1 = {}; - var deserializers$1 = {}; - var addCustomErrorDeserializer$1 = function (name, deserializer) { - deserializers$1[name] = deserializer; - }; - var createCustomErrorClass$1 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$1[name] = C; - return C; - }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers$1[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass$1(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); - var AmountRequired = createCustomErrorClass$1("AmountRequired"); - var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass$1("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass$1("NetworkDown"); - var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); - var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass$1("FeeRequired"); - var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); - var SyncError = createCustomErrorClass$1("SyncError"); - var PairingFailed = createCustomErrorClass$1("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); - var DBNotReset = createCustomErrorClass$1("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$1(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); - var StatusCodes$1 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$1(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$1(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$1(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass$1, - addCustomErrorDeserializer: addCustomErrorDeserializer$1, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition$1, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError$1, - StatusCodes: StatusCodes$1, - getAltStatusMessage: getAltStatusMessage$1, - TransportStatusError: TransportStatusError$1 - }); - - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport$1 = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter__default["default"](); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$i.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$i.concat([ - Buffer$i.from([cla, ins, p1, p2]), - Buffer$i.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError$1(sw); - } - return [2 /*return*/, response]; - } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; - } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; - } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); - - var hidFraming$1 = {}; - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$i.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$i.alloc(0), - dataLength: 0, - sequence: 0 - }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$i.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$i.concat([ - data, - Buffer$i.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$i.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$i.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$i.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - exports["default"] = createHIDframing; - - }(hidFraming$1)); - - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); - - var __assign = (undefined && undefined.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - var _a; - var DeviceModelId; - (function (DeviceModelId) { - DeviceModelId["blue"] = "blue"; - DeviceModelId["nanoS"] = "nanoS"; - DeviceModelId["nanoSP"] = "nanoSP"; - DeviceModelId["nanoX"] = "nanoX"; - })(DeviceModelId || (DeviceModelId = {})); - var devices = (_a = {}, - _a[DeviceModelId.blue] = { - id: DeviceModelId.blue, - productName: "Ledger Blue", - productIdMM: 0x00, - legacyUsbProductId: 0x0000, - usbOnly: true, - memorySize: 480 * 1024, - masks: [0x31000000, 0x31010000], - getBlockSize: function (_firwareVersion) { return 4 * 1024; } - }, - _a[DeviceModelId.nanoS] = { - id: DeviceModelId.nanoS, - productName: "Ledger Nano S", - productIdMM: 0x10, - legacyUsbProductId: 0x0001, - usbOnly: true, - memorySize: 320 * 1024, - masks: [0x31100000], - getBlockSize: function (firmwareVersion) { - var _a; - return semver.lt((_a = semver.coerce(firmwareVersion)) !== null && _a !== void 0 ? _a : "", "2.0.0") - ? 4 * 1024 - : 2 * 1024; - } - }, - _a[DeviceModelId.nanoSP] = { - id: DeviceModelId.nanoSP, - productName: "Ledger Nano SP", - productIdMM: 0x50, - legacyUsbProductId: 0x0005, - usbOnly: true, - memorySize: 1533 * 1024, - masks: [0x33100000], - getBlockSize: function (_firmwareVersion) { return 32; } - }, - _a[DeviceModelId.nanoX] = { - id: DeviceModelId.nanoX, - productName: "Ledger Nano X", - productIdMM: 0x40, - legacyUsbProductId: 0x0004, - usbOnly: false, - memorySize: 2 * 1024 * 1024, - masks: [0x33000000], - getBlockSize: function (_firwareVersion) { return 4 * 1024; }, - bluetoothSpec: [ - { - // this is the legacy one (prototype version). we will eventually drop it. - serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", - notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", - writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66", - writeCmdUuid: "d973f2e3-b19e-11e2-9e96-0800200c9a66" - }, - { - serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", - notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", - writeUuid: "13d63400-2c97-0004-0002-4c6564676572", - writeCmdUuid: "13d63400-2c97-0004-0003-4c6564676572" - }, - ] - }, - _a); - ({ - Blue: DeviceModelId.blue, - "Nano S": DeviceModelId.nanoS, - "Nano X": DeviceModelId.nanoX - }); - var devicesList = Object.values(devices); - /** - * - */ - var ledgerUSBVendorId = 0x2c97; - /** - * - */ - var identifyUSBProductId = function (usbProductId) { - var legacy = devicesList.find(function (d) { return d.legacyUsbProductId === usbProductId; }); - if (legacy) - return legacy; - var mm = usbProductId >> 8; - var deviceModel = devicesList.find(function (d) { return d.productIdMM === mm; }); - return deviceModel; - }; - var bluetoothServices = []; - var serviceUuidToInfos = {}; - for (var id$1 in devices) { - var deviceModel = devices[id$1]; - var bluetoothSpec = deviceModel.bluetoothSpec; - if (bluetoothSpec) { - for (var i = 0; i < bluetoothSpec.length; i++) { - var spec = bluetoothSpec[i]; - bluetoothServices.push(spec.serviceUuid); - serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = __assign({ deviceModel: deviceModel }, spec); - } - } - } - - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var ledgerDevices = [ - { - vendorId: ledgerUSBVendorId - }, - ]; - function requestLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { - var device; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, navigator.usb.requestDevice({ - filters: ledgerDevices - })]; - case 1: - device = _a.sent(); - return [2 /*return*/, device]; - } - }); - }); - } - function getLedgerDevices() { - return __awaiter$1(this, void 0, void 0, function () { - var devices; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, navigator.usb.getDevices()]; - case 1: - devices = _a.sent(); - return [2 /*return*/, devices.filter(function (d) { return d.vendorId === ledgerUSBVendorId; })]; - } - }); - }); - } - function getFirstLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { - var existingDevices; - return __generator$1(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getLedgerDevices()]; - case 1: - existingDevices = _a.sent(); - if (existingDevices.length > 0) - return [2 /*return*/, existingDevices[0]]; - return [2 /*return*/, requestLedgerDevice()]; - } - }); - }); - } - var isSupported$1 = function () { - return Promise.resolve(!!navigator && - !!navigator.usb && - typeof navigator.usb.getDevices === "function"); - }; - - var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var configurationValue = 1; - var endpointNumber = 3; - /** - * WebUSB Transport implementation - * @example - * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; - * ... - * TransportWebUSB.create().then(transport => ...) - */ - var TransportWebUSB = /** @class */ (function (_super) { - __extends(TransportWebUSB, _super); - function TransportWebUSB(device, interfaceNumber) { - var _this = _super.call(this) || this; - _this.channel = Math.floor(Math.random() * 0xffff); - _this.packetSize = 64; - _this._disconnectEmitted = false; - _this._emitDisconnect = function (e) { - if (_this._disconnectEmitted) - return; - _this._disconnectEmitted = true; - _this.emit("disconnect", e); - }; - _this.device = device; - _this.interfaceNumber = interfaceNumber; - _this.deviceModel = identifyUSBProductId(device.productId); - return _this; - } - /** - * Similar to create() except it will always display the device permission (even if some devices are already accepted). - */ - TransportWebUSB.request = function () { - return __awaiter(this, void 0, void 0, function () { - var device; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, requestLedgerDevice()]; - case 1: - device = _a.sent(); - return [2 /*return*/, TransportWebUSB.open(device)]; - } - }); - }); - }; - /** - * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). - */ - TransportWebUSB.openConnected = function () { - return __awaiter(this, void 0, void 0, function () { - var devices; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getLedgerDevices()]; - case 1: - devices = _a.sent(); - if (devices.length === 0) - return [2 /*return*/, null]; - return [2 /*return*/, TransportWebUSB.open(devices[0])]; - } - }); - }); - }; - /** - * Create a Ledger transport with a USBDevice - */ - TransportWebUSB.open = function (device) { - return __awaiter(this, void 0, void 0, function () { - var iface, interfaceNumber, e_1, transport, onDisconnect; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, device.open()]; - case 1: - _a.sent(); - if (!(device.configuration === null)) return [3 /*break*/, 3]; - return [4 /*yield*/, device.selectConfiguration(configurationValue)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [4 /*yield*/, gracefullyResetDevice(device)]; - case 4: - _a.sent(); - iface = device.configurations[0].interfaces.find(function (_a) { - var alternates = _a.alternates; - return alternates.some(function (a) { return a.interfaceClass === 255; }); - }); - if (!iface) { - throw new TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); - } - interfaceNumber = iface.interfaceNumber; - _a.label = 5; - case 5: - _a.trys.push([5, 7, , 9]); - return [4 /*yield*/, device.claimInterface(interfaceNumber)]; - case 6: - _a.sent(); - return [3 /*break*/, 9]; - case 7: - e_1 = _a.sent(); - return [4 /*yield*/, device.close()]; - case 8: - _a.sent(); - throw new TransportInterfaceNotAvailable(e_1.message); - case 9: - transport = new TransportWebUSB(device, interfaceNumber); - onDisconnect = function (e) { - if (device === e.device) { - // $FlowFixMe - navigator.usb.removeEventListener("disconnect", onDisconnect); - transport._emitDisconnect(new DisconnectedDevice()); - } - }; - // $FlowFixMe - navigator.usb.addEventListener("disconnect", onDisconnect); - return [2 /*return*/, transport]; - } - }); - }); - }; - /** - * Release the transport device - */ - TransportWebUSB.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeBusyPromise]; - case 1: - _a.sent(); - return [4 /*yield*/, this.device.releaseInterface(this.interfaceNumber)]; - case 2: - _a.sent(); - return [4 /*yield*/, gracefullyResetDevice(this.device)]; - case 3: - _a.sent(); - return [4 /*yield*/, this.device.close()]; - case 4: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - TransportWebUSB.prototype.exchange = function (apdu) { - return __awaiter(this, void 0, void 0, function () { - var b; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { - var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = this, channel = _a.channel, packetSize = _a.packetSize; - log$1("apdu", "=> " + apdu.toString("hex")); - framing = hidFraming(channel, packetSize); - blocks = framing.makeBlocks(apdu); - i = 0; - _b.label = 1; - case 1: - if (!(i < blocks.length)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.device.transferOut(endpointNumber, blocks[i])]; - case 2: - _b.sent(); - _b.label = 3; - case 3: - i++; - return [3 /*break*/, 1]; - case 4: - if (!!(result = framing.getReducedResult(acc))) return [3 /*break*/, 6]; - return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; - case 5: - r = _b.sent(); - buffer = Buffer$i.from(r.data.buffer); - acc = framing.reduceResponse(acc, buffer); - return [3 /*break*/, 4]; - case 6: - log$1("apdu", "<= " + result.toString("hex")); - return [2 /*return*/, result]; - } - }); - }); })["catch"](function (e) { - if (e && e.message && e.message.includes("disconnected")) { - _this._emitDisconnect(e); - throw new DisconnectedDeviceDuringOperation(e.message); - } - throw e; - })]; - case 1: - b = _a.sent(); - return [2 /*return*/, b]; - } - }); - }); - }; - TransportWebUSB.prototype.setScrambleKey = function () { }; - /** - * Check if WebUSB transport is supported. - */ - TransportWebUSB.isSupported = isSupported$1; - /** - * List the WebUSB devices that was previously authorized by the user. - */ - TransportWebUSB.list = getLedgerDevices; - /** - * Actively listen to WebUSB devices and emit ONE device - * that was either accepted before, if not it will trigger the native permission UI. - * - * Important: it must be called in the context of a UI click! - */ - TransportWebUSB.listen = function (observer) { - var unsubscribed = false; - getFirstLedgerDevice().then(function (device) { - if (!unsubscribed) { - var deviceModel = identifyUSBProductId(device.productId); - observer.next({ - type: "add", - descriptor: device, - deviceModel: deviceModel - }); - observer.complete(); - } - }, function (error) { - if (window.DOMException && - error instanceof window.DOMException && - error.code === 18) { - observer.error(new TransportWebUSBGestureRequired(error.message)); - } - else { - observer.error(new TransportOpenUserCancelled(error.message)); - } - }); - function unsubscribe() { - unsubscribed = true; - } - return { - unsubscribe: unsubscribe - }; - }; - return TransportWebUSB; - }(Transport$1)); - function gracefullyResetDevice(device) { - return __awaiter(this, void 0, void 0, function () { - var err_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - return [4 /*yield*/, device.reset()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - err_1 = _a.sent(); - console.warn(err_1); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': TransportWebUSB - }); - - /** Namespace for the U2F api. - * @type {Object} - */ - var u2f = u2f || {}; - - var googleU2fApi = u2f; // Adaptation for u2f-api package - - /** - * The U2F extension id - * @type {string} - * @const - */ - u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; - - /** - * Message types for messsages to/from the extension - * @const - * @enum {string} - */ - u2f.MessageTypes = { - 'U2F_REGISTER_REQUEST': 'u2f_register_request', - 'U2F_SIGN_REQUEST': 'u2f_sign_request', - 'U2F_REGISTER_RESPONSE': 'u2f_register_response', - 'U2F_SIGN_RESPONSE': 'u2f_sign_response' - }; - - /** - * Response status codes - * @const - * @enum {number} - */ - u2f.ErrorCodes = { - 'OK': 0, - 'OTHER_ERROR': 1, - 'BAD_REQUEST': 2, - 'CONFIGURATION_UNSUPPORTED': 3, - 'DEVICE_INELIGIBLE': 4, - 'TIMEOUT': 5 - }; - - /** - * A message type for registration requests - * @typedef {{ - * type: u2f.MessageTypes, - * signRequests: Array., - * registerRequests: ?Array., - * timeoutSeconds: ?number, - * requestId: ?number - * }} - */ - u2f.Request; - - /** - * A message for registration responses - * @typedef {{ - * type: u2f.MessageTypes, - * responseData: (u2f.Error | u2f.RegisterResponse | u2f.SignResponse), - * requestId: ?number - * }} - */ - u2f.Response; - - /** - * An error object for responses - * @typedef {{ - * errorCode: u2f.ErrorCodes, - * errorMessage: ?string - * }} - */ - u2f.Error; - - /** - * Data object for a single sign request. - * @typedef {{ - * version: string, - * challenge: string, - * keyHandle: string, - * appId: string - * }} - */ - u2f.SignRequest; - - /** - * Data object for a sign response. - * @typedef {{ - * keyHandle: string, - * signatureData: string, - * clientData: string - * }} - */ - u2f.SignResponse; - - /** - * Data object for a registration request. - * @typedef {{ - * version: string, - * challenge: string, - * appId: string - * }} - */ - u2f.RegisterRequest; - - /** - * Data object for a registration response. - * @typedef {{ - * registrationData: string, - * clientData: string - * }} - */ - u2f.RegisterResponse; - - - // Low level MessagePort API support - - /** - * Call MessagePort disconnect - */ - u2f.disconnect = function() { - if (u2f.port_ && u2f.port_.port_) { - u2f.port_.port_.disconnect(); - u2f.port_ = null; - } - }; - - /** - * Sets up a MessagePort to the U2F extension using the - * available mechanisms. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - */ - u2f.getMessagePort = function(callback) { - if (typeof chrome != 'undefined' && chrome.runtime) { - // The actual message here does not matter, but we need to get a reply - // for the callback to run. Thus, send an empty signature request - // in order to get a failure response. - var msg = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: [] - }; - chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { - if (!chrome.runtime.lastError) { - // We are on a whitelisted origin and can talk directly - // with the extension. - u2f.getChromeRuntimePort_(callback); - } else { - // chrome.runtime was available, but we couldn't message - // the extension directly, use iframe - u2f.getIframePort_(callback); - } - }); - } else { - // chrome.runtime was not available at all, which is normal - // when this origin doesn't have access to any extensions. - u2f.getIframePort_(callback); - } - }; - - /** - * Connects directly to the extension via chrome.runtime.connect - * @param {function(u2f.WrappedChromeRuntimePort_)} callback - * @private - */ - u2f.getChromeRuntimePort_ = function(callback) { - var port = chrome.runtime.connect(u2f.EXTENSION_ID, - {'includeTlsChannelId': true}); - setTimeout(function() { - callback(null, new u2f.WrappedChromeRuntimePort_(port)); - }, 0); - }; - - /** - * A wrapper for chrome.runtime.Port that is compatible with MessagePort. - * @param {Port} port - * @constructor - * @private - */ - u2f.WrappedChromeRuntimePort_ = function(port) { - this.port_ = port; - }; - - /** - * Posts a message on the underlying channel. - * @param {Object} message - */ - u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { - this.port_.postMessage(message); - }; - - /** - * Emulates the HTML 5 addEventListener interface. Works only for the - * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. - * @param {string} eventName - * @param {function({data: Object})} handler - */ - u2f.WrappedChromeRuntimePort_.prototype.addEventListener = - function(eventName, handler) { - var name = eventName.toLowerCase(); - if (name == 'message' || name == 'onmessage') { - this.port_.onMessage.addListener(function(message) { - // Emulate a minimal MessageEvent object - handler({'data': message}); - }); - } else { - console.error('WrappedChromeRuntimePort only supports onMessage'); - } - }; - - /** - * Sets up an embedded trampoline iframe, sourced from the extension. - * @param {function(MessagePort)} callback - * @private - */ - u2f.getIframePort_ = function(callback) { - // Create the iframe - var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; - var iframe = document.createElement('iframe'); - iframe.src = iframeOrigin + '/u2f-comms.html'; - iframe.setAttribute('style', 'display:none'); - document.body.appendChild(iframe); - - var hasCalledBack = false; - - var channel = new MessageChannel(); - var ready = function(message) { - if (message.data == 'ready') { - channel.port1.removeEventListener('message', ready); - if (!hasCalledBack) - { - hasCalledBack = true; - callback(null, channel.port1); - } - } else { - console.error('First event on iframe port was not "ready"'); - } - }; - channel.port1.addEventListener('message', ready); - channel.port1.start(); - - iframe.addEventListener('load', function() { - // Deliver the port to the iframe and initialize - iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); - }); - - // Give this 200ms to initialize, after that, we treat this method as failed - setTimeout(function() { - if (!hasCalledBack) - { - hasCalledBack = true; - callback(new Error("IFrame extension not supported")); - } - }, 200); - }; - - - // High-level JS API - - /** - * Default extension response timeout in seconds. - * @const - */ - u2f.EXTENSION_TIMEOUT_SEC = 30; - - /** - * A singleton instance for a MessagePort to the extension. - * @type {MessagePort|u2f.WrappedChromeRuntimePort_} - * @private - */ - u2f.port_ = null; - - /** - * Callbacks waiting for a port - * @type {Array.} - * @private - */ - u2f.waitingForPort_ = []; - - /** - * A counter for requestIds. - * @type {number} - * @private - */ - u2f.reqCounter_ = 0; - - /** - * A map from requestIds to client callbacks - * @type {Object.} - * @private - */ - u2f.callbackMap_ = {}; - - /** - * Creates or retrieves the MessagePort singleton to use. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - * @private - */ - u2f.getPortSingleton_ = function(callback) { - if (u2f.port_) { - callback(null, u2f.port_); - } else { - if (u2f.waitingForPort_.length == 0) { - u2f.getMessagePort(function(err, port) { - if (!err) { - u2f.port_ = port; - u2f.port_.addEventListener('message', - /** @type {function(Event)} */ (u2f.responseHandler_)); - } - - // Careful, here be async callbacks. Maybe. - while (u2f.waitingForPort_.length) - u2f.waitingForPort_.shift()(err, port); - }); - } - u2f.waitingForPort_.push(callback); - } - }; - - /** - * Handles response messages from the extension. - * @param {MessageEvent.} message - * @private - */ - u2f.responseHandler_ = function(message) { - var response = message.data; - var reqId = response['requestId']; - if (!reqId || !u2f.callbackMap_[reqId]) { - console.error('Unknown or missing requestId in response.'); - return; - } - var cb = u2f.callbackMap_[reqId]; - delete u2f.callbackMap_[reqId]; - cb(null, response['responseData']); - }; - - /** - * Calls the callback with true or false as first and only argument - * @param {Function} callback - */ - u2f.isSupported = function(callback) { - u2f.getPortSingleton_(function(err, port) { - callback(!err); - }); - }; - - /** - * Dispatches an array of sign requests to available U2F tokens. - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.SignResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: signRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - /** - * Dispatches register requests to available U2F tokens. An array of sign - * requests identifies already registered tokens. - * @param {Array.} registerRequests - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.RegisterResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.register = function(registerRequests, signRequests, - callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_REGISTER_REQUEST, - signRequests: signRequests, - registerRequests: registerRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - var u2fApi$1 = API; - - var chromeApi = googleU2fApi; - - // Feature detection (yes really) - var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; - var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) - && !navigator.userAgent.match( /Chrome\// ); - var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); - - var _backend = null; - function getBackend( Promise ) - { - if ( !_backend ) - _backend = new Promise( function( resolve, reject ) - { - function notSupported( ) - { - // Note; {native: true} means *not* using Google's hack - resolve( { u2f: null, native: true } ); - } - - if ( !isBrowser ) - return notSupported( ); - - if ( isSafari ) - // Safari doesn't support U2F, and the Safari-FIDO-U2F - // extension lacks full support (Multi-facet apps), so we - // block it until proper support. - return notSupported( ); - - var hasNativeSupport = - ( typeof window.u2f !== 'undefined' ) && - ( typeof window.u2f.sign === 'function' ); - - if ( hasNativeSupport ) - resolve( { u2f: window.u2f, native: true } ); - - if ( isEDGE ) - // We don't want to check for Google's extension hack on EDGE - // as it'll cause trouble (popups, etc) - return notSupported( ); - - if ( location.protocol === 'http:' ) - // U2F isn't supported over http, only https - return notSupported( ); - - if ( typeof MessageChannel === 'undefined' ) - // Unsupported browser, the chrome hack would throw - return notSupported( ); - - // Test for google extension support - chromeApi.isSupported( function( ok ) - { - if ( ok ) - resolve( { u2f: chromeApi, native: false } ); - else - notSupported( ); - } ); - } ); - - return _backend; - } - - function API( Promise ) - { - return { - isSupported : isSupported.bind( Promise ), - ensureSupport : ensureSupport.bind( Promise ), - register : register.bind( Promise ), - sign : sign.bind( Promise ), - ErrorCodes : API.ErrorCodes, - ErrorNames : API.ErrorNames - }; - } - - API.ErrorCodes = { - CANCELLED: -1, - OK: 0, - OTHER_ERROR: 1, - BAD_REQUEST: 2, - CONFIGURATION_UNSUPPORTED: 3, - DEVICE_INELIGIBLE: 4, - TIMEOUT: 5 - }; - API.ErrorNames = { - "-1": "CANCELLED", - "0": "OK", - "1": "OTHER_ERROR", - "2": "BAD_REQUEST", - "3": "CONFIGURATION_UNSUPPORTED", - "4": "DEVICE_INELIGIBLE", - "5": "TIMEOUT" - }; - - function makeError( msg, err ) - { - var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR - var type = API.ErrorNames[ '' + code ]; - var error = new Error( msg ); - error.metaData = { - type: type, - code: code - }; - return error; - } - - function deferPromise( Promise, promise ) - { - var ret = { }; - ret.promise = new Promise( function( resolve, reject ) { - ret.resolve = resolve; - ret.reject = reject; - promise.then( resolve, reject ); - } ); - /** - * Reject request promise and disconnect port if 'disconnect' flag is true - * @param {string} msg - * @param {boolean} disconnect - */ - ret.promise.cancel = function( msg, disconnect ) - { - getBackend( Promise ) - .then( function( backend ) - { - if ( disconnect && !backend.native ) - backend.u2f.disconnect( ); - - ret.reject( makeError( msg, { errorCode: -1 } ) ); - } ); - }; - return ret; - } - - function isSupported( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( function( backend ) - { - return !!backend.u2f; - } ); - } - - function _ensureSupport( backend ) - { - if ( !backend.u2f ) - { - if ( location.protocol === 'http:' ) - throw new Error( "U2F isn't supported over http, only https" ); - throw new Error( "U2F not supported" ); - } - } - - function ensureSupport( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( _ensureSupport ); - } - - function register( registerRequests, signRequests /* = null */, timeout ) - { - var Promise = this; - - if ( !Array.isArray( registerRequests ) ) - registerRequests = [ registerRequests ]; - - if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) - { - timeout = signRequests; - signRequests = null; - } - - if ( !signRequests ) - signRequests = [ ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = registerRequests[ 0 ].appId; - - u2f.register( - appId, registerRequests, signRequests, cbNative, timeout ); - } - else - { - u2f.register( - registerRequests, signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function sign( signRequests, timeout ) - { - var Promise = this; - - if ( !Array.isArray( signRequests ) ) - signRequests = [ signRequests ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = signRequests[ 0 ].appId; - var challenge = signRequests[ 0 ].challenge; - - u2f.sign( appId, challenge, signRequests, cbNative, timeout ); - } - else - { - u2f.sign( signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function makeDefault( func ) - { - API[ func ] = function( ) - { - if ( !commonjsGlobal.Promise ) - // This is very unlikely to ever happen, since browsers - // supporting U2F will most likely support Promises. - throw new Error( "The platform doesn't natively support promises" ); - - var args = [ ].slice.call( arguments ); - return API( commonjsGlobal.Promise )[ func ].apply( null, args ); - }; - } - - // Provide default functions using the built-in Promise if available. - makeDefault( 'isSupported' ); - makeDefault( 'ensureSupport' ); - makeDefault( 'register' ); - makeDefault( 'sign' ); - - var u2fApi = u2fApi$1; - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; - }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; - }; - - createCustomErrorClass("AccountNameRequired"); - createCustomErrorClass("AccountNotSupported"); - createCustomErrorClass("AmountRequired"); - createCustomErrorClass("BluetoothRequired"); - createCustomErrorClass("BtcUnmatchedApp"); - createCustomErrorClass("CantOpenDevice"); - createCustomErrorClass("CashAddrNotSupported"); - createCustomErrorClass("CurrencyNotSupported"); - createCustomErrorClass("DeviceAppVerifyNotSupported"); - createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - createCustomErrorClass("DeviceNotGenuine"); - createCustomErrorClass("DeviceOnDashboardExpected"); - createCustomErrorClass("DeviceOnDashboardUnexpected"); - createCustomErrorClass("DeviceInOSUExpected"); - createCustomErrorClass("DeviceHalted"); - createCustomErrorClass("DeviceNameInvalid"); - createCustomErrorClass("DeviceSocketFail"); - createCustomErrorClass("DeviceSocketNoBulkStatus"); - createCustomErrorClass("DisconnectedDevice"); - createCustomErrorClass("DisconnectedDeviceDuringOperation"); - createCustomErrorClass("EnpointConfig"); - createCustomErrorClass("EthAppPleaseEnableContractData"); - createCustomErrorClass("FeeEstimationFailed"); - createCustomErrorClass("FirmwareNotRecognized"); - createCustomErrorClass("HardResetFail"); - createCustomErrorClass("InvalidXRPTag"); - createCustomErrorClass("InvalidAddress"); - createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - createCustomErrorClass("LatestMCUInstalledError"); - createCustomErrorClass("UnknownMCU"); - createCustomErrorClass("LedgerAPIError"); - createCustomErrorClass("LedgerAPIErrorWithMessage"); - createCustomErrorClass("LedgerAPINotAvailable"); - createCustomErrorClass("ManagerAppAlreadyInstalled"); - createCustomErrorClass("ManagerAppRelyOnBTC"); - createCustomErrorClass("ManagerAppDepInstallRequired"); - createCustomErrorClass("ManagerAppDepUninstallRequired"); - createCustomErrorClass("ManagerDeviceLocked"); - createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - createCustomErrorClass("ManagerNotEnoughSpace"); - createCustomErrorClass("ManagerUninstallBTCDep"); - createCustomErrorClass("NetworkDown"); - createCustomErrorClass("NoAddressesFound"); - createCustomErrorClass("NotEnoughBalance"); - createCustomErrorClass("NotEnoughBalanceToDelegate"); - createCustomErrorClass("NotEnoughBalanceInParentAccount"); - createCustomErrorClass("NotEnoughSpendableBalance"); - createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - createCustomErrorClass("NoAccessToCamera"); - createCustomErrorClass("NotEnoughGas"); - createCustomErrorClass("NotSupportedLegacyAddress"); - createCustomErrorClass("GasLessThanEstimate"); - createCustomErrorClass("PasswordsDontMatch"); - createCustomErrorClass("PasswordIncorrect"); - createCustomErrorClass("RecommendSubAccountsToEmpty"); - createCustomErrorClass("RecommendUndelegation"); - createCustomErrorClass("TimeoutTagged"); - createCustomErrorClass("UnexpectedBootloader"); - createCustomErrorClass("MCUNotGenuineToDashboard"); - createCustomErrorClass("RecipientRequired"); - createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - createCustomErrorClass("UpdateFetchFileFail"); - createCustomErrorClass("UpdateIncorrectHash"); - createCustomErrorClass("UpdateIncorrectSig"); - createCustomErrorClass("UpdateYourApp"); - createCustomErrorClass("UserRefusedDeviceNameChange"); - createCustomErrorClass("UserRefusedAddress"); - createCustomErrorClass("UserRefusedFirmwareUpdate"); - createCustomErrorClass("UserRefusedAllowManager"); - createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - createCustomErrorClass("TransportOpenUserCancelled"); - createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - createCustomErrorClass("TransportWebUSBGestureRequired"); - createCustomErrorClass("DeviceShouldStayInApp"); - createCustomErrorClass("WebsocketConnectionError"); - createCustomErrorClass("WebsocketConnectionFailed"); - createCustomErrorClass("WrongDeviceForAccount"); - createCustomErrorClass("WrongAppForCurrency"); - createCustomErrorClass("ETHAddressNonEIP"); - createCustomErrorClass("CantScanQRCode"); - createCustomErrorClass("FeeNotLoaded"); - createCustomErrorClass("FeeRequired"); - createCustomErrorClass("FeeTooHigh"); - createCustomErrorClass("SyncError"); - createCustomErrorClass("PairingFailed"); - createCustomErrorClass("GenuineCheckFailed"); - createCustomErrorClass("LedgerAPI4xx"); - createCustomErrorClass("LedgerAPI5xx"); - createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - createCustomErrorClass("NoDBPathGiven"); - createCustomErrorClass("DBWrongPassword"); - createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa, - }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - class Transport { - constructor() { - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter__default["default"](); - - this.send = async (cla, ins, p1, p2, data = Buffer$i.alloc(0), statusList = [StatusCodes.OK]) => { - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - - const response = await this.exchange(Buffer$i.concat([Buffer$i.from([cla, ins, p1, p2]), Buffer$i.from([data.length]), data])); - const sw = response.readUInt16BE(response.length - 2); - - if (!statusList.some(s => s === sw)) { - throw new TransportStatusError(sw); - } - - return response; - }; - - this.exchangeBusyPromise = void 0; - - this.exchangeAtomicImpl = async f => { - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - - let resolveBusy; - const busyPromise = new Promise(r => { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - let unresponsiveReached = false; - const timeout = setTimeout(() => { - unresponsiveReached = true; - this.emit("unresponsive"); - }, this.unresponsiveTimeout); - - try { - const res = await f(); - - if (unresponsiveReached) { - this.emit("responsive"); - } - - return res; - } finally { - clearTimeout(timeout); - if (resolveBusy) resolveBusy(); - this.exchangeBusyPromise = null; - } - }; - - this._appAPIlock = null; - } - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - exchange(_apdu) { - throw new Error("exchange not implemented"); - } - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - setScrambleKey(_key) {} - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - close() { - return Promise.resolve(); - } - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - on(eventName, cb) { - this._events.on(eventName, cb); - } - /** - * Stop listening to an event on an instance of transport. - */ - - - off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - - emit(event, ...args) { - this._events.emit(event, ...args); - } - /** - * Enable or not logs of the binary exchange - */ - - - setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - - setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - - - setExchangeUnresponsiveTimeout(unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - } - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - static create(openTimeout = 3000, listenTimeout) { - return new Promise((resolve, reject) => { - let found = false; - const sub = this.listen({ - next: e => { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: e => { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: () => { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - - if (!found) { - reject(new TransportError(this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - const listenTimeoutId = listenTimeout ? setTimeout(() => { - sub.unsubscribe(); - reject(new TransportError(this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - decorateAppAPIMethods(self, methods, scrambleKey) { - for (let methodName of methods) { - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - - decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - return async (...args) => { - const { - _appAPIlock - } = this; - - if (_appAPIlock) { - return Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked")); - } - - try { - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return await f.apply(ctx, args); - } finally { - this._appAPIlock = null; - } - }; - } - - } - Transport.isSupported = void 0; - Transport.list = void 0; - Transport.listen = void 0; - Transport.open = void 0; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - - /** - * A Log object - */ - let id = 0; - const subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - - const log = (type, message, data) => { - const obj = { - type, - id: String(++id), - date: new Date() - }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - - const listen = cb => { - subscribers.push(cb); - return () => { - const i = subscribers.indexOf(cb); - - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (let i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } // for debug purpose - - - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; - } - - function wrapU2FTransportError(originalError, message, id) { - const err = new TransportError(message, id); // $FlowFixMe - - err.originalError = originalError; - return err; - } - - function wrapApdu(apdu, key) { - const result = Buffer$i.alloc(apdu.length); - - for (let i = 0; i < apdu.length; i++) { - result[i] = apdu[i] ^ key[i % key.length]; - } - - return result; - } // Convert from normal to web-safe, strip trailing "="s - - - const webSafe64 = base64 => base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Convert from web-safe to normal, add trailing "="s - - - const normal64 = base64 => base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); - - function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { - const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$i.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); - const signRequest = { - version: "U2F_V2", - keyHandle: webSafe64(keyHandle.toString("base64")), - challenge: webSafe64(challenge.toString("base64")), - appId: location.origin - }; - log("apdu", "=> " + apdu.toString("hex")); - return u2fApi.sign(signRequest, timeoutMillis / 1000).then(response => { - const { - signatureData - } = response; - - if (typeof signatureData === "string") { - const data = Buffer$i.from(normal64(signatureData), "base64"); - let result; - - if (!unwrap) { - result = data; - } else { - result = data.slice(5); - } - - log("apdu", "<= " + result.toString("hex")); - return result; - } else { - throw response; - } - }); - } - - let transportInstances = []; - - function emitDisconnect() { - transportInstances.forEach(t => t.emit("disconnect")); - transportInstances = []; - } - - function isTimeoutU2FError(u2fError) { - return u2fError.metaData.code === 5; - } - /** - * U2F web Transport implementation - * @example - * import TransportU2F from "@ledgerhq/hw-transport-u2f"; - * ... - * TransportU2F.create().then(transport => ...) - */ - - - class TransportU2F extends Transport { - /* - */ - - /* - */ - - /** - * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) - */ - static async open(_, _openTimeout = 5000) { - return new TransportU2F(); - } - - constructor() { - super(); - this.scrambleKey = void 0; - this.unwrap = true; - transportInstances.push(this); - } - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - - async exchange(apdu) { - try { - return await attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); - } catch (e) { - const isU2FError = typeof e.metaData === "object"; - - if (isU2FError) { - if (isTimeoutU2FError(e)) { - emitDisconnect(); - } // the wrapping make error more usable and "printable" to the end user. - - - throw wrapU2FTransportError(e, "Failed to sign with Ledger device: U2F " + e.metaData.type, "U2F_" + e.metaData.code); - } else { - throw e; - } - } - } - /** - */ - - - setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$i.from(scrambleKey, "ascii"); - } - /** - */ - - - setUnwrap(unwrap) { - this.unwrap = unwrap; - } - - close() { - // u2f have no way to clean things up - return Promise.resolve(); - } - - } - TransportU2F.isSupported = u2fApi.isSupported; - - TransportU2F.list = () => // this transport is not discoverable but we are going to guess if it is here with isSupported() - u2fApi.isSupported().then(supported => supported ? [null] : []); - - TransportU2F.listen = observer => { - let unsubscribed = false; - u2fApi.isSupported().then(supported => { - if (unsubscribed) return; - - if (supported) { - observer.next({ - type: "add", - descriptor: null - }); - observer.complete(); - } else { - observer.error(new TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); - } - }); - return { - unsubscribe: () => { - unsubscribed = true; - } - }; - }; - - var TransportU2F$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': TransportU2F - }); - - var inherits$2 = inherits$f.exports; - var HashBase = hashBase; - var Buffer$1 = safeBuffer.exports.Buffer; - - var ARRAY16 = new Array(16); - - function MD5$1 () { - HashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } - - inherits$2(MD5$1, HashBase); - - MD5$1.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; - - MD5$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$1.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; - - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } - - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } - - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } - - function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } - - var md5_js = MD5$1; - - var Buffer = safeBuffer.exports.Buffer; - var Transform = require$$0__default$2["default"].Transform; - var StringDecoder = require$$2__default["default"].StringDecoder; - var inherits$1 = inherits$f.exports; - - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$1(CipherBase, Transform); - - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer.from(data, inputEnc); - } - - var outData = this._update(data); - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - - return outData - }; - - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; - - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; - - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; - - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; - - var cipherBase = CipherBase; - - var inherits = inherits$f.exports; - var MD5 = md5_js; - var RIPEMD160 = ripemd160$1; - var sha = sha_js.exports; - var Base = cipherBase; - - function Hash (hash) { - Base.call(this, 'digest'); - - this._hash = hash; - } - - inherits(Hash, Base); - - Hash.prototype._update = function (data) { - this._hash.update(data); - }; - - Hash.prototype._final = function () { - return this._hash.digest() - }; - - var browser = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() - - return new Hash(sha(alg)) - }; - - var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser - }, [browser])); - - exports.Btc = Btc$1; - exports.Log = index; - exports.TransportU2F = TransportU2F$1; - exports.TransportWebUSB = TransportWebUSB$1; - exports.createHash = browser$1; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,o=Object.create(i.prototype),s=new A(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return k()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=M(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function m(){}function y(){}function v(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,_=b&&b(b(P([])));_&&_!==r&&n.call(_,o)&&(w=_);var E=v.prototype=m.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function M(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,M(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function A(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function P(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),O(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;O(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:P(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const o=2147483648;var s=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=o)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[i]+=o;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new s(n)},s.prototype.toPathArray=function(){return this.path},s.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var u=s,a=i(Object.freeze({__proto__:null,default:{}})),h=a.createHash,f={exports:{}},c=[],l=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,d=!1;function g(){d=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+c[i>>12&63]+c[i>>6&63]+c[63&i]);return o.join("")}function y(t){var e;d||g();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=c[e>>2],i+=c[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=c[e>>10],i+=c[e>>4&63],i+=c[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function w(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var b={}.toString,_=Array.isArray||function(t){return"[object Array]"==b.call(t)};M.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=S();function S(){return M.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function I(t,e){if(S()=S())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+S().toString(16)+" bytes");return 0|t}function R(t){return!(null==t||!t._isBuffer)}function N(t,e){if(R(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ot(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return st(t).length;default:if(n)return ot(t).length;e=(""+e).toLowerCase(),n=!0}}function x(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return z(this,e,r);case"utf8":case"utf-8":return K(this,e,r);case"ascii":return V(this,e,r);case"latin1":case"binary":return $(this,e,r);case"base64":return G(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function B(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function L(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=M.from(e,n)),R(e))return 0===e.length?-1:U(t,e,r,n,i);if("number"==typeof e)return e&=255,M.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):U(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function U(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function G(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function K(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=W)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},M.prototype.compare=function(t,e,r,n,i){if(!R(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return C(this,t,e,r);case"utf8":case"utf-8":return D(this,t,e,r);case"ascii":return H(this,t,e,r);case"latin1":case"binary":return F(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},M.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var W=4096;function V(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function J(t,e,r,n,i,o){if(!R(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function Z(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Q(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function tt(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function et(t,e,r,n,i){return i||tt(t,0,r,4),w(t,e,r,n,23,4),r+4}function rt(t,e,r,n,i){return i||tt(t,0,r,8),w(t,e,r,n,52,8),r+8}M.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},M.prototype.readUInt8=function(t,e){return e||Y(t,1,this.length),this[t]},M.prototype.readUInt16LE=function(t,e){return e||Y(t,2,this.length),this[t]|this[t+1]<<8},M.prototype.readUInt16BE=function(t,e){return e||Y(t,2,this.length),this[t]<<8|this[t+1]},M.prototype.readUInt32LE=function(t,e){return e||Y(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},M.prototype.readUInt32BE=function(t,e){return e||Y(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},M.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Y(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},M.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Y(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},M.prototype.readInt8=function(t,e){return e||Y(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},M.prototype.readInt16LE=function(t,e){e||Y(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},M.prototype.readInt16BE=function(t,e){e||Y(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},M.prototype.readInt32LE=function(t,e){return e||Y(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},M.prototype.readInt32BE=function(t,e){return e||Y(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},M.prototype.readFloatLE=function(t,e){return e||Y(t,4,this.length),v(this,t,!0,23,4)},M.prototype.readFloatBE=function(t,e){return e||Y(t,4,this.length),v(this,t,!1,23,4)},M.prototype.readDoubleLE=function(t,e){return e||Y(t,8,this.length),v(this,t,!0,52,8)},M.prototype.readDoubleBE=function(t,e){return e||Y(t,8,this.length),v(this,t,!1,52,8)},M.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||J(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},M.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,1,255,0),M.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},M.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,65535,0),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Z(this,t,e,!0),e+2},M.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,65535,0),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Z(this,t,e,!1),e+2},M.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,4294967295,0),M.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Q(this,t,e,!0),e+4},M.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,4294967295,0),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Q(this,t,e,!1),e+4},M.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);J(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},M.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);J(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},M.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,1,127,-128),M.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},M.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,32767,-32768),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Z(this,t,e,!0),e+2},M.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,32767,-32768),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Z(this,t,e,!1),e+2},M.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,2147483647,-2147483648),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Q(this,t,e,!0),e+4},M.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Q(this,t,e,!1),e+4},M.prototype.writeFloatLE=function(t,e,r){return et(this,t,e,!0,r)},M.prototype.writeFloatBE=function(t,e,r){return et(this,t,e,!1,r)},M.prototype.writeDoubleLE=function(t,e,r){return rt(this,t,e,!0,r)},M.prototype.writeDoubleBE=function(t,e,r){return rt(this,t,e,!1,r)},M.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!M.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function st(t){return function(t){var e,r,n,i,o,s;d||g();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new p(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=l[t.charCodeAt(e)]<<2|l[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=l[t.charCodeAt(e)]<<10|l[t.charCodeAt(e+1)]<<4|l[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(nt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ut(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function at(t){return null!=t&&(!!t._isBuffer||ht(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&ht(t.slice(0,0))}(t))}function ht(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ft=i(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:M,SlowBuffer:function(t){return+t!=t&&(t=0),M.alloc(+t)},isBuffer:at})); +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +!function(t,e){var r=ft,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(f,f.exports);var ct=f.exports.Buffer;var lt=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ct.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ct.from(e)),!ct.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,m=0|s[2],y=8191&m,v=m>>>13,w=0|s[3],b=8191&w,_=w>>>13,E=0|s[4],S=8191&E,I=E>>>13,M=0|s[5],T=8191&M,O=M>>>13,A=0|s[6],P=8191&A,k=A>>>13,R=0|s[7],N=8191&R,x=R>>>13,B=0|s[8],L=8191&B,U=B>>>13,C=0|s[9],D=8191&C,H=C>>>13,F=0|u[0],j=8191&F,q=F>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var mt=(h+(n=Math.imul(c,j))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,j)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(d,j),i=(i=Math.imul(d,q))+Math.imul(g,j)|0,o=Math.imul(g,q);var yt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(y,j),i=(i=Math.imul(y,q))+Math.imul(v,j)|0,o=Math.imul(v,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var vt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(b,j),i=(i=Math.imul(b,q))+Math.imul(_,j)|0,o=Math.imul(_,q),n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,j),i=(i=Math.imul(S,q))+Math.imul(I,j)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,W)|0,n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,j),i=(i=Math.imul(T,q))+Math.imul(O,j)|0,o=Math.imul(O,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var _t=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(P,j),i=(i=Math.imul(P,q))+Math.imul(k,j)|0,o=Math.imul(k,q),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,tt)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var Et=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(N,j),i=(i=Math.imul(N,q))+Math.imul(x,j)|0,o=Math.imul(x,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,W)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,z)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,n=n+Math.imul(y,rt)|0,i=(i=i+Math.imul(y,nt)|0)+Math.imul(v,rt)|0,o=o+Math.imul(v,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(L,j),i=(i=Math.imul(L,q))+Math.imul(U,j)|0,o=Math.imul(U,q),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(O,Y)|0,o=o+Math.imul(O,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,o=o+Math.imul(_,nt)|0,n=n+Math.imul(y,ot)|0,i=(i=i+Math.imul(y,st)|0)+Math.imul(v,ot)|0,o=o+Math.imul(v,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,j),i=(i=Math.imul(D,q))+Math.imul(H,j)|0,o=Math.imul(H,q),n=n+Math.imul(L,K)|0,i=(i=i+Math.imul(L,W)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(_,ot)|0,o=o+Math.imul(_,st)|0,n=n+Math.imul(y,at)|0,i=(i=i+Math.imul(y,ht)|0)+Math.imul(v,at)|0,o=o+Math.imul(v,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Mt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(O,rt)|0,o=o+Math.imul(O,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(_,at)|0,o=o+Math.imul(_,ht)|0,n=n+Math.imul(y,ct)|0,i=(i=i+Math.imul(y,lt)|0)+Math.imul(v,ct)|0,o=o+Math.imul(v,lt)|0;var Tt=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(L,Y)|0,i=(i=i+Math.imul(L,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(T,ot)|0,i=(i=i+Math.imul(T,st)|0)+Math.imul(O,ot)|0,o=o+Math.imul(O,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(_,ct)|0,o=o+Math.imul(_,lt)|0;var Ot=(h+(n=n+Math.imul(y,dt)|0)|0)+((8191&(i=(i=i+Math.imul(y,gt)|0)+Math.imul(v,dt)|0))<<13)|0;h=((o=o+Math.imul(v,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(x,rt)|0,o=o+Math.imul(x,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ht)|0)+Math.imul(O,at)|0,o=o+Math.imul(O,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var At=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;h=((o=o+Math.imul(_,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(x,ot)|0,o=o+Math.imul(x,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(T,ct)|0,i=(i=i+Math.imul(T,lt)|0)+Math.imul(O,ct)|0,o=o+Math.imul(O,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(L,ot)|0,i=(i=i+Math.imul(L,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(x,at)|0,o=o+Math.imul(x,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(k,ct)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(O,dt)|0))<<13)|0;h=((o=o+Math.imul(O,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(x,ct)|0,o=o+Math.imul(x,lt)|0;var Rt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(L,ct)|0,i=(i=i+Math.imul(L,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(x,dt)|0))<<13)|0;h=((o=o+Math.imul(x,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var xt=(h+(n=n+Math.imul(L,dt)|0)|0)+((8191&(i=(i=i+Math.imul(L,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=mt,a[1]=yt,a[2]=vt,a[3]=wt,a[4]=bt,a[5]=_t,a[6]=Et,a[7]=St,a[8]=It,a[9]=Mt,a[10]=Tt,a[11]=Ot,a[12]=At,a[13]=Pt,a[14]=kt,a[15]=Rt,a[16]=Nt,a[17]=xt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new E(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};function y(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){E.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}y.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},y.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},y.prototype.split=function(t,e){t.iushrn(this.n,0,e)},y.prototype.imulK=function(t){return t.imul(this.k)},n(v,y),v.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},v.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(m[t])return m[t];var e;if("k256"===t)e=new v;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return m[t]=e,e},E.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},E.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},E.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},E.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},E.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},E.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},E.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},E.prototype.isqr=function(t){return this.imul(t,t.clone())},E.prototype.sqr=function(t){return this.mul(t,t)},E.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,m=0;0!==g.cmp(u);m++)g=g.redSqr();r(m=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},E.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},E.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,E),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(xt);var Bt={},Lt="6.5.4",Ut={},Ct={exports:{}};!function(t){!function(t,e){function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){if(i.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==e&&"be"!==e||(r=e,e=10),this._init(t||0,e||10,r||"be"))}var o;"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:require("buffer").Buffer}catch(t){}function s(t,e){var r=t.charCodeAt(e);return r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,m=0|s[2],y=8191&m,v=m>>>13,w=0|s[3],b=8191&w,_=w>>>13,E=0|s[4],S=8191&E,I=E>>>13,M=0|s[5],T=8191&M,O=M>>>13,A=0|s[6],P=8191&A,k=A>>>13,R=0|s[7],N=8191&R,x=R>>>13,B=0|s[8],L=8191&B,U=B>>>13,C=0|s[9],D=8191&C,H=C>>>13,F=0|u[0],j=8191&F,q=F>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var mt=(h+(n=Math.imul(c,j))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,j)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(d,j),i=(i=Math.imul(d,q))+Math.imul(g,j)|0,o=Math.imul(g,q);var yt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(y,j),i=(i=Math.imul(y,q))+Math.imul(v,j)|0,o=Math.imul(v,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var vt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(b,j),i=(i=Math.imul(b,q))+Math.imul(_,j)|0,o=Math.imul(_,q),n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,j),i=(i=Math.imul(S,q))+Math.imul(I,j)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,W)|0,n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,j),i=(i=Math.imul(T,q))+Math.imul(O,j)|0,o=Math.imul(O,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var _t=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(P,j),i=(i=Math.imul(P,q))+Math.imul(k,j)|0,o=Math.imul(k,q),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,tt)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var Et=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(N,j),i=(i=Math.imul(N,q))+Math.imul(x,j)|0,o=Math.imul(x,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,W)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,z)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,n=n+Math.imul(y,rt)|0,i=(i=i+Math.imul(y,nt)|0)+Math.imul(v,rt)|0,o=o+Math.imul(v,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(L,j),i=(i=Math.imul(L,q))+Math.imul(U,j)|0,o=Math.imul(U,q),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(O,Y)|0,o=o+Math.imul(O,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,o=o+Math.imul(_,nt)|0,n=n+Math.imul(y,ot)|0,i=(i=i+Math.imul(y,st)|0)+Math.imul(v,ot)|0,o=o+Math.imul(v,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,j),i=(i=Math.imul(D,q))+Math.imul(H,j)|0,o=Math.imul(H,q),n=n+Math.imul(L,K)|0,i=(i=i+Math.imul(L,W)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(_,ot)|0,o=o+Math.imul(_,st)|0,n=n+Math.imul(y,at)|0,i=(i=i+Math.imul(y,ht)|0)+Math.imul(v,at)|0,o=o+Math.imul(v,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Mt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(O,rt)|0,o=o+Math.imul(O,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(_,at)|0,o=o+Math.imul(_,ht)|0,n=n+Math.imul(y,ct)|0,i=(i=i+Math.imul(y,lt)|0)+Math.imul(v,ct)|0,o=o+Math.imul(v,lt)|0;var Tt=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(L,Y)|0,i=(i=i+Math.imul(L,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(T,ot)|0,i=(i=i+Math.imul(T,st)|0)+Math.imul(O,ot)|0,o=o+Math.imul(O,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(_,ct)|0,o=o+Math.imul(_,lt)|0;var Ot=(h+(n=n+Math.imul(y,dt)|0)|0)+((8191&(i=(i=i+Math.imul(y,gt)|0)+Math.imul(v,dt)|0))<<13)|0;h=((o=o+Math.imul(v,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(x,rt)|0,o=o+Math.imul(x,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ht)|0)+Math.imul(O,at)|0,o=o+Math.imul(O,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var At=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;h=((o=o+Math.imul(_,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(x,ot)|0,o=o+Math.imul(x,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(T,ct)|0,i=(i=i+Math.imul(T,lt)|0)+Math.imul(O,ct)|0,o=o+Math.imul(O,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(L,ot)|0,i=(i=i+Math.imul(L,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(x,at)|0,o=o+Math.imul(x,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(k,ct)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(O,dt)|0))<<13)|0;h=((o=o+Math.imul(O,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(x,ct)|0,o=o+Math.imul(x,lt)|0;var Rt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(L,ct)|0,i=(i=i+Math.imul(L,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(x,dt)|0))<<13)|0;h=((o=o+Math.imul(x,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var xt=(h+(n=n+Math.imul(L,dt)|0)|0)+((8191&(i=(i=i+Math.imul(L,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=mt,a[1]=yt,a[2]=vt,a[3]=wt,a[4]=bt,a[5]=_t,a[6]=Et,a[7]=St,a[8]=It,a[9]=Mt,a[10]=Tt,a[11]=Ot,a[12]=At,a[13]=Pt,a[14]=kt,a[15]=Rt,a[16]=Nt,a[17]=xt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new E(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};function y(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){E.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}y.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},y.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},y.prototype.split=function(t,e){t.iushrn(this.n,0,e)},y.prototype.imulK=function(t){return t.imul(this.k)},n(v,y),v.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},v.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(m[t])return m[t];var e;if("k256"===t)e=new v;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return m[t]=e,e},E.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},E.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},E.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},E.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},E.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},E.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},E.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},E.prototype.isqr=function(t){return this.imul(t,t.clone())},E.prototype.sqr=function(t){return this.mul(t,t)},E.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,m=0;0!==g.cmp(u);m++)g=g.redSqr();r(m=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},E.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},E.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,E),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Ct);var Dt=Ht;function Ht(t,e){if(!t)throw new Error(e||"Assertion failed")}Ht.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Ft={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Ft),function(t){var e=t,r=Ct.exports,n=Dt,i=Ft;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ut);var jt,qt={exports:{}};function Gt(t){this.rand=t}if(qt.exports=function(t){return jt||(jt=new Gt(null)),jt.generate(t)},qt.exports.Rand=Gt,Gt.prototype.generate=function(t){return this._rand(t)},Gt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Zt=Jt;function Qt(t,e){this.curve=t,this.type=e,this.precomputed=null}Jt.prototype.point=function(){throw new Error("Not implemented")},Jt.prototype.validate=function(){throw new Error("Not implemented")},Jt.prototype._fixedNafMul=function(t,e){Yt(t.precomputed);var r=t._getDoubles(),n=zt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];Yt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Jt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var m=[-3,-1,-5,-7,0,7,5,1,3],y=Xt(r[p],r[d]);for(c=Math.max(y[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var E=0;o>=0;){var S=!0;for(s=0;s=0&&E++,b=b.dblp(E),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Qt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},ae.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},ae.prototype.pointFromX=function(t,e){(t=new ie(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},ae.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},ae.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},fe.prototype.isInfinity=function(){return this.inf},fe.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},fe.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},fe.prototype.getX=function(){return this.x.fromRed()},fe.prototype.getY=function(){return this.y.fromRed()},fe.prototype.mul=function(t){return t=new ie(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},fe.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},fe.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},fe.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},fe.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},fe.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},oe(ce,se.BasePoint),ae.prototype.jpoint=function(t,e,r){return new ce(this,t,e,r)},ce.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},ce.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},ce.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},ce.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},ce.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},ce.prototype.inspect=function(){return this.isInfinity()?"":""},ce.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var le=Ct.exports,pe=te.exports,de=Zt,ge=Ut;function me(t){de.call(this,"mont",t),this.a=new le(t.a,16).toRed(this.red),this.b=new le(t.b,16).toRed(this.red),this.i4=new le(4).toRed(this.red).redInvm(),this.two=new le(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}pe(me,de);var ye=me;function ve(t,e,r){de.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new le(e,16),this.z=new le(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}me.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},pe(ve,de.BasePoint),me.prototype.decodePoint=function(t,e){return this.point(ge.toArray(t,e),1)},me.prototype.point=function(t,e){return new ve(this,t,e)},me.prototype.pointFromJSON=function(t){return ve.fromJSON(this,t)},ve.prototype.precompute=function(){},ve.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ve.fromJSON=function(t,e){return new ve(t,e[0],e[1]||t.one)},ve.prototype.inspect=function(){return this.isInfinity()?"":""},ve.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ve.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ve.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ve.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ve.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ve.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ve.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var we=Ut,be=Ct.exports,_e=te.exports,Ee=Zt,Se=we.assert;function Ie(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,Ee.call(this,"edwards",t),this.a=new be(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new be(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new be(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Se(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}_e(Ie,Ee);var Me=Ie;function Te(t,e,r,n,i){Ee.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new be(e,16),this.y=new be(r,16),this.z=n?new be(n,16):this.curve.one,this.t=i&&new be(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}Ie.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},Ie.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},Ie.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},Ie.prototype.pointFromX=function(t,e){(t=new be(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},Ie.prototype.pointFromY=function(t,e){(t=new be(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},Ie.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},_e(Te,Ee.BasePoint),Ie.prototype.pointFromJSON=function(t){return Te.fromJSON(this,t)},Ie.prototype.point=function(t,e,r,n){return new Te(this,t,e,r,n)},Te.fromJSON=function(t,e){return new Te(t,e[0],e[1],e[2])},Te.prototype.inspect=function(){return this.isInfinity()?"":""},Te.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Te.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Te.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Te.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Te.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Te.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Te.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Te.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Te.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Te.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Te.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Te.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Te.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Te.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Te.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Te.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Te.prototype.toP=Te.prototype.normalize,Te.prototype.mixedAdd=Te.prototype.add,function(t){var e=t;e.base=Zt,e.short=he,e.mont=ye,e.edwards=Me}(Wt);var Oe={},Ae={},Pe={},ke=Dt,Re=te.exports;function Ne(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Be(t){return 1===t.length?"0"+t:t}function Le(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Pe.inherits=Re,Pe.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Ne(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Pe.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Pe.rotr32=function(t,e){return t>>>e|t<<32-e},Pe.rotl32=function(t,e){return t<>>32-e},Pe.sum32=function(t,e){return t+e>>>0},Pe.sum32_3=function(t,e,r){return t+e+r>>>0},Pe.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Pe.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Pe.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Pe.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Pe.sum64_lo=function(t,e,r,n){return e+n>>>0},Pe.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Pe.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Pe.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Pe.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Pe.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Pe.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Pe.shr64_hi=function(t,e,r){return t>>>r},Pe.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Ue={},Ce=Pe,De=Dt;function He(){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}Ue.BlockHash=He,He.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},je.g1_256=function(t){return qe(t,17)^qe(t,19)^t>>>10};var Ve=Pe,$e=Ue,ze=je,Xe=Ve.rotl32,Ye=Ve.sum32,Je=Ve.sum32_5,Ze=ze.ft_1,Qe=$e.BlockHash,tr=[1518500249,1859775393,2400959708,3395469782];function er(){if(!(this instanceof er))return new er;Qe.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ve.inherits(er,Qe);var rr=er;er.blockSize=512,er.outSize=160,er.hmacStrength=80,er.padLength=64,er.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),En(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Pn=An;An.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},An.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Tn.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Bn=Ct.exports,Ln=Ut,Un=Ln.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Un(t.r&&t.s,"Signature without r or s"),this.r=new Bn(t.r,16),this.s=new Bn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Dn=Cn;function Hn(){this.place=0}function Fn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function jn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Ln.toArray(t,e);var r=new Hn;if(48!==t[r.place++])return!1;var n=Fn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Fn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Fn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Bn(o),this.s=new Bn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=jn(e),r=jn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];qn(n,e.length),(n=n.concat(e)).push(2),qn(n,r.length);var i=n.concat(r),o=[48];return qn(o,i.length),o=o.concat(i),Ln.encode(o,t)};var Gn=Ct.exports,Kn=Pn,Wn=Ut,Vn=Oe,$n=qt.exports,zn=Wn.assert,Xn=xn,Yn=Dn;function Jn(t){if(!(this instanceof Jn))return new Jn(t);"string"==typeof t&&(zn(Object.prototype.hasOwnProperty.call(Vn,t),"Unknown curve "+t),t=Vn[t]),t instanceof Vn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Zn=Jn;Jn.prototype.keyPair=function(t){return new Xn(this,t)},Jn.prototype.keyFromPrivate=function(t,e){return Xn.fromPrivate(this,t,e)},Jn.prototype.keyFromPublic=function(t,e){return Xn.fromPublic(this,t,e)},Jn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Kn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||$n(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Gn(2));;){var i=new Gn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Jn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Jn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Gn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Kn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Gn(1)),h=0;;h++){var f=n.k?n.k(h):new Gn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new Yn({r:p,s:d,recoveryParam:g})}}}}}},Jn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Gn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new Yn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Jn.prototype.recoverPubKey=function(t,e,r,n){zn((3&r)===r,"The recovery param is more than two bits"),e=new Yn(e,n);var i=this.n,o=new Gn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Jn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new Yn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Qn=Ut,ti=Qn.assert,ei=Qn.parseBytes,ri=Qn.cachedProperty;function ni(t,e){this.eddsa=t,this._secret=ei(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=ei(e.pub)}ni.fromPublic=function(t,e){return e instanceof ni?e:new ni(t,{pub:e})},ni.fromSecret=function(t,e){return e instanceof ni?e:new ni(t,{secret:e})},ni.prototype.secret=function(){return this._secret},ri(ni,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ri(ni,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ri(ni,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ri(ni,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ri(ni,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ri(ni,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ni.prototype.sign=function(t){return ti(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ni.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ni.prototype.getSecret=function(t){return ti(this._secret,"KeyPair is public only"),Qn.encode(this.secret(),t)},ni.prototype.getPublic=function(t){return Qn.encode(this.pubBytes(),t)};var ii=ni,oi=Ct.exports,si=Ut,ui=si.assert,ai=si.cachedProperty,hi=si.parseBytes;function fi(t,e){this.eddsa=t,"object"!=typeof e&&(e=hi(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),ui(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof oi&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}ai(fi,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),ai(fi,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),ai(fi,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),ai(fi,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),fi.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},fi.prototype.toHex=function(){return si.encode(this.toBytes(),"hex").toUpperCase()};var ci=fi,li=Ae,pi=Oe,di=Ut,gi=di.assert,mi=di.parseBytes,yi=ii,vi=ci;function wi(t){if(gi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof wi))return new wi(t);t=pi[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=li.sha512}var bi=wi;wi.prototype.sign=function(t,e){t=mi(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},wi.prototype.verify=function(t,e,r){t=mi(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},wi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Vi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Ai)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function ji(t){return 4!==t[0]}function qi(t){return!!Di(t)&&(t.compare(Ai)>0&&t.compare(Pi)<0)}function Gi(t,e){return void 0===t&&void 0!==e?ji(e):void 0===t||t}function Ki(t){return new Mi(t)}function Wi(t){return t.toArrayLike(Buffer,"be",32)}function Vi(t){return Ti.curve.decodePoint(t)}function $i(t,e){return Buffer.from(t._encode(e))}function zi(t,e,r){if(!Di(t))throw new TypeError(Ci);if(!qi(e))throw new TypeError(Bi);if(void 0!==r&&!Di(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Ki(e),i=Ki(t);let o,s;Oi(t,e,(function(t){const e=Ki(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Ri),0!==o.isZero()&&(s=e.invm(Ri).mul(i.add(n.mul(o))).umod(Ri),0!==s.isZero()))}),qi,r),s.cmp(Ni)>0&&(s=Ri.sub(s));const u=Buffer.allocUnsafe(64);return Wi(o).copy(u,0),Wi(s).copy(u,32),u}var Xi={isPoint:Fi,isPointCompressed:function(t){return!!Fi(t)&&ji(t)},isPrivate:qi,pointAdd:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Fi(e))throw new TypeError(Li);const n=Vi(t),i=Vi(e),o=n.add(i);return o.isInfinity()?null:$i(o,Gi(r,t))},pointAddScalar:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Hi(e))throw new TypeError(Ui);const n=Gi(r,t),i=Vi(t);if(0===e.compare(Ai))return $i(i,n);const o=Ki(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:$i(u,n)},pointCompress:function(t,e){if(!Fi(t))throw new TypeError(Li);const r=Vi(t);if(r.isInfinity())throw new TypeError(Li);return $i(r,Gi(e,t))},pointFromScalar:function(t,e){if(!qi(t))throw new TypeError(Bi);const r=Ki(t),n=xi.mul(r);return n.isInfinity()?null:$i(n,Gi(e))},pointMultiply:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Hi(e))throw new TypeError(Ui);const n=Gi(r,t),i=Vi(t),o=Ki(e),s=i.mul(o);return s.isInfinity()?null:$i(s,n)},privateAdd:function(t,e){if(!qi(t))throw new TypeError(Bi);if(!Hi(e))throw new TypeError(Ui);const r=Ki(t),n=Ki(e),i=Wi(r.add(n).umod(Ri));return qi(i)?i:null},privateSub:function(t,e){if(!qi(t))throw new TypeError(Bi);if(!Hi(e))throw new TypeError(Ui);const r=Ki(t),n=Ki(e),i=Wi(r.sub(n).umod(Ri));return qi(i)?i:null},sign:function(t,e){return zi(t,e)},signWithEntropy:function(t,e,r){return zi(t,e,r)},verify:function(t,e,r,n){if(!Di(t))throw new TypeError(Ci);if(!Fi(e))throw new TypeError(Li);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Pi)<0&&r.compare(Pi)<0}(r))throw new TypeError("Expected Signature");const i=Vi(e),o=Ki(r.slice(0,32)),s=Ki(r.slice(32,64));if(n&&s.cmp(Ni)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Ki(t),a=s.invm(Ri),h=u.mul(a).umod(Ri),f=o.mul(a).umod(Ri),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Ri).eq(o)}};try{Nt.exports=require("./native")}catch(t){Nt.exports=Xi}var Yi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Ji in Yi.Null=Yi.Nil,Yi)Yi[Ji].toJSON=function(t){return t}.bind(null,Ji);var Zi=Yi,Qi=Zi;function to(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function eo(t){return Qi.Nil(t)?"":to(t.constructor)}function ro(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function no(t){return Qi.Function(t)?t.toJSON?t.toJSON():to(t):Qi.Array(t)?"Array":t&&Qi.Object(t)?"Object":void 0!==t?t:""}function io(t,e,r){var n=function(t){return Qi.Function(t)?"":Qi.String(t)?JSON.stringify(t):t&&Qi.Object(t)?"":t}(e);return"Expected "+no(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function oo(t,e,r){r=r||eo(e),this.message=io(t,e,r),ro(this,oo),this.__type=t,this.__value=e,this.__valueTypeName=r}function so(t,e,r,n,i){t?(i=i||eo(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),io('property "'+no(r)+o+no(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',ro(this,oo),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}oo.prototype=Object.create(Error.prototype),oo.prototype.constructor=oo,so.prototype=Object.create(Error.prototype),so.prototype.constructor=oo;var uo={TfTypeError:oo,TfPropertyTypeError:so,tfCustomError:function(t,e){return new oo(t,{},e)},tfSubError:function(t,e,r){return t instanceof so?(e=e+"."+t.__property,t=new so(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof oo&&(t=new so(t.__type,e,r,t.__value,t.__valueTypeName)),ro(t),t},tfJSON:no,getValueTypeName:eo},ao=Zi,ho=uo;function fo(t){return Buffer.isBuffer(t)}function co(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function lo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw ho.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var po=lo.bind(null,ao.Array),go=lo.bind(null,fo),mo=lo.bind(null,co),yo=lo.bind(null,ao.String);var vo=Math.pow(2,53)-1;var wo={ArrayN:po,Buffer:fo,BufferN:go,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:co,HexN:mo,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-vo&&t<=vo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=vo&&Math.floor(t)===t}};for(var bo in wo)wo[bo].toJSON=function(t){return t}.bind(null,bo);var _o=wo,Eo=Zi,So=uo.tfJSON,Io=uo.TfTypeError,Mo=uo.TfPropertyTypeError,To=uo.tfSubError,Oo=uo.getValueTypeName,Ao={arrayOf:function(t,e){function r(r,n){return!!Eo.Array(r)&&(!Eo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw To(t,r)}}))))))}return t=Po(t),e=e||{},r.toJSON=function(){var r="["+So(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return Eo.Nil(r)||e(r,n,t)}return e=Po(e),r.toJSON=function(){return"?"+So(e)},r},map:function(t,e){function r(r,n){if(!Eo.Object(r))return!1;if(Eo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw To(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw To(t,i)}}return!0}return t=Po(t),e&&(e=Po(e)),r.toJSON=e?function(){return"{"+So(e)+": "+So(t)+"}"}:function(){return"{"+So(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Po(t[r]);function n(t,r){if(!Eo.Object(t))return!1;if(Eo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw To(t,n)}if(r)for(n in t)if(!e[n])throw new Mo(void 0,n);return!0}return n.toJSON=function(){return So(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(So).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(So).join(" & ")},e},quacksLike:function(t){function e(e){return t===Oo(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return!Eo.Nil(e)&&(!Eo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw To(t,n)}}))))}return e.toJSON=function(){return"("+t.map(So).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Po(t){if(Eo.String(t))return"?"===t[0]?Ao.maybe(t.slice(1)):Eo[t]||Ao.quacksLike(t);if(t&&Eo.Object(t)){if(Eo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Ao.arrayOf(t[0])}return Ao.object(t)}return Eo.Function(t)?t:Ao.value(t)}function ko(t,e,r,n){if(Eo.Function(t)){if(t(e,r))return!0;throw new Io(n||t,e)}return ko(Po(t),e,r)}for(var Ro in Ao.oneOf=Ao.anyOf,Eo)ko[Ro]=Eo[Ro];for(Ro in Ao)ko[Ro]=Ao[Ro];var No=_o;for(Ro in No)ko[Ro]=No[Ro];ko.compile=Po,ko.TfTypeError=Io,ko.TfPropertyTypeError=Mo;var xo=ko,Bo=vt;function Lo(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Uo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return Lo(Bo.decode(t),e)},decodeRaw:Lo,encode:function(t,e,r){return"number"==typeof t?Bo.encode(Uo(t,e,r)):Bo.encode(Uo(t.version,t.privateKey,t.compressed))},encodeRaw:Uo};Object.defineProperty(Ot,"__esModule",{value:!0});const Do=At,Ho=vt,Fo=Nt.exports,jo=xo,qo=Co,Go=jo.BufferN(32),Ko=jo.compile({wif:jo.UInt8,bip32:{public:jo.UInt32,private:jo.UInt32}}),Wo={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Vo=2147483648,$o=Math.pow(2,31)-1;function zo(t){return jo.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function Xo(t){return jo.UInt32(t)&&t<=$o}class Yo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,jo(Ko,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Fo.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Do.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Qo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Ho.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return qo.encode(this.network.wif,this.privateKey,!0)}derive(t){jo(jo.UInt32,t);const e=t>=Vo,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Do.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Fo.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Fo.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Qo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Fo.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Zo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return jo(Xo,t),this.derive(t+Vo)}derivePath(t){jo(zo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Fo.sign(t,this.privateKey);{let e=Fo.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Fo.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Fo.verify(t,this.publicKey,e)}}function Jo(t,e,r){return Zo(t,e,r)}function Zo(t,e,r,n,i,o){if(jo({privateKey:Go,chainCode:Go},{privateKey:t,chainCode:e}),r=r||Wo,!Fo.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new Yo(t,void 0,e,r,n,i,o)}function Qo(t,e,r,n,i,o){if(jo({publicKey:jo.BufferN(33),chainCode:Go},{publicKey:t,chainCode:e}),r=r||Wo,!Fo.isPoint(t))throw new TypeError("Point is not on the curve");return new Yo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Ho.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Wo;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Zo(r.slice(46,78),u,e,i,s,o)}else{a=Qo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Jo,Ot.fromPublicKey=function(t,e,r){return Qo(t,e,r)},Ot.fromSeed=function(t,e){if(jo(jo.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Wo;const r=Do.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Jo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var ts=Ot;Tt.fromSeed=ts.fromSeed,Tt.fromBase58=ts.fromBase58,Tt.fromPublicKey=ts.fromPublicKey,Tt.fromPrivateKey=ts.fromPrivateKey;var es={},rs={};Object.defineProperty(rs,"__esModule",{value:!0}),rs.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},rs.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},rs.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ns={},is={},os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0}),ss.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var us={},as={};Object.defineProperty(as,"__esModule",{value:!0});const hs=xo,fs=Math.pow(2,31)-1;function cs(t){return hs.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}as.UInt31=function(t){return hs.UInt32(t)&&t<=fs},as.BIP32Path=cs,cs.toJSON=()=>"BIP32 derivation path",as.Signer=function(t){return(hs.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};as.Satoshi=function(t){return hs.UInt53(t)&&t<=21e14},as.ECPoint=hs.quacksLike("Point"),as.Network=hs.compile({messagePrefix:hs.oneOf(hs.Buffer,hs.String),bip32:{public:hs.UInt32,private:hs.UInt32},pubKeyHash:hs.UInt8,scriptHash:hs.UInt8,wif:hs.UInt8}),as.Buffer256bit=hs.BufferN(32),as.Hash160bit=hs.BufferN(20),as.Hash256bit=hs.BufferN(32),as.Number=hs.Number,as.Array=hs.Array,as.Boolean=hs.Boolean,as.String=hs.String,as.Buffer=hs.Buffer,as.Hex=hs.Hex,as.maybe=hs.maybe,as.tuple=hs.tuple,as.UInt8=hs.UInt8,as.UInt32=hs.UInt32,as.Function=hs.Function,as.BufferN=hs.BufferN,as.Null=hs.Null,as.oneOf=hs.oneOf;var ls=f.exports.Buffer;var ps={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=ls.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(us,"__esModule",{value:!0});const ds=as,gs=ps,ms=xo,ys=Buffer.alloc(1,0);function vs(t){let e=0;for(;0===t[e];)++e;return e===t.length?ys:128&(t=t.slice(e))[0]?Buffer.concat([ys,t],1+t.length):t}function ws(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}us.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=gs.decode(t.slice(0,-1)),i=ws(n.r),o=ws(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},us.encode=function(t,e){ms({signature:ds.BufferN(64),hashType:ds.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=vs(t.slice(0,32)),o=vs(t.slice(32,64));return Buffer.concat([gs.encode(i,o),n])};var bs={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},_s=bs;function Es(t){return t<_s.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}var Ss={encodingLength:Es,encode:function(t,e,r){var n=Es(e);return 1===n?t.writeUInt8(e,r):2===n?(t.writeUInt8(_s.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):3===n?(t.writeUInt8(_s.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(_s.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n},decode:function(t,e){var r,n,i=t.readUInt8(e);if(i<_s.OP_PUSHDATA1)r=i,n=1;else if(i===_s.OP_PUSHDATA1){if(e+2>t.length)return null;r=t.readUInt8(e+1),n=2}else if(i===_s.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==_s.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},Is=bs,Ms={};for(var Ts in Is){Ms[Is[Ts]]=Ts}var Os=Ms;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ss,r=us,n=as,i=ps,o=Nt.exports,s=Ss,u=xo;t.OPS=bs;const a=Os,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function m(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function y(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=m,t.toASM=function(t){return p(t)&&(t=m(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=m(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=y,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!y(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(os);var As={};Object.defineProperty(As,"__esModule",{value:!0}),As.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},As.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(is,"__esModule",{value:!0});const Ps=rs,ks=os,Rs=As,Ns=xo,xs=ks.OPS;is.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ns({network:Ns.maybe(Ns.Object),output:Ns.maybe(Ns.Buffer),data:Ns.maybe(Ns.arrayOf(Ns.Buffer))},t);const r={name:"embed",network:t.network||Ps.bitcoin};if(Rs.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Rs.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ns.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Bs={};Object.defineProperty(Bs,"__esModule",{value:!0});const Ls=rs,Us=os,Cs=As,Ds=Us.OPS,Hs=xo,Fs=Nt.exports,js=Ds.OP_RESERVED;function qs(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Bs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Us.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ds.OP_0)}e=Object.assign({validate:!0},e||{}),Hs({network:Hs.maybe(Hs.Object),m:Hs.maybe(Hs.Number),n:Hs.maybe(Hs.Number),output:Hs.maybe(Hs.Buffer),pubkeys:Hs.maybe(Hs.arrayOf(Fs.isPoint)),signatures:Hs.maybe(Hs.arrayOf(r)),input:Hs.maybe(Hs.Buffer)},t);const n={network:t.network||Ls.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Us.decompile(t),n.m=i[0]-js,n.n=i[i.length-2]-js,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Us.compile([].concat(js+t.m,t.pubkeys,js+n.n,Ds.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Us.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Us.compile([Ds.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Hs.Number(i[0]))throw new TypeError("Output is invalid");if(!Hs.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ds.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Fs.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!qs(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ds.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!qs(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});const Ks=rs,Ws=os,Vs=As,$s=xo,zs=Ws.OPS,Xs=Nt.exports;Gs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),$s({network:$s.maybe($s.Object),output:$s.maybe($s.Buffer),pubkey:$s.maybe(Xs.isPoint),signature:$s.maybe(Ws.isCanonicalScriptSignature),input:$s.maybe($s.Buffer)},t);const r=Vs.value((()=>Ws.decompile(t.input))),n={name:"p2pk",network:t.network||Ks.bitcoin};if(Vs.prop(n,"output",(()=>{if(t.pubkey)return Ws.compile([t.pubkey,zs.OP_CHECKSIG])})),Vs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Vs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Vs.prop(n,"input",(()=>{if(t.signature)return Ws.compile([t.signature])})),Vs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==zs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!Xs.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Ws.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var Ys={},Js={};Object.defineProperty(Js,"__esModule",{value:!0});const Zs=h;function Qs(t){try{return Zs("rmd160").update(t).digest()}catch(e){return Zs("ripemd160").update(t).digest()}}function tu(t){return Zs("sha256").update(t).digest()}Js.ripemd160=Qs,Js.sha1=function(t){return Zs("sha1").update(t).digest()},Js.sha256=tu,Js.hash160=function(t){return Qs(tu(t))},Js.hash256=function(t){return tu(tu(t))},Object.defineProperty(Ys,"__esModule",{value:!0});const eu=Js,ru=rs,nu=os,iu=As,ou=xo,su=nu.OPS,uu=Nt.exports,au=vt;Ys.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ou({network:ou.maybe(ou.Object),address:ou.maybe(ou.String),hash:ou.maybe(ou.BufferN(20)),output:ou.maybe(ou.BufferN(25)),pubkey:ou.maybe(uu.isPoint),signature:ou.maybe(nu.isCanonicalScriptSignature),input:ou.maybe(ou.Buffer)},t);const r=iu.value((()=>{const e=au.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=iu.value((()=>nu.decompile(t.input))),i=t.network||ru.bitcoin,o={name:"p2pkh",network:i};if(iu.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),au.encode(t)})),iu.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?eu.hash160(t.pubkey||o.pubkey):void 0)),iu.prop(o,"output",(()=>{if(o.hash)return nu.compile([su.OP_DUP,su.OP_HASH160,o.hash,su.OP_EQUALVERIFY,su.OP_CHECKSIG])})),iu.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),iu.prop(o,"signature",(()=>{if(t.input)return n()[0]})),iu.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return nu.compile([t.signature,t.pubkey])})),iu.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==su.OP_DUP||t.output[1]!==su.OP_HASH160||20!==t.output[2]||t.output[23]!==su.OP_EQUALVERIFY||t.output[24]!==su.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=eu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!nu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!uu.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=eu.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var hu={};Object.defineProperty(hu,"__esModule",{value:!0});const fu=Js,cu=rs,lu=os,pu=As,du=xo,gu=lu.OPS,mu=vt;hu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),du({network:du.maybe(du.Object),address:du.maybe(du.String),hash:du.maybe(du.BufferN(20)),output:du.maybe(du.BufferN(23)),redeem:du.maybe({network:du.maybe(du.Object),output:du.maybe(du.Buffer),input:du.maybe(du.Buffer),witness:du.maybe(du.arrayOf(du.Buffer))}),input:du.maybe(du.Buffer),witness:du.maybe(du.arrayOf(du.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||cu.bitcoin);const n={network:r},i=pu.value((()=>{const e=mu.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=pu.value((()=>lu.decompile(t.input))),s=pu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:lu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(pu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),mu.encode(t)})),pu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?fu.hash160(n.redeem.output):void 0)),pu.prop(n,"output",(()=>{if(n.hash)return lu.compile([gu.OP_HASH160,n.hash,gu.OP_EQUAL])})),pu.prop(n,"redeem",(()=>{if(t.input)return s()})),pu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return lu.compile([].concat(lu.decompile(t.redeem.input),t.redeem.output))})),pu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),pu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==gu.OP_HASH160||20!==t.output[1]||t.output[22]!==gu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=lu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=fu.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=lu.decompile(t.input);if(!lu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var yu={},vu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",wu={},bu=0;bu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Su(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Eu(e)^n>>5}for(e=Eu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Su(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Mu(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Su(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=Eu(n)^s,i+=vu.charAt(s)}for(o=0;o<6;++o)n=Eu(n);for(n^=1,o=0;o<6;++o){i+=vu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Mu(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Mu(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Mu(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Mu(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(yu,"__esModule",{value:!0});const Ou=Js,Au=rs,Pu=os,ku=As,Ru=xo,Nu=Pu.OPS,xu=Nt.exports,Bu=Tu,Lu=Buffer.alloc(0);yu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ru({address:Ru.maybe(Ru.String),hash:Ru.maybe(Ru.BufferN(20)),input:Ru.maybe(Ru.BufferN(0)),network:Ru.maybe(Ru.Object),output:Ru.maybe(Ru.BufferN(22)),pubkey:Ru.maybe(xu.isPoint),signature:Ru.maybe(Pu.isCanonicalScriptSignature),witness:Ru.maybe(Ru.arrayOf(Ru.Buffer))},t);const r=ku.value((()=>{const e=Bu.decode(t.address),r=e.words.shift(),n=Bu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Au.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Bu.toWords(i.hash);return t.unshift(0),Bu.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Ou.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Pu.compile([Nu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Lu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Nu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Ou.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Pu.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Ou.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Uu={};Object.defineProperty(Uu,"__esModule",{value:!0});const Cu=Js,Du=rs,Hu=os,Fu=As,ju=xo,qu=Hu.OPS,Gu=Nt.exports,Ku=Tu,Wu=Buffer.alloc(0);function Vu(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Gu.isPoint(t))}Uu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ju({network:ju.maybe(ju.Object),address:ju.maybe(ju.String),hash:ju.maybe(ju.BufferN(32)),output:ju.maybe(ju.BufferN(34)),redeem:ju.maybe({input:ju.maybe(ju.Buffer),network:ju.maybe(ju.Object),output:ju.maybe(ju.Buffer),witness:ju.maybe(ju.arrayOf(ju.Buffer))}),input:ju.maybe(ju.BufferN(0)),witness:ju.maybe(ju.arrayOf(ju.Buffer))},t);const r=Fu.value((()=>{const e=Ku.decode(t.address),r=e.words.shift(),n=Ku.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Fu.value((()=>Hu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Du.bitcoin);const o={network:i};if(Fu.prop(o,"address",(()=>{if(!o.hash)return;const t=Ku.toWords(o.hash);return t.unshift(0),Ku.encode(i.bech32,t)})),Fu.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Fu.prop(o,"output",(()=>{if(o.hash)return Hu.compile([qu.OP_0,o.hash])})),Fu.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Wu,witness:t.witness.slice(0,-1)}})),Fu.prop(o,"input",(()=>{if(o.witness)return Wu})),Fu.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Hu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Wu,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Fu.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==qu.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Hu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Hu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Vu)||t.redeem.output&&(Hu.decompile(t.redeem.output)||[]).some(Vu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Vu)||(Hu.decompile(e)||[]).some(Vu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(ns,"__esModule",{value:!0});const $u=is;ns.embed=$u.p2data;const zu=Bs;ns.p2ms=zu.p2ms;const Xu=Gs;ns.p2pk=Xu.p2pk;const Yu=Ys;ns.p2pkh=Yu.p2pkh;const Ju=hu;ns.p2sh=Ju.p2sh;const Zu=yu;ns.p2wpkh=Zu.p2wpkh;const Qu=Uu;ns.p2wsh=Qu.p2wsh,Object.defineProperty(es,"__esModule",{value:!0});const ta=rs,ea=ns,ra=os,na=as,ia=Tu,oa=vt,sa=xo;function ua(t){const e=oa.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function aa(t){const e=ia.decode(t),r=ia.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}es.fromBase58Check=ua,es.fromBech32=aa,es.toBase58Check=function(t,e){sa(na.tuple(na.Hash160bit,na.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),oa.encode(r)},es.toBech32=function(t,e,r){const n=ia.toWords(t);return n.unshift(e),ia.encode(r,n)},es.fromOutputScript=function(t,e){e=e||ta.bitcoin;try{return ea.p2pkh({output:t,network:e}).address}catch(t){}try{return ea.p2sh({output:t,network:e}).address}catch(t){}try{return ea.p2wpkh({output:t,network:e}).address}catch(t){}try{return ea.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ra.toASM(t)+" has no matching Address")},es.toOutputScript=function(t,e){let r,n;e=e||ta.bitcoin;try{r=ua(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return ea.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return ea.p2sh({hash:r.hash}).output}else{try{n=aa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return ea.p2wpkh({hash:n.data}).output;if(32===n.data.length)return ea.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ha={},fa=a.randomBytes;Object.defineProperty(ha,"__esModule",{value:!0});const ca=rs,la=as,pa=Nt.exports,da=fa,ga=xo,ma=Co,ya=ga.maybe(ga.compile({compressed:la.maybe(la.Boolean),network:la.maybe(la.Network)}));class va{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ca.bitcoin,void 0!==e&&(this.__Q=pa.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=pa.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return ma.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return pa.sign(t,this.__D);{let e=pa.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=pa.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return pa.verify(t,this.publicKey,e)}}function wa(t,e){if(ga(la.Buffer256bit,t),!pa.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return ga(ya,e),new va(t,void 0,e)}ha.fromPrivateKey=wa,ha.fromPublicKey=function(t,e){return ga(pa.isPoint,t),ga(ya,e),new va(void 0,t,e)},ha.fromWIF=function(t,e){const r=ma.decode(t),n=r.version;if(la.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ca.bitcoin,n!==e.wif)throw new Error("Invalid network version");return wa(r.privateKey,{compressed:r.compressed,network:e})},ha.makeRandom=function(t){ga(ya,t),void 0===t&&(t={});const e=t.rng||da;let r;do{r=e(32),ga(la.Buffer256bit,r)}while(!pa.isPrivate(r));return wa(r,t)};var ba={},_a={},Ea=f.exports.Buffer;function Sa(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Ia(t){return Sa(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Ma={encode:function t(e,r,n){if(Sa(e),r||(r=Ea.allocUnsafe(Ia(e))),!Ea.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Ea.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Sa(o),o},encodingLength:Ia};Object.defineProperty(_a,"__esModule",{value:!0});const Ta=as,Oa=xo,Aa=Ma;function Pa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Pa(n+r,9007199254740991),n+r}function Ra(t,e,r){return Pa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}_a.readUInt64LE=ka,_a.writeUInt64LE=Ra,_a.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};_a.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Oa(Ta.tuple(Ta.Buffer,Ta.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Aa.decode(this.buffer,this.offset);return this.offset+=Aa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Ha.encodingLength(this.ins.length)+Ha.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Fa(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Fa(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Ha.encodingLength(e)+t.reduce(((t,e)=>t+Fa(e)),0)}(e.witness)),0):0)}clone(){const t=new $a;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Da(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return Ka;const n=La.compile(La.decompile(e).filter((t=>t!==Ua.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===$a.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===$a.SIGHASH_SINGLE){if(t>=this.outs.length)return Ka;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&$a.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=ja})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ba.hash256(o)}hashForWitnessV0(t,e,r,n){Da(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=Ga,u=Ga,a=Ga;if(n&$a.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ba.hash256(o)),n&$a.SIGHASH_ANYONECANPAY||(31&n)===$a.SIGHASH_SINGLE||(31&n)===$a.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ba.hash256(o)),(31&n)!==$a.SIGHASH_SINGLE&&(31&n)!==$a.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Fa(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ba.hash256(o)}else if((31&n)===$a.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}$a.DEFAULT_SEQUENCE=4294967295,$a.SIGHASH_ALL=1,$a.SIGHASH_NONE=2,$a.SIGHASH_SINGLE=3,$a.SIGHASH_ANYONECANPAY=128,$a.ADVANCED_TRANSACTION_MARKER=0,$a.ADVANCED_TRANSACTION_FLAG=1,Na.Transaction=$a;Object.defineProperty(ba,"__esModule",{value:!0});const za=_a,Xa=Js,Ya=Na,Ja=as,Za=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=Ya.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Qa([{getHash:Ja.Function}],t),0===t.length)throw eh;if(e&&!ih(t))throw rh;const r=t.map((t=>t.getHash(e))),n=Za(r,Xa.hash256);return e?Xa.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ih(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+th.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return Xa.hash256(this.toBuffer(!0))}getId(){return za.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new za.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(th.encode(this.transactions.length,e,r.offset),r.offset+=th.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=za.reverseBuffer(this.getHash()),e=nh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw eh;const t=nh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw eh;if(!this.hasWitnessCommit())throw rh;const t=nh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ih(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ba.Block=nh;var oh={},sh={},uh={},ah={},hh={},fh={},ch={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(ch);var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=ch;lh.decode=function(t){if(t.key[0]!==ph.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},lh.encode=function(t){const e=Buffer.from([ph.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},lh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",lh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},lh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=ch;dh.encode=function(t){return{key:Buffer.from([gh.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const yh=ch;mh.decode=function(t){if(t.key[0]!==yh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([yh.InputTypes.FINAL_SCRIPTSIG]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var vh={};Object.defineProperty(vh,"__esModule",{value:!0});const wh=ch;vh.decode=function(t){if(t.key[0]!==wh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},vh.encode=function(t){return{key:Buffer.from([wh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},vh.expected="Buffer",vh.check=function(t){return Buffer.isBuffer(t)},vh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const _h=ch;bh.decode=function(t){if(t.key[0]!==_h.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},bh.encode=function(t){return{key:Buffer.from([_h.InputTypes.NON_WITNESS_UTXO]),value:t}},bh.expected="Buffer",bh.check=function(t){return Buffer.isBuffer(t)},bh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0});const Sh=ch;Eh.decode=function(t){if(t.key[0]!==Sh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Eh.encode=function(t){const e=Buffer.from([Sh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},Eh.expected="{ pubkey: Buffer; signature: Buffer; }",Eh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Eh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Mh=ch;Ih.decode=function(t){if(t.key[0]!==Mh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},Ih.encode=function(t){return{key:Buffer.from([Mh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},Ih.expected="string",Ih.check=function(t){return"string"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Th={};Object.defineProperty(Th,"__esModule",{value:!0});const Oh=ch;Th.decode=function(t){if(t.key[0]!==Oh.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Th.encode=function(t){const e=Buffer.from([Oh.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Th.expected="number",Th.check=function(t){return"number"==typeof t},Th.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ah={},Ph={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Rh(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Nh(t){return Rh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Rh(e),r||(r=Buffer.allocUnsafe(Nh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Rh(i),i}},kh.encodingLength=Nh,Object.defineProperty(Ph,"__esModule",{value:!0});const xh=kh;function Bh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Lh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ph.range=t=>[...Array(t).keys()],Ph.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Fh={};Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var qh={};Object.defineProperty(qh,"__esModule",{value:!0}),qh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(fh,"__esModule",{value:!0});const Gh=ch,Kh=mh,Wh=vh,Vh=bh,$h=Eh,zh=Ih,Xh=Th,Yh=Ah,Jh=Hh,Zh=Fh,Qh=jh,tf=qh,ef={unsignedTx:dh,globalXpub:lh,checkPubkey:Zh.makeChecker([])};fh.globals=ef;const rf={nonWitnessUtxo:Vh,partialSig:$h,sighashType:Xh,finalScriptSig:Kh,finalScriptWitness:Wh,porCommitment:zh,witnessUtxo:Yh,bip32Derivation:Jh.makeConverter(Gh.InputTypes.BIP32_DERIVATION),redeemScript:Qh.makeConverter(Gh.InputTypes.REDEEM_SCRIPT),witnessScript:tf.makeConverter(Gh.InputTypes.WITNESS_SCRIPT),checkPubkey:Zh.makeChecker([Gh.InputTypes.PARTIAL_SIG,Gh.InputTypes.BIP32_DERIVATION])};fh.inputs=rf;const nf={bip32Derivation:Jh.makeConverter(Gh.OutputTypes.BIP32_DERIVATION),redeemScript:Qh.makeConverter(Gh.OutputTypes.REDEEM_SCRIPT),witnessScript:tf.makeConverter(Gh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Zh.makeChecker([Gh.OutputTypes.BIP32_DERIVATION])};fh.outputs=nf,Object.defineProperty(hh,"__esModule",{value:!0});const of=fh,sf=Ph,uf=kh,af=ch;function hf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function ff(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case af.GlobalTypes.UNSIGNED_TX:if(hf("global",t.key,af.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case af.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(of.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of sf.range(s)){const e={};for(const n of r[t])switch(of.inputs.checkPubkey(n),n.key[0]){case af.InputTypes.NON_WITNESS_UTXO:if(hf("input",n.key,af.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=of.inputs.nonWitnessUtxo.decode(n);break;case af.InputTypes.WITNESS_UTXO:if(hf("input",n.key,af.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=of.inputs.witnessUtxo.decode(n);break;case af.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(of.inputs.partialSig.decode(n));break;case af.InputTypes.SIGHASH_TYPE:if(hf("input",n.key,af.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=of.inputs.sighashType.decode(n);break;case af.InputTypes.REDEEM_SCRIPT:if(hf("input",n.key,af.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=of.inputs.redeemScript.decode(n);break;case af.InputTypes.WITNESS_SCRIPT:if(hf("input",n.key,af.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=of.inputs.witnessScript.decode(n);break;case af.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(of.inputs.bip32Derivation.decode(n));break;case af.InputTypes.FINAL_SCRIPTSIG:hf("input",n.key,af.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=of.inputs.finalScriptSig.decode(n);break;case af.InputTypes.FINAL_SCRIPTWITNESS:hf("input",n.key,af.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=of.inputs.finalScriptWitness.decode(n);break;case af.InputTypes.POR_COMMITMENT:hf("input",n.key,af.InputTypes.POR_COMMITMENT),e.porCommitment=of.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of sf.range(u)){const e={};for(const r of n[t])switch(of.outputs.checkPubkey(r),r.key[0]){case af.OutputTypes.REDEEM_SCRIPT:if(hf("output",r.key,af.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=of.outputs.redeemScript.decode(r);break;case af.OutputTypes.WITNESS_SCRIPT:if(hf("output",r.key,af.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=of.outputs.witnessScript.decode(r);break;case af.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(of.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}hh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=uf.decode(t,r);r+=uf.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===af.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of sf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of sf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return ff(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},hh.checkKeyBuffer=hf,hh.psbtFromKeyVals=ff;var cf={};Object.defineProperty(cf,"__esModule",{value:!0});const lf=fh,pf=Ph;cf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=mf({globalMap:t,inputs:e,outputs:r}),s=pf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(pf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const df=(t,e)=>t.key.compare(e.key);function gf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(df)}function mf({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:gf(t,lf.globals),inputKeyVals:e.map((t=>gf(t,lf.inputs))),outputKeyVals:r.map((t=>gf(t,lf.outputs)))}}cf.psbtToKeyVals=mf,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(hh),e(cf)}(ah),Object.defineProperty(uh,"__esModule",{value:!0});const yf=ah;function vf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function wf(t){return t.globalMap.unsignedTx}function bf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}uh.combine=function(t){const e=t[0],r=yf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=wf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=bf(r.globalKeyVals),s=r.inputKeyVals.map(bf),u=r.outputKeyVals.map(bf);for(const t of n){const e=wf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=yf.psbtToKeyVals(t);bf(n.globalKeyVals).forEach(vf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(bf).forEach(((t,e)=>t.forEach(vf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(bf).forEach(((t,e)=>t.forEach(vf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return yf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var _f={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fh;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(_f),Object.defineProperty(sh,"__esModule",{value:!0});const Ef=uh,Sf=ah,If=ch,Mf=_f;sh.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Sf.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Sf.psbtToBuffer(this)}updateGlobal(t){return Mf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Mf.checkForInput(this.inputs,t);return Mf.updateInput(e,r),this}updateOutput(t,e){const r=Mf.checkForOutput(this.outputs,t);return Mf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Mf.checkHasKey(t,this.globalMap.unknownKeyVals,Mf.getEnumLength(If.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Mf.checkForInput(this.inputs,t);return Mf.checkHasKey(e,r.unknownKeyVals,Mf.getEnumLength(If.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Mf.checkForOutput(this.outputs,t);return Mf.checkHasKey(e,r.unknownKeyVals,Mf.getEnumLength(If.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Mf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Mf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Mf.checkForInput(this.inputs,t);Mf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=Ef.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(oh,"__esModule",{value:!0});const Tf=sh,Of=kh,Af=_f,Pf=es,kf=_a,Rf=Js,Nf=ha,xf=ns,Bf=os,Lf=Na,Uf={network:rs.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new Tf.Psbt(new Hf)){this.data=e,this.opts=Object.assign({},Uf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=Tf.Psbt.fromBuffer(t,Df),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{tc(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Pf.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Jf(t),this.opts.maximumFeeRate=t}setVersion(t){Jf(t),Zf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Jf(t),Zf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Jf(e),Zf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Zf(this.data.inputs,"addInput"),t.witnessScript&&yc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);tc(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&cc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Zf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Pf.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(qf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return lc(this.data.inputs,r,e,!0),r}getFeeRate(){return ic("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return ic("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Af.checkForInput(this.data.inputs,0),bc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=oc){const r=Af.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=pc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||$f(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Bf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Af.checkForInput(this.data.inputs,t),r=mc(dc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Bf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||gc(r)||(n=r,Bf.isCanonicalScriptSignature(n)))return;var n;if(!Bf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=hc(t),r=e[e.length-1];if(gc(r))return;if(!Bf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+wc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=dc(r,e,n),{meaningfulScript:o}=mc(i,r,"input",e.redeemScript,e.witnessScript);return vc(t,o)}(e,Af.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Af.checkForInput(this.data.inputs,t),n=Yf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=mc(i,r,"output",e.redeemScript,e.witnessScript);return vc(t,o)}(e,Af.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Af.checkForOutput(this.data.outputs,t),n=Yf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Af.checkForInput(this.data.inputs,0);return bc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Bf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?uc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Qf(e.pubkey,h,"verify");const f=Nf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Lf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of bc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of bc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Lf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return ac(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=ac(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Lf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of bc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Lf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=sc(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Bf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Lf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=sc(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Bf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Ff(this.__CACHE),this.data.toBuffer()}toHex(){return Ff(this.__CACHE),this.data.toHex()}toBase64(){return Ff(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&yc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&cc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}oh.Psbt=Cf;const Df=t=>new Hf(t);class Hf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Lf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Ff(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function jf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Nf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function qf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Gf(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Kf=Gf(xf.p2ms),Wf=Gf(xf.p2pk),Vf=Gf(xf.p2pkh),$f=Gf(xf.p2wpkh),zf=Gf(xf.p2wsh),Xf=Gf(xf.p2sh);function Yf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Jf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Zf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Bf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Bf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Bf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Bf.signature.decode(t.signature),i=[];n&Lf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Lf.Transaction.SIGHASH_ALL:break;case Lf.Transaction.SIGHASH_SINGLE:case Lf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Qf(t,e,r){if(!vc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function tc(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function ec(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const rc=ec(xf.p2sh,"Redeem script"),nc=ec(xf.p2wsh,"Witness script");function ic(t,e,r,n){if(!r.every(qf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),lc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function oc(t,e,r,n,i,o){const s=wc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return jf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return jf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=fc(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function sc(t,e,r,n,i){const o=Af.checkForInput(t,e),{hash:s,sighashType:u,script:a}=uc(e,o,n,!1,i);return Qf(r,a,"sign"),{hash:s,sighashType:u}}function uc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Lf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Lf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Lf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Lf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Lf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=pc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=mc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if($f(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function ac(t,e,r){const n=Af.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function hc(t){let e=0;function r(){const r=Of.decode(t,e);return e+=Of.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=hc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=pc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function pc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||cc(t,e,r),n[r]}function dc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return pc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function gc(t){return 33===t.length&&Bf.isCanonicalPubKey(t)}function mc(t,e,r,n,i){const o=Xf(t),s=o&&n&&zf(n),u=zf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,rc(e,t,n,r),nc(e,n,i,r),yc(a)):u?(a=i,nc(e,t,i,r),yc(a)):o?(a=n,rc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function yc(t){if($f(t)||Xf(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function vc(t,e){const r=Rf.hash160(t),n=Bf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function wc(t){return $f(t)?"witnesspubkeyhash":Vf(t)?"pubkeyhash":Kf(t)?"multisig":Wf(t)?"pubkey":"nonstandard"}function bc(t){return[...Array(t).keys()]}var _c={},Ec={},Sc={},Ic={};Object.defineProperty(Ic,"__esModule",{value:!0});const Mc=os,Tc=os;function Oc(t){return t===Tc.OPS.OP_0||Mc.isCanonicalScriptSignature(t)}function Ac(t,e){const r=Mc.decompile(t);return!(r.length<2)&&(r[0]===Tc.OPS.OP_0&&(e?r.slice(1).every(Oc):r.slice(1).every(Mc.isCanonicalScriptSignature)))}Ic.check=Ac,Ac.toJSON=()=>"multisig input";var Pc={};Object.defineProperty(Pc,"__esModule",{value:!0});const kc=os,Rc=os,Nc=as,xc=Rc.OPS.OP_RESERVED;function Bc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Rc.OPS.OP_CHECKMULTISIG)return!1;if(!Nc.Number(r[0]))return!1;if(!Nc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Pc.check=Bc,Bc.toJSON=()=>"multi-sig output",Object.defineProperty(Sc,"__esModule",{value:!0});const Lc=Ic;Sc.input=Lc;const Uc=Pc;Sc.output=Uc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Dc=os,Hc=Dc.OPS;function Fc(t){const e=Dc.compile(t);return e.length>1&&e[0]===Hc.OP_RETURN}Cc.check=Fc,Fc.toJSON=()=>"null data output";const jc={check:Fc};Cc.output=jc;var qc={},Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});const Kc=os;function Wc(t){const e=Kc.decompile(t);return 1===e.length&&Kc.isCanonicalScriptSignature(e[0])}Gc.check=Wc,Wc.toJSON=()=>"pubKey input";var Vc={};Object.defineProperty(Vc,"__esModule",{value:!0});const $c=os,zc=os;function Xc(t){const e=$c.decompile(t);return 2===e.length&&$c.isCanonicalPubKey(e[0])&&e[1]===zc.OPS.OP_CHECKSIG}Vc.check=Xc,Xc.toJSON=()=>"pubKey output",Object.defineProperty(qc,"__esModule",{value:!0});const Yc=Gc;qc.input=Yc;const Jc=Vc;qc.output=Jc;var Zc={},Qc={};Object.defineProperty(Qc,"__esModule",{value:!0});const tl=os;function el(t){const e=tl.decompile(t);return 2===e.length&&tl.isCanonicalScriptSignature(e[0])&&tl.isCanonicalPubKey(e[1])}Qc.check=el,el.toJSON=()=>"pubKeyHash input";var rl={};Object.defineProperty(rl,"__esModule",{value:!0});const nl=os,il=os;function ol(t){const e=nl.compile(t);return 25===e.length&&e[0]===il.OPS.OP_DUP&&e[1]===il.OPS.OP_HASH160&&20===e[2]&&e[23]===il.OPS.OP_EQUALVERIFY&&e[24]===il.OPS.OP_CHECKSIG}rl.check=ol,ol.toJSON=()=>"pubKeyHash output",Object.defineProperty(Zc,"__esModule",{value:!0});const sl=Qc;Zc.input=sl;const ul=rl;Zc.output=ul;var al={},hl={},fl={};Object.defineProperty(fl,"__esModule",{value:!0});const cl=os,ll=os;function pl(t){const e=cl.compile(t);return 22===e.length&&e[0]===ll.OPS.OP_0&&20===e[1]}fl.check=pl,pl.toJSON=()=>"Witness pubKeyHash output";var dl={};Object.defineProperty(dl,"__esModule",{value:!0});const gl=os,ml=os;function yl(t){const e=gl.compile(t);return 34===e.length&&e[0]===ml.OPS.OP_0&&32===e[1]}dl.check=yl,yl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(hl,"__esModule",{value:!0});const vl=os,wl=Sc,bl=qc,_l=Zc,El=fl,Sl=dl;function Il(t,e){const r=vl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=vl.decompile(vl.compile(r.slice(0,-1))),o=vl.decompile(n);return!!o&&(!!vl.isPushOnly(i)&&(1===r.length?Sl.check(o)||El.check(o):!(!_l.input.check(i)||!_l.output.check(o))||(!(!wl.input.check(i,e)||!wl.output.check(o))||!(!bl.input.check(i)||!bl.output.check(o)))))}hl.check=Il,Il.toJSON=()=>"scriptHash input";var Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const Tl=os,Ol=os;function Al(t){const e=Tl.compile(t);return 23===e.length&&e[0]===Ol.OPS.OP_HASH160&&20===e[1]&&e[22]===Ol.OPS.OP_EQUAL}Ml.check=Al,Al.toJSON=()=>"scriptHash output",Object.defineProperty(al,"__esModule",{value:!0});const Pl=hl;al.input=Pl;const kl=Ml;al.output=kl;var Rl={},Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const xl=os,Bl=os,Ll=as,Ul=xo,Cl=Buffer.from("aa21a9ed","hex");function Dl(t){const e=xl.compile(t);return e.length>37&&e[0]===Bl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Nl.check=Dl,Dl.toJSON=()=>"Witness commitment output",Nl.encode=function(t){Ul(Ll.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Bl.OPS.OP_RETURN,e])},Nl.decode=function(t){return Ul(Dl,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Rl,"__esModule",{value:!0});const Hl=Nl;Rl.output=Hl;var Fl={},jl={};Object.defineProperty(jl,"__esModule",{value:!0});const ql=os;function Gl(t){const e=ql.decompile(t);return 2===e.length&&ql.isCanonicalScriptSignature(e[0])&&function(t){return ql.isCanonicalPubKey(t)&&33===t.length}(e[1])}jl.check=Gl,Gl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Fl,"__esModule",{value:!0});const Kl=jl;Fl.input=Kl;const Wl=fl;Fl.output=Wl;var Vl={},$l={};Object.defineProperty($l,"__esModule",{value:!0});const zl=os,Xl=xo,Yl=Sc,Jl=qc,Zl=Zc;function Ql(t,e){if(Xl(Xl.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=zl.decompile(r);if(!n||0===n.length)return!1;const i=zl.compile(t.slice(0,-1));return!(!Zl.input.check(i)||!Zl.output.check(n))||(!(!Yl.input.check(i,e)||!Yl.output.check(n))||!(!Jl.input.check(i)||!Jl.output.check(n)))}$l.check=Ql,Ql.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Vl,"__esModule",{value:!0});const tp=$l;Vl.input=tp;const ep=dl;Vl.output=ep,Object.defineProperty(Ec,"__esModule",{value:!0});const rp=os,np=Sc,ip=Cc,op=qc,sp=Zc,up=al,ap=Rl,hp=Fl,fp=Vl,cp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Ec.types=cp,Ec.output=function(t){if(hp.output.check(t))return cp.P2WPKH;if(fp.output.check(t))return cp.P2WSH;if(sp.output.check(t))return cp.P2PKH;if(up.output.check(t))return cp.P2SH;const e=rp.decompile(t);if(!e)throw new TypeError("Invalid script");return np.output.check(e)?cp.P2MS:op.output.check(e)?cp.P2PK:ap.output.check(e)?cp.WITNESS_COMMITMENT:ip.output.check(e)?cp.NULLDATA:cp.NONSTANDARD},Ec.input=function(t,e){const r=rp.decompile(t);if(!r)throw new TypeError("Invalid script");return sp.input.check(r)?cp.P2PKH:up.input.check(r,e)?cp.P2SH:np.input.check(r,e)?cp.P2MS:op.input.check(r)?cp.P2PK:cp.NONSTANDARD},Ec.witness=function(t,e){const r=rp.decompile(t);if(!r)throw new TypeError("Invalid script");return hp.input.check(r)?cp.P2WPKH:fp.input.check(r,e)?cp.P2WSH:cp.NONSTANDARD},Object.defineProperty(_c,"__esModule",{value:!0});const lp=es,pp=_a,dp=Ec,gp=Js,mp=ha,yp=rs,vp=ns,wp=os,bp=os,_p=Na,Ep=as,Sp=xo,Ip=dp.types,Mp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Tp(t,e,r){try{Sp(t,e)}catch(t){throw new Error(r)}}class Op{constructor(t=yp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new _p.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Op(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==Ip.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=mp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=wp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Sp(Sp.maybe(Sp.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Sp(Ep.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Sp(Ep.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=pp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof _p.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=lp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=wp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Mp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Tp(Sp.Number,e.vin,"sign must include vin parameter as Number (input index)"),Tp(Ep.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Tp(Sp.maybe(Sp.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.Buffer,e.witnessScript,`${n} requires witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.Buffer,e.witnessScript,`${n} requires witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires witnessScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||_p.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Rp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Sp(Ep.Satoshi,a),l.value=a}if(!Rp(l)){const t=function(t,e,r,n){if(r&&n){const i=vp.p2wsh({redeem:{output:n}}),o=vp.p2wsh({output:r}),s=vp.p2sh({redeem:{output:r}}),u=vp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Pp(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+wp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===Ip.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:Ip.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:Ip.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=vp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=vp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Pp(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+wp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===Ip.P2WPKH&&(o=vp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:Ip.P2SH,prevOutScript:n.output,hasWitness:i.type===Ip.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=vp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=vp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Pp(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+wp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===Ip.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:Ip.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===Ip.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===Ip.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Pp(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+wp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===Ip.P2WPKH&&(n=vp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===Ip.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=vp.p2pkh({pubkey:e}).output;return{prevOutType:Ip.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:Ip.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Rp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(_p.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Ap(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Pp(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||dp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===Ip.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Np(t)&_p.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===_p.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Np(t)&_p.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Np(r);return n===_p.Transaction.SIGHASH_NONE||n===_p.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Ap(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=dp.input(t,!0),i=dp.witness(e,!0);n===Ip.NONSTANDARD&&(n=void 0),i===Ip.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case Ip.P2WPKH:{const{output:t,pubkey:r,signature:n}=vp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:Ip.P2WPKH,pubkeys:[r],signatures:[n]}}case Ip.P2PKH:{const{output:e,pubkey:r,signature:n}=vp.p2pkh({input:t});return{prevOutScript:e,prevOutType:Ip.P2PKH,pubkeys:[r],signatures:[n]}}case Ip.P2PK:{const{signature:e}=vp.p2pk({input:t});return{prevOutType:Ip.P2PK,pubkeys:[void 0],signatures:[e]}}case Ip.P2MS:{const{m:e,pubkeys:r,signatures:i}=vp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:Ip.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===Ip.P2SH){const{output:r,redeem:n}=vp.p2sh({input:t,witness:e}),i=dp.output(n.output),o=Ap(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:Ip.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===Ip.P2WSH){const{output:r,redeem:n}=vp.p2wsh({input:t,witness:e}),i=dp.output(n.output);let o;return o=i===Ip.P2WPKH?Ap(n.input,n.witness,i):Ap(wp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:Ip.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:Ip.NONSTANDARD,prevOutScript:t}}function Pp(t,e){Sp(Ep.Buffer,t);const r=dp.output(t);switch(r){case Ip.P2PKH:{if(!e)return{type:r};const n=vp.p2pkh({output:t}).hash,i=gp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case Ip.P2WPKH:{if(!e)return{type:r};const n=vp.p2wpkh({output:t}).hash,i=gp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case Ip.P2PK:return{type:r,pubkeys:[vp.p2pk({output:t}).pubkey],signatures:[void 0]};case Ip.P2MS:{const e=vp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case Ip.P2PKH:if(0===n.length)break;if(0===i.length)break;return vp.p2pkh({pubkey:n[0],signature:i[0]});case Ip.P2WPKH:if(0===n.length)break;if(0===i.length)break;return vp.p2wpkh({pubkey:n[0],signature:i[0]});case Ip.P2PK:if(0===n.length)break;if(0===i.length)break;return vp.p2pk({signature:i[0]});case Ip.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||bp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return vp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case Ip.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return vp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case Ip.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return vp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Rp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Np(t){return t.readUInt8(t.length-1)}_c.TransactionBuilder=Op,Object.defineProperty(Mt,"__esModule",{value:!0});const xp=Tt;Mt.bip32=xp;const Bp=es;Mt.address=Bp;const Lp=Js;var Up=Mt.crypto=Lp;const Cp=ha;Mt.ECPair=Cp;const Dp=rs;Mt.networks=Dp;const Hp=ns;Mt.payments=Hp;const Fp=os;Mt.script=Fp;var jp=ba;Mt.Block=jp.Block;var qp=oh;Mt.Psbt=qp.Psbt;var Gp=os;Mt.opcodes=Gp.OPS;var Kp=Na;Mt.Transaction=Kp.Transaction;var Wp=_c;Mt.TransactionBuilder=Wp.TransactionBuilder;var Vp={exports:{}};var $p={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var zp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=$p,n=zp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Vp,Vp.exports);const Xp=["includePrerelease","loose","rtl"];var Yp=t=>t?"object"!=typeof t?{loose:!0}:Xp.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Jp=/^[0-9]+$/,Zp=(t,e)=>{const r=Jp.test(t),n=Jp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tZp(e,t)};const td=zp,{MAX_LENGTH:ed,MAX_SAFE_INTEGER:rd}=$p,{re:nd,t:id}=Vp.exports,od=Yp,{compareIdentifiers:sd}=Qp;class ud{constructor(t,e){if(e=od(e),t instanceof ud){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>ed)throw new TypeError(`version is longer than ${ed} characters`);td("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?nd[id.LOOSE]:nd[id.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>rd||this.major<0)throw new TypeError("Invalid major version");if(this.minor>rd||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>rd||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var ad=ud;const{MAX_LENGTH:hd}=$p,{re:fd,t:cd}=Vp.exports,ld=ad,pd=Yp;var dd=(t,e)=>{if(e=pd(e),t instanceof ld)return t;if("string"!=typeof t)return null;if(t.length>hd)return null;if(!(e.loose?fd[cd.LOOSE]:fd[cd.FULL]).test(t))return null;try{return new ld(t,e)}catch(t){return null}};const gd=dd;var md=(t,e)=>{const r=gd(t,e);return r?r.version:null};const yd=dd;var vd=(t,e)=>{const r=yd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const wd=ad;var bd=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new wd(t,r).inc(e,n).version}catch(t){return null}};const _d=ad;var Ed=(t,e,r)=>new _d(t,r).compare(new _d(e,r));const Sd=Ed;var Id=(t,e,r)=>0===Sd(t,e,r);const Md=dd,Td=Id;var Od=(t,e)=>{if(Td(t,e))return null;{const r=Md(t),n=Md(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Ad=ad;var Pd=(t,e)=>new Ad(t,e).major;const kd=ad;var Rd=(t,e)=>new kd(t,e).minor;const Nd=ad;var xd=(t,e)=>new Nd(t,e).patch;const Bd=dd;var Ld=(t,e)=>{const r=Bd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Ud=Ed;var Cd=(t,e,r)=>Ud(e,t,r);const Dd=Ed;var Hd=(t,e)=>Dd(t,e,!0);const Fd=ad;var jd=(t,e,r)=>{const n=new Fd(t,r),i=new Fd(e,r);return n.compare(i)||n.compareBuild(i)};const qd=jd;var Gd=(t,e)=>t.sort(((t,r)=>qd(t,r,e)));const Kd=jd;var Wd=(t,e)=>t.sort(((t,r)=>Kd(r,t,e)));const Vd=Ed;var $d=(t,e,r)=>Vd(t,e,r)>0;const zd=Ed;var Xd=(t,e,r)=>zd(t,e,r)<0;const Yd=Ed;var Jd=(t,e,r)=>0!==Yd(t,e,r);const Zd=Ed;var Qd=(t,e,r)=>Zd(t,e,r)>=0;const tg=Ed;var eg=(t,e,r)=>tg(t,e,r)<=0;const rg=Id,ng=Jd,ig=$d,og=Qd,sg=Xd,ug=eg;var ag=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return rg(t,r,n);case"!=":return ng(t,r,n);case">":return ig(t,r,n);case">=":return og(t,r,n);case"<":return sg(t,r,n);case"<=":return ug(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const hg=ad,fg=dd,{re:cg,t:lg}=Vp.exports;var pg=(t,e)=>{if(t instanceof hg)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=cg[lg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),cg[lg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;cg[lg.COERCERTL].lastIndex=-1}else r=t.match(cg[lg.COERCE]);return null===r?null:fg(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},dg=gg;function gg(t){var e=this;if(e instanceof gg||(e=new gg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},gg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},gg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},gg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},gg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new gg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},gg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Ng=(t,e,r)=>{const n=t[Pg].get(e);if(n){const e=n.value;if(xg(t,e)){if(Lg(t,n),!t[Ig])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Ag].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Mg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Mg]&&r>t[Mg]},Bg=t=>{if(t[Eg]>t[_g])for(let e=t[Ag].tail;t[Eg]>t[_g]&&null!==e;){const r=e.prev;Lg(t,e),e=r}},Lg=(t,e)=>{if(e){const r=e.value;t[Tg]&&t[Tg](r.key,r.value),t[Eg]-=r.length,t[Pg].delete(r.key),t[Ag].removeNode(e)}};class Ug{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Lg(t,r),t[Ig]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Dg=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[_g]=t.max||1/0;const e=t.length||Rg;if(this[Sg]="function"!=typeof e?Rg:e,this[Ig]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Mg]=t.maxAge||0,this[Tg]=t.dispose,this[Og]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[_g]=t||1/0,Bg(this)}get max(){return this[_g]}set allowStale(t){this[Ig]=!!t}get allowStale(){return this[Ig]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Mg]=t,Bg(this)}get maxAge(){return this[Mg]}set lengthCalculator(t){"function"!=typeof t&&(t=Rg),t!==this[Sg]&&(this[Sg]=t,this[Eg]=0,this[Ag].forEach((t=>{t.length=this[Sg](t.value,t.key),this[Eg]+=t.length}))),Bg(this)}get lengthCalculator(){return this[Sg]}get length(){return this[Eg]}get itemCount(){return this[Ag].length}rforEach(t,e){e=e||this;for(let r=this[Ag].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Ag].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Ag].toArray().map((t=>t.key))}values(){return this[Ag].toArray().map((t=>t.value))}reset(){this[Tg]&&this[Ag]&&this[Ag].length&&this[Ag].forEach((t=>this[Tg](t.key,t.value))),this[Pg]=new Map,this[Ag]=new bg,this[Eg]=0}dump(){return this[Ag].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Ag]}set(t,e,r){if((r=r||this[Mg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Sg](e,t);if(this[Pg].has(t)){if(i>this[_g])return Lg(this,this[Pg].get(t)),!1;const o=this[Pg].get(t).value;return this[Tg]&&(this[Og]||this[Tg](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Eg]+=i-o.length,o.length=i,this.get(t),Bg(this),!0}const o=new Ug(t,e,i,n,r);return o.length>this[_g]?(this[Tg]&&this[Tg](t,e),!1):(this[Eg]+=o.length,this[Ag].unshift(o),this[Pg].set(t,this[Ag].head),Bg(this),!0)}has(t){if(!this[Pg].has(t))return!1;const e=this[Pg].get(t).value;return!xg(this,e)}get(t){return Ng(this,t,!0)}peek(t){return Ng(this,t,!1)}pop(){const t=this[Ag].tail;return t?(Lg(this,t),t.value):null}del(t){Lg(this,this[Pg].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Pg].forEach(((t,e)=>Ng(this,e,!1)))}};class Hg{constructor(t,e){if(e=qg(e),t instanceof Hg)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Hg(t.raw,e);if(t instanceof Gg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Jg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Zg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=jg.get(e);if(r)return r;const n=this.options.loose,i=n?Vg[$g.HYPHENRANGELOOSE]:Vg[$g.HYPHENRANGE];t=t.replace(i,fm(this.options.includePrerelease)),Kg("hyphen replace",t),t=t.replace(Vg[$g.COMPARATORTRIM],zg),Kg("comparator trim",t,Vg[$g.COMPARATORTRIM]),t=(t=(t=t.replace(Vg[$g.TILDETRIM],Xg)).replace(Vg[$g.CARETTRIM],Yg)).split(/\s+/).join(" ");const o=n?Vg[$g.COMPARATORLOOSE]:Vg[$g.COMPARATOR],s=t.split(" ").map((t=>tm(t,this.options))).join(" ").split(/\s+/).map((t=>hm(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Gg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Jg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return jg.set(e,a),a}intersects(t,e){if(!(t instanceof Hg))throw new TypeError("a Range is required");return this.set.some((r=>Qg(r,e)&&t.set.some((t=>Qg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Wg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Zg=t=>""===t.value,Qg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},tm=(t,e)=>(Kg("comp",t,e),t=im(t,e),Kg("caret",t),t=rm(t,e),Kg("tildes",t),t=sm(t,e),Kg("xrange",t),t=am(t,e),Kg("stars",t),t),em=t=>!t||"x"===t.toLowerCase()||"*"===t,rm=(t,e)=>t.trim().split(/\s+/).map((t=>nm(t,e))).join(" "),nm=(t,e)=>{const r=e.loose?Vg[$g.TILDELOOSE]:Vg[$g.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Kg("tilde",t,e,r,n,i,o),em(r)?s="":em(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:em(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Kg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Kg("tilde return",s),s}))},im=(t,e)=>t.trim().split(/\s+/).map((t=>om(t,e))).join(" "),om=(t,e)=>{Kg("caret",t,e);const r=e.loose?Vg[$g.CARETLOOSE]:Vg[$g.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Kg("caret",t,e,r,i,o,s),em(r)?u="":em(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:em(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Kg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Kg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Kg("caret return",u),u}))},sm=(t,e)=>(Kg("replaceXRanges",t,e),t.split(/\s+/).map((t=>um(t,e))).join(" ")),um=(t,e)=>{t=t.trim();const r=e.loose?Vg[$g.XRANGELOOSE]:Vg[$g.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Kg("xRange",t,r,n,i,o,s,u);const a=em(i),h=a||em(o),f=h||em(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Kg("xRange return",r),r}))},am=(t,e)=>(Kg("replaceStars",t,e),t.trim().replace(Vg[$g.STAR],"")),hm=(t,e)=>(Kg("replaceGTE0",t,e),t.trim().replace(Vg[e.includePrerelease?$g.GTE0PRE:$g.GTE0],"")),fm=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=em(n)?"":em(i)?`>=${n}.0.0${t?"-0":""}`:em(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=em(h)?"":em(f)?`<${+h+1}.0.0-0`:em(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),cm=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},lm=Symbol("SemVer ANY");class pm{static get ANY(){return lm}constructor(t,e){if(e=gm(e),t instanceof pm){if(t.loose===!!e.loose)return t;t=t.value}wm("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===lm?this.value="":this.value=this.operator+this.semver.version,wm("comp",this)}parse(t){const e=this.options.loose?mm[ym.COMPARATORLOOSE]:mm[ym.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new bm(r[2],this.options.loose):this.semver=lm}toString(){return this.value}test(t){if(wm("Comparator.test",t,this.options.loose),this.semver===lm||t===lm)return!0;if("string"==typeof t)try{t=new bm(t,this.options)}catch(t){return!1}return vm(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof pm))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new _m(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new _m(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=vm(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=vm(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var dm=pm;const gm=Yp,{re:mm,t:ym}=Vp.exports,vm=ag,wm=zp,bm=ad,_m=Fg,Em=Fg;var Sm=(t,e,r)=>{try{e=new Em(e,r)}catch(t){return!1}return e.test(t)};const Im=Fg;var Mm=(t,e)=>new Im(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Tm=ad,Om=Fg;var Am=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Om(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Tm(n,r)))})),n};const Pm=ad,km=Fg;var Rm=(t,e,r)=>{let n=null,i=null,o=null;try{o=new km(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Pm(n,r)))})),n};const Nm=ad,xm=Fg,Bm=$d;var Lm=(t,e)=>{t=new xm(t,e);let r=new Nm("0.0.0");if(t.test(r))return r;if(r=new Nm("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new Nm(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Bm(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Bm(r,i)||(r=i)}return r&&t.test(r)?r:null};const Um=Fg;var Cm=(t,e)=>{try{return new Um(t,e).range||"*"}catch(t){return null}};const Dm=ad,Hm=dm,{ANY:Fm}=Hm,jm=Fg,qm=Sm,Gm=$d,Km=Xd,Wm=eg,Vm=Qd;var $m=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Dm(t,n),e=new jm(e,n),r){case">":i=Gm,o=Wm,s=Km,u=">",a=">=";break;case"<":i=Km,o=Vm,s=Gm,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(qm(t,e,n))return!1;for(let r=0;r{t.semver===Fm&&(t=new Hm(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const zm=$m;var Xm=(t,e,r)=>zm(t,e,">",r);const Ym=$m;var Jm=(t,e,r)=>Ym(t,e,"<",r);const Zm=Fg;var Qm=(t,e,r)=>(t=new Zm(t,r),e=new Zm(e,r),t.intersects(e));const ty=Sm,ey=Ed;const ry=Fg,ny=dm,{ANY:iy}=ny,oy=Sm,sy=Ed,uy=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===iy){if(1===e.length&&e[0].semver===iy)return!0;t=r.includePrerelease?[new ny(">=0.0.0-0")]:[new ny(">=0.0.0")]}if(1===e.length&&e[0].semver===iy){if(r.includePrerelease)return!0;e=[new ny(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=ay(i,e,r):"<"===e.operator||"<="===e.operator?o=hy(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=sy(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!oy(t,String(i),r))return null;if(o&&!oy(t,String(o),r))return null;for(const n of e)if(!oy(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=ay(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!oy(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=hy(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!oy(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},ay=(t,e,r)=>{if(!t)return e;const n=sy(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},hy=(t,e,r)=>{if(!t)return e;const n=sy(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var fy=(t,e,r={})=>{if(t===e)return!0;t=new ry(t,r),e=new ry(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=uy(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const cy=Vp.exports;var ly={re:cy.re,src:cy.src,tokens:cy.t,SEMVER_SPEC_VERSION:$p.SEMVER_SPEC_VERSION,SemVer:ad,compareIdentifiers:Qp.compareIdentifiers,rcompareIdentifiers:Qp.rcompareIdentifiers,parse:dd,valid:md,clean:vd,inc:bd,diff:Od,major:Pd,minor:Rd,patch:xd,prerelease:Ld,compare:Ed,rcompare:Cd,compareLoose:Hd,compareBuild:jd,sort:Gd,rsort:Wd,gt:$d,lt:Xd,eq:Id,neq:Jd,gte:Qd,lte:eg,cmp:ag,coerce:pg,Comparator:dm,Range:Fg,satisfies:Sm,toComparators:Mm,maxSatisfying:Am,minSatisfying:Rm,minVersion:Lm,validRange:Cm,outside:$m,gtr:Xm,ltr:Jm,intersects:Qm,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>ey(t,e,r)));for(const t of s){ty(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Oy(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ay(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Py(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}vy.prototype=Object.create(null),wy.EventEmitter=wy,wy.usingDomains=!1,wy.prototype.domain=void 0,wy.prototype._events=void 0,wy.prototype._maxListeners=void 0,wy.defaultMaxListeners=10,wy.init=function(){this.domain=null,wy.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new vy,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},wy.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},wy.prototype.getMaxListeners=function(){return by(this)},wy.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:_y(r,f,this);break;case 2:Ey(r,f,this,arguments[1]);break;case 3:Sy(r,f,this,arguments[1],arguments[2]);break;case 4:Iy(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new vy,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var ky=Object.freeze({__proto__:null,default:wy,EventEmitter:wy});function Ry(){throw new Error("setTimeout has not been defined")}function Ny(){throw new Error("clearTimeout has not been defined")}var xy=Ry,By=Ny;function Ly(t){if(xy===setTimeout)return setTimeout(t,0);if((xy===Ry||!xy)&&setTimeout)return xy=setTimeout,setTimeout(t,0);try{return xy(t,0)}catch(e){try{return xy.call(null,t,0)}catch(e){return xy.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xy=setTimeout),"function"==typeof global.clearTimeout&&(By=clearTimeout);var Uy,Cy=[],Dy=!1,Hy=-1;function Fy(){Dy&&Uy&&(Dy=!1,Uy.length?Cy=Uy.concat(Cy):Hy=-1,Cy.length&&jy())}function jy(){if(!Dy){var t=Ly(Fy);Dy=!0;for(var e=Cy.length;e;){for(Uy=Cy,Cy=[];++Hy1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),ov(e)?r.showHidden=e:e&&Iv(r,e),cv(r.showHidden)&&(r.showHidden=!1),cv(r.depth)&&(r.depth=2),cv(r.colors)&&(r.colors=!1),cv(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Qy),ev(r,t,r.depth)}function Qy(t,e){var r=Zy.styles[e];return r?"["+Zy.colors[r][0]+"m"+t+"["+Zy.colors[r][1]+"m":t}function tv(t,e){return t}function ev(t,e,r){if(t.customInspect&&e&&mv(e.inspect)&&e.inspect!==Zy&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return hv(n)||(n=ev(t,n,r)),n}var i=function(t,e){if(cv(e))return t.stylize("undefined","undefined");if(hv(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(av(e))return t.stylize(""+e,"number");if(ov(e))return t.stylize(""+e,"boolean");if(sv(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),gv(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return rv(e);if(0===o.length){if(mv(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(lv(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(dv(e))return t.stylize(Date.prototype.toString.call(e),"date");if(gv(e))return rv(e)}var a,h="",f=!1,c=["{","}"];(iv(e)&&(f=!0,c=["[","]"]),mv(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return lv(e)&&(h=" "+RegExp.prototype.toString.call(e)),dv(e)&&(h=" "+Date.prototype.toUTCString.call(e)),gv(e)&&(h=" "+rv(e)),0!==o.length||f&&0!=e.length?r<0?lv(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function rv(t){return"["+Error.prototype.toString.call(t)+"]"}function nv(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Mv(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=sv(r)?ev(t,a.value,null):ev(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),cv(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function iv(t){return Array.isArray(t)}function ov(t){return"boolean"==typeof t}function sv(t){return null===t}function uv(t){return null==t}function av(t){return"number"==typeof t}function hv(t){return"string"==typeof t}function fv(t){return"symbol"==typeof t}function cv(t){return void 0===t}function lv(t){return pv(t)&&"[object RegExp]"===wv(t)}function pv(t){return"object"==typeof t&&null!==t}function dv(t){return pv(t)&&"[object Date]"===wv(t)}function gv(t){return pv(t)&&("[object Error]"===wv(t)||t instanceof Error)}function mv(t){return"function"==typeof t}function yv(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function vv(t){return Buffer.isBuffer(t)}function wv(t){return Object.prototype.toString.call(t)}function bv(t){return t<10?"0"+t.toString(10):t.toString(10)}Zy.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]},Zy.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var _v=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ev(){var t=new Date,e=[bv(t.getHours()),bv(t.getMinutes()),bv(t.getSeconds())].join(":");return[t.getDate(),_v[t.getMonth()],e].join(" ")}function Sv(){console.log("%s - %s",Ev(),$y.apply(null,arguments))}function Iv(t,e){if(!e||!pv(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Mv(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Tv={inherits:Wy,_extend:Iv,log:Sv,isBuffer:vv,isPrimitive:yv,isFunction:mv,isError:gv,isDate:dv,isObject:pv,isRegExp:lv,isUndefined:cv,isSymbol:fv,isString:hv,isNumber:av,isNullOrUndefined:uv,isNull:sv,isBoolean:ov,isArray:iv,inspect:Zy,deprecate:zy,format:$y,debuglog:Jy},Ov=Object.freeze({__proto__:null,format:$y,deprecate:zy,debuglog:Jy,inspect:Zy,isArray:iv,isBoolean:ov,isNull:sv,isNullOrUndefined:uv,isNumber:av,isString:hv,isSymbol:fv,isUndefined:cv,isRegExp:lv,isObject:pv,isDate:dv,isError:gv,isFunction:mv,isPrimitive:yv,isBuffer:vv,log:Sv,inherits:Wy,_extend:Iv,default:Tv});function Av(){this.head=null,this.tail=null,this.length=0}Av.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Av.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Av.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Av.prototype.clear=function(){this.head=this.tail=null,this.length=0},Av.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Av.prototype.concat=function(t){if(0===this.length)return M.alloc(0);if(1===this.length)return this.head.data;for(var e=M.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Pv=M.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function kv(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Pv(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Nv;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xv;break;default:return void(this.write=Rv)}this.charBuffer=new M(6),this.charReceived=0,this.charLength=0}function Rv(t){return t.toString(this.encoding)}function Nv(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xv(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}kv.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},kv.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},kv.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e};var Bv=Object.freeze({__proto__:null,StringDecoder:kv});Cv.ReadableState=Uv;var Lv=Jy("stream");function Uv(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof cw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Av,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new kv(t.encoding),this.encoding=t.encoding)}function Cv(t){if(!(this instanceof Cv))return new Cv(t);this._readableState=new Uv(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),wy.call(this)}function Dv(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,jv(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&jv(t))),function(t,e){e.readingMore||(e.readingMore=!0,qy(Gv,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Hv?t=Hv:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function jv(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Lv("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?qy(qv,t):qv(t))}function qv(t){Lv("emit readable"),t.emit("readable"),Vv(t)}function Gv(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function zv(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,qy(Xv,e,t))}function Xv(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Yv(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Lv("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?zv(this):jv(this),null;if(0===(t=Fv(t,e))&&e.ended)return 0===e.length&&zv(this),null;var n,i=e.needReadable;return Lv("need readable",i),(0===e.length||e.length-t0?$v(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&zv(this)),null!==n&&this.emit("data",n),n},Cv.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Cv.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Lv("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Lv("onunpipe"),t===r&&h()}function s(){Lv("onend"),t.end()}n.endEmitted?qy(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Lv("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Vv(t))}}(r);t.on("drain",u);var a=!1;function h(){Lv("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Lv("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Yv(n.pipes,t))&&!a&&(Lv("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Lv("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Lv("onfinish"),t.removeListener("close",p),g()}function g(){Lv("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Lv("pipe resume"),r.resume()),t},Cv.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},tw.prototype._write=function(t,e,r){r(new Error("not implemented"))},tw.prototype._writev=null,tw.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,sw(t,e),r&&(e.finished?qy(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Wy(cw,Cv);for(var aw=Object.keys(tw.prototype),hw=0;hw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Tw.alloc(0);for(var e=Tw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Pw(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Tw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Aw,value:function(t,e){return Ow(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Cw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Cw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Dw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Dw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Cw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Cw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Cw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Cw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Cw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Cw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Cw("ERR_STREAM_WRITE_AFTER_END","write after end"),Cw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Cw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Cw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Lw.codes=Uw;var Hw=Lw.codes.ERR_INVALID_OPT_VALUE;var Fw,jw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Hw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},qw=Ew.deprecate,Gw=fb;function Kw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}fb.WritableState=hb;var Ww={deprecate:qw},Vw=_w,$w=ft.Buffer,zw=r.Uint8Array||function(){};var Xw,Yw=Bw,Jw=jw.getHighWaterMark,Zw=Lw.codes,Qw=Zw.ERR_INVALID_ARG_TYPE,tb=Zw.ERR_METHOD_NOT_IMPLEMENTED,eb=Zw.ERR_MULTIPLE_CALLBACK,rb=Zw.ERR_STREAM_CANNOT_PIPE,nb=Zw.ERR_STREAM_DESTROYED,ib=Zw.ERR_STREAM_NULL_VALUES,ob=Zw.ERR_STREAM_WRITE_AFTER_END,sb=Zw.ERR_UNKNOWN_ENCODING,ub=Yw.errorOrDestroy;function ab(){}function hb(t,e,r){Fw=Fw||vb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Fw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=Jw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new eb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(mb,t,e),t._writableState.errorEmitted=!0,ub(t,n)):(i(n),t._writableState.errorEmitted=!0,ub(t,n),mb(t,e))}(t,r,n,e,i);else{var o=db(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||pb(t,r),n?process.nextTick(lb,t,r,o,i):lb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new Kw(this)}function fb(t){var e=this instanceof(Fw=Fw||vb);if(!e&&!Xw.call(fb,this))return new fb(t);this._writableState=new hb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Vw.call(this)}function cb(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new nb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function lb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),mb(t,e)}function pb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,cb(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new Kw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(cb(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function db(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function gb(t,e){t._final((function(r){e.pendingcb--,r&&ub(t,r),e.prefinished=!0,t.emit("prefinish"),mb(t,e)}))}function mb(t,e){var r=db(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(gb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}te.exports(fb,Vw),hb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(hb.prototype,"buffer",{get:Ww.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Xw=Function.prototype[Symbol.hasInstance],Object.defineProperty(fb,Symbol.hasInstance,{value:function(t){return!!Xw.call(this,t)||this===fb&&(t&&t._writableState instanceof hb)}})):Xw=function(t){return t instanceof this},fb.prototype.pipe=function(){ub(this,new rb)},fb.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,$w.isBuffer(n)||n instanceof zw);return s&&!$w.isBuffer(t)&&(t=function(t){return $w.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ab),i.ending?function(t,e){var r=new ob;ub(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new ib:"string"==typeof r||e.objectMode||(i=new Qw("chunk",["string","Buffer"],r)),!i||(ub(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=$w.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new sb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(fb.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(fb.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),fb.prototype._write=function(t,e,r){r(new tb("_write()"))},fb.prototype._writev=null,fb.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,mb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(fb.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(fb.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),fb.prototype.destroy=Yw.destroy,fb.prototype._undestroy=Yw.undestroy,fb.prototype._destroy=function(t,e){e(t)};var yb=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},vb=Ib,wb=c_,bb=Gw;te.exports(Ib,wb);for(var _b=yb(bb.prototype),Eb=0;Eb<_b.length;Eb++){var Sb=_b[Eb];Ib.prototype[Sb]||(Ib.prototype[Sb]=bb.prototype[Sb])}function Ib(t){if(!(this instanceof Ib))return new Ib(t);wb.call(this,t),bb.call(this,t),this.allowHalfOpen=!0,t&&(!1===t.readable&&(this.readable=!1),!1===t.writable&&(this.writable=!1),!1===t.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",Mb)))}function Mb(){this._writableState.ended||process.nextTick(Tb,this)}function Tb(t){t.end()}Object.defineProperty(Ib.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Ib.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Ib.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Ib.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}});var Ob={},Ab=f.exports.Buffer,Pb=Ab.isEncoding||function(t){switch((t=""+t)&&t.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!0;default:return!1}};function kb(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){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 t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(Ab.isEncoding===Pb||!Pb(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=xb,this.end=Bb,e=4;break;case"utf8":this.fillLast=Nb,e=4;break;case"base64":this.text=Lb,this.end=Ub,e=3;break;default:return this.write=Cb,void(this.end=Db)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Ab.allocUnsafe(e)}function Rb(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Nb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function xb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function Bb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Lb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Ub(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Cb(t){return t.toString(this.encoding)}function Db(t){return t&&t.length?this.write(t):""}Ob.StringDecoder=kb,kb.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},kb.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Hb=Lw.codes.ERR_STREAM_PREMATURE_CLOSE;function Fb(){}var jb,qb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===d_.prototype||(e=function(t){return d_.from(t)}(e)),n)s.endEmitted?P_(t,new A_):B_(t,s,e,!0);else if(s.ended)P_(t,new T_);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?B_(t,s,e,!1):H_(t,s)):B_(t,s,e,!1)}else n||(s.reading=!1,H_(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=L_?t=L_:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function C_(t){var e=t._readableState;m_("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(m_("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(D_,t))}function D_(t){var e=t._readableState;m_("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,K_(t)}function H_(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(F_,t,e))}function F_(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function q_(t){m_("readable nexttick read 0"),t.read(0)}function G_(t,e){m_("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),K_(t),e.flowing&&!e.reading&&t.read(0)}function K_(t){var e=t._readableState;for(m_("flow",e.flowing);e.flowing&&null!==t.read(););}function W_(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function V_(t){var e=t._readableState;m_("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick($_,e,t))}function $_(t,e){if(m_("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function z_(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return m_("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?V_(this):C_(this),null;if(0===(t=U_(t,e))&&e.ended)return 0===e.length&&V_(this),null;var n,i=e.needReadable;return m_("need readable",i),(0===e.length||e.length-t0?W_(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&V_(this)),null!==n&&this.emit("data",n),n},N_.prototype._read=function(t){P_(this,new O_("_read()"))},N_.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,m_("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){m_("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,m_("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){m_("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;m_("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&l_(t,"data")&&(e.flowing=!0,K_(t))}}(r);t.on("drain",u);var a=!1;function h(e){m_("ondata");var i=t.write(e);m_("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==z_(n.pipes,t))&&!a&&(m_("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){m_("onerror",e),p(),t.removeListener("error",f),0===l_(t,"error")&&P_(t,e)}function c(){t.removeListener("finish",l),p()}function l(){m_("onfinish"),t.removeListener("close",c),p()}function p(){m_("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(m_("pipe resume"),r.resume()),t},N_.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,m_("on readable",n.length,n.reading),n.length?C_(this):n.reading||process.nextTick(q_,this))),r},N_.prototype.addListener=N_.prototype.on,N_.prototype.removeListener=function(t,e){var r=p_.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(j_,this),r},N_.prototype.removeAllListeners=function(t){var e=p_.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(j_,this),e},N_.prototype.resume=function(){var t=this._readableState;return t.flowing||(m_("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(G_,t,e))}(this,t)),t.paused=!1,this},N_.prototype.pause=function(){return m_("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(m_("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},N_.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(m_("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(m_("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(gE),s||(o.forEach(gE),i(n))}))}));return e.reduce(mE)};!function(t,e){var r=ww;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=c_).Stream=r||e,e.Readable=e,e.Writable=Gw,e.Duplex=vb,e.Transform=X_,e.PassThrough=uE,e.finished=qb,e.pipeline=vE)}(yy,yy.exports);var wE=f.exports.Buffer,bE=yy.exports.Transform;function _E(t){bE.call(this),this._block=wE.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,te.exports)(_E,bE),_E.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},_E.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},_E.prototype.update=function(t,e){if(function(t,e){if(!wE.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");wE.isBuffer(t)||(t=wE.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},_E.prototype._update=function(){throw new Error("_update is not implemented")},_E.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},_E.prototype._digest=function(){throw new Error("_digest is not implemented")};var EE=_E,SE=ft.Buffer,IE=te.exports,ME=EE,TE=new Array(16),OE=[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],AE=[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],PE=[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],kE=[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],RE=[0,1518500249,1859775393,2400959708,2840853838],NE=[1352829926,1548603684,1836072691,2053994217,0];function xE(){ME.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function BE(t,e){return t<>>32-e}function LE(t,e,r,n,i,o,s,u){return BE(t+(e^r^n)+o+s|0,u)+i|0}function UE(t,e,r,n,i,o,s,u){return BE(t+(e&r|~e&n)+o+s|0,u)+i|0}function CE(t,e,r,n,i,o,s,u){return BE(t+((e|~r)^n)+o+s|0,u)+i|0}function DE(t,e,r,n,i,o,s,u){return BE(t+(e&n|r&~n)+o+s|0,u)+i|0}function HE(t,e,r,n,i,o,s,u){return BE(t+(e^(r|~n))+o+s|0,u)+i|0}IE(xE,ME),xE.prototype._update=function(){for(var t=TE,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=LE(r,n,i,o,s,t[OE[l]],RE[0],PE[l]),d=HE(u,a,h,f,c,t[AE[l]],NE[0],kE[l])):l<32?(p=UE(r,n,i,o,s,t[OE[l]],RE[1],PE[l]),d=DE(u,a,h,f,c,t[AE[l]],NE[1],kE[l])):l<48?(p=CE(r,n,i,o,s,t[OE[l]],RE[2],PE[l]),d=CE(u,a,h,f,c,t[AE[l]],NE[2],kE[l])):l<64?(p=DE(r,n,i,o,s,t[OE[l]],RE[3],PE[l]),d=UE(u,a,h,f,c,t[AE[l]],NE[3],kE[l])):(p=HE(r,n,i,o,s,t[OE[l]],RE[4],PE[l]),d=LE(u,a,h,f,c,t[AE[l]],NE[4],kE[l])),r=s,s=o,o=BE(i,10),i=n,n=p,u=c,c=f,f=BE(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},xE.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=SE.alloc?SE.alloc(20):new SE(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var FE=xE,jE={exports:{}},qE=f.exports.Buffer;function GE(t,e){this._block=qE.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}GE.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=qE.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},GE.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var KE=GE,WE=te.exports,VE=KE,$E=f.exports.Buffer,zE=[1518500249,1859775393,-1894007588,-899497514],XE=new Array(80);function YE(){this.init(),this._w=XE,VE.call(this,64,56)}function JE(t){return t<<30|t>>>2}function ZE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}WE(YE,VE),YE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},YE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+ZE(f,i,o,s)+u+r[h]+zE[f];u=s,s=o,o=JE(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},YE.prototype._hash=function(){var t=$E.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var QE=YE,tS=te.exports,eS=KE,rS=f.exports.Buffer,nS=[1518500249,1859775393,-1894007588,-899497514],iS=new Array(80);function oS(){this.init(),this._w=iS,eS.call(this,64,56)}function sS(t){return t<<5|t>>>27}function uS(t){return t<<30|t>>>2}function aS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}tS(oS,eS),oS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},oS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=sS(n)+aS(f,i,o,s)+u+r[h]+nS[f]|0;u=s,s=o,o=uS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},oS.prototype._hash=function(){var t=rS.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var hS=oS,fS=te.exports,cS=KE,lS=f.exports.Buffer,pS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],dS=new Array(64);function gS(){this.init(),this._w=dS,cS.call(this,64,56)}function mS(t,e,r){return r^t&(e^r)}function yS(t,e,r){return t&e|r&(t|e)}function vS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function wS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function bS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function _S(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}fS(gS,cS),gS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},gS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=_S(e[f-2])+e[f-7]+bS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+wS(s)+mS(s,u,a)+pS[c]+e[c]|0,p=vS(r)+yS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},gS.prototype._hash=function(){var t=lS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var ES=gS,SS=te.exports,IS=ES,MS=KE,TS=f.exports.Buffer,OS=new Array(64);function AS(){this.init(),this._w=OS,MS.call(this,64,56)}SS(AS,IS),AS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},AS.prototype._hash=function(){var t=TS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var PS=AS,kS=te.exports,RS=KE,NS=f.exports.Buffer,xS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],BS=new Array(160);function LS(){this.init(),this._w=BS,RS.call(this,128,112)}function US(t,e,r){return r^t&(e^r)}function CS(t,e,r){return t&e|r&(t|e)}function DS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function HS(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function FS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function jS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function qS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function GS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function KS(t,e){return t>>>0>>0?1:0}kS(LS,RS),LS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},LS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,m=0|this._gl,y=0|this._hl,v=0;v<32;v+=2)e[v]=t.readInt32BE(4*v),e[v+1]=t.readInt32BE(4*v+4);for(;v<160;v+=2){var w=e[v-30],b=e[v-30+1],_=FS(w,b),E=jS(b,w),S=qS(w=e[v-4],b=e[v-4+1]),I=GS(b,w),M=e[v-14],T=e[v-14+1],O=e[v-32],A=e[v-32+1],P=E+T|0,k=_+M+KS(P,E)|0;k=(k=k+S+KS(P=P+I|0,I)|0)+O+KS(P=P+A|0,A)|0,e[v]=k,e[v+1]=P}for(var R=0;R<160;R+=2){k=e[R],P=e[R+1];var N=CS(r,n,i),x=CS(f,c,l),B=DS(r,f),L=DS(f,r),U=HS(s,d),C=HS(d,s),D=xS[R],H=xS[R+1],F=US(s,u,a),j=US(d,g,m),q=y+C|0,G=h+U+KS(q,y)|0;G=(G=(G=G+F+KS(q=q+j|0,j)|0)+D+KS(q=q+H|0,H)|0)+k+KS(q=q+P|0,P)|0;var K=L+x|0,W=B+N+KS(K,L)|0;h=a,y=m,a=u,m=g,u=s,g=d,s=o+G+KS(d=p+q|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+W+KS(f=q+K|0,q)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+m|0,this._hl=this._hl+y|0,this._ah=this._ah+r+KS(this._al,f)|0,this._bh=this._bh+n+KS(this._bl,c)|0,this._ch=this._ch+i+KS(this._cl,l)|0,this._dh=this._dh+o+KS(this._dl,p)|0,this._eh=this._eh+s+KS(this._el,d)|0,this._fh=this._fh+u+KS(this._fl,g)|0,this._gh=this._gh+a+KS(this._gl,m)|0,this._hh=this._hh+h+KS(this._hl,y)|0},LS.prototype._hash=function(){var t=NS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var WS=LS,VS=te.exports,$S=WS,zS=KE,XS=f.exports.Buffer,YS=new Array(160);function JS(){this.init(),this._w=YS,zS.call(this,128,112)}VS(JS,$S),JS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},JS.prototype._hash=function(){var t=XS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var ZS=JS,QS=jE.exports=function(t){t=t.toLowerCase();var e=QS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};QS.sha=QE,QS.sha1=hS,QS.sha224=PS,QS.sha256=ES,QS.sha384=ZS,QS.sha512=WS;var tI=jE.exports;function eI(t){return(new FE).update(tI("sha256").update(t).digest()).digest()}var rI,nI=(rI=function(t,e){return rI=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},rI(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}rI(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),iI=function(t,e){this.psbt=t,this.masterFp=e},oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(iI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=eI(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(oI),uI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new py,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Up.sha256(Buffer.from("TapTweak","utf-8"));return Up.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(Nt.exports.pointAddScalar(e,r)).slice(1)},e}(oI),aI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=this.createRedeemScript(t),n=eI(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=eI(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(oI),hI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=eI(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(oI),fI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},cI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return gI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new dI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new dI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function FI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,HI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,HI(t.script.length),t.script])}))),r}function jI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,HI(t.script.length),t.script,t.sequence])}));var a=FI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),HI(t.inputs.length),s,a])}var qI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},GI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new mI(e,yI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return qI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I;return GI(this,(function(M){switch(M.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new MI,[4,this.client.getMasterFingerprint()];case 1:n=M.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new uI(e,r):t.additionals.includes("bech32")?new hI(e,r):t.segwit?new aI(e,r):new sI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,M.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new py).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new py;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new py;CI(h,f),CI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new py).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}UI(t,r)}}(r),I=function(t){var e,r,n=new py;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new py,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aM(t,e,r){return oM(this,void 0,void 0,(function(){var n,i,o,s;return sM(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function hM(t,e,r,n){return void 0===n&&(n=[]),oM(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N=this;return sM(this,(function(x){switch(x.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return oM(N,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return sM(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>gy?gy:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=uM(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,aM(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return aM(t,e)},[4,aM(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),HI(o.length)]),e)];case 1:x.sent(),x.label=2;case 2:x.trys.push([2,8,9,10]),d=uM(o),g=d.next(),x.label=3;case 3:return g.done?[3,7]:(m=g.value,y=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),v=f?m.tree||Buffer.from([0]):Buffer.alloc(0),T=Buffer.concat([m.prevout,v,y?Buffer.from([0]):HI(m.script.length)]),[4,aM(t,T)]);case 4:return x.sent(),[4,f?p(Buffer.concat([m.script,m.sequence])):y?p(m.sequence):l(m.script,m.sequence)];case 5:x.sent(),x.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=x.sent(),A={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(A)throw A.error}return[7];case 10:return[4,aM(t,HI(s.length))];case 11:x.sent(),x.label=12;case 12:x.trys.push([12,17,18,19]),b=uM(s),_=b.next(),x.label=13;case 13:return _.done?[3,16]:(E=_.value,T=Buffer.concat([E.amount,f?Buffer.from([0,0]):Buffer.alloc(0),HI(E.script.length),E.script]),[4,aM(t,T)]);case 14:x.sent(),x.label=15;case 15:return _=b.next(),[3,13];case 16:return[3,19];case 17:return S=x.sent(),k={error:S},[3,19];case 18:try{_&&!_.done&&(R=b.return)&&R.call(b)}finally{if(k)throw k.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(T=Buffer.concat(I),M=f?T:Buffer.concat([HI(T.length),T])),[4,l(Buffer.concat([u,M||Buffer.alloc(0)]))];case 20:return O=x.sent(),iM(O,"missing result in processScriptBlocks"),[2,O]}}))}))}var fM=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},cM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function pM(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function dM(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),fM(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O;return cM(this,(function(A){switch(A.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),HI(r.inputs.length)]),[4,pM(t,e,!0,a,i,o,s)];case 1:A.sent(),h=0,f=s.includes("decred"),A.label=2;case 2:A.trys.push([2,15,16,17]),c=lM(r.inputs),l=c.next(),A.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),HI(p.script.length)]),[4,pM(t,e,!1,a,i,o,s)]);case 4:if(A.sent(),m=[],y=0,0===p.script.length)m.push(p.sequence);else for(;y!==p.script.length;)v=p.script.length-y>gy?gy:p.script.length-y,y+v!==p.script.length?m.push(p.script.slice(y,y+v)):m.push(Buffer.concat([p.script.slice(y,y+v),p.sequence])),y+=v;A.label=5;case 5:A.trys.push([5,10,11,12]),T=void 0,w=lM(m),b=w.next(),A.label=6;case 6:return b.done?[3,9]:(_=b.value,[4,pM(t,e,!1,_,i,o,s)]);case 7:A.sent(),A.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return E=A.sent(),T={error:E},[3,12];case 11:try{b&&!b.done&&(O=w.return)&&O.call(w)}finally{if(T)throw T.error}return[7];case 12:h++,A.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=A.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(M=c.return)&&M.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function gM(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=tI("sha256").update(tI("sha256").update(jI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function mM(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=bt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var yM=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:gy,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var _M=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},EM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},AM={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function PM(t,e){return MM(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N,x,B,L,U,C,D,H,F,j,q,G,K,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return TM(this,(function(ht){switch(ht.label){case 0:if(r=IM(IM({},AM),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(m=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,SM(t)];case 2:return y=ht.sent(),m=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||ly.gte(e,"1.4.0"))}(y),[3,4];case 3:if(27904!==(v=ht.sent()).statusCode)throw v;return m=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),_=c.includes("stealthcoin"),E=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),M=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,T=Buffer.alloc(0),O=Buffer.alloc(0),A=Buffer.alloc(4),l&&!b?A.writeUInt32LE(S?2147483652:2147483651,0):_?A.writeUInt32LE(2,0):A.writeUInt32LE(1,0),P=[],k=[],R=[],N=[],x=!0,B=!1,L={inputs:[],version:A,timestamp:Buffer.alloc(0)},U=M&&!m?gM:hM,C=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=OM(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:F=ht.sent(),XI("hw","got trustedInput="+F),(j=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:my,0),P.push({trustedInput:!0,value:Buffer.from(F,"hex"),sequence:j}),ht.label=8;case 8:q=$[0].outputs,G=$[1],q&&G<=q.length-1&&k.push(q[G]),l&&!b?(L.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),L.nExpiryHeight=l,L.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(L.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(L.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:my,0),{script:T,prevout:O,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),eI(N[it]),Buffer.from([136,172])]):k[it].script,X=Object.assign({},L),Y=M?[P[it]]:P,M?X.inputs=[IM(IM({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,dM(t,!M&&x,X,Y,M,!!l&&!b,c,m)]):[3,34];case 27:return ht.sent(),M?[3,31]:B||!o?[3,29]:[4,wM(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,bM(t,C,c)];case 30:ht.sent(),ht.label=31;case 31:return x&&(d(),w(1,0)),[4,mM(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),R.push(J),L.inputs[it].script=T,x&&(x=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},UM={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function CM(t,e){return xM(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N,x,B,L;return BM(this,(function(U){switch(U.label){case 0:r=NM(NM({},UM),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],m=!0,y=!1,v={inputs:[],version:l},w=a?gM:hM,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),_=LM(n),E=_.next(),U.label=2;case 2:return E.done?[3,6]:(P=E.value,y?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=U.sent(),(O=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:my,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:O}),U.label=4;case 4:I=P[0].outputs,M=P[1],I&&M<=I.length-1&&d.push(I[M]),U.label=5;case 5:return E=_.next(),[3,2];case 6:return[3,9];case 7:return T=U.sent(),B={error:T},[3,9];case 8:try{E&&!E.done&&(L=_.return)&&L.call(_)}finally{if(B)throw B.error}return[7];case 9:for(A=0;A=4&&"number"==typeof n[A][3]?n[A][3]:my,0),v.inputs.push({script:f,prevout:c,sequence:O});return a?[4,dM(t,!0,v,p,!0)]:[3,12];case 10:return U.sent(),[4,bM(t,b)];case 11:U.sent(),U.label=12;case 12:A=0,U.label=13;case 13:return A=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[A].script,R=Object.assign({},v),N=a?[p[A]]:p,a?R.inputs=[NM(NM({},R.inputs[A]),{script:k})]:R.inputs[A].script=k,[4,dM(t,!a&&m,R,N,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,bM(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,mM(t,i[A],s,u)];case 17:x=U.sent(),g.push(a?x.toString("hex"):x.slice(0,x.length-1).toString("hex")),v.inputs[A].script=f,m&&(m=!1),U.label=18;case 18:return A++,[3,13];case 19:return[2,g]}}))}))}var DM=function(){return DM=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),PM(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),CM(this.transport,t)},t}();function qM(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var GM=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function KM(t){return tI("sha256").update(t).digest()}var WM,VM=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new lI(t.map((function(t){return pI(t)}))),this.values=e,this.valuesTree=new lI(e.map((function(t){return pI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([HI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),$M=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),zM=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},XM=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},QM=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(WM||(WM={}));var eT,rT,nT=function(){},iT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=WM.YIELD,n.results=e,n}return JM(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(nT),oT=function(t){function e(e,r){var n=t.call(this)||this;return n.code=WM.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return JM(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=HI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,QM([],ZM(a.slice(-f)),!1)),Buffer.concat(QM([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],ZM(a.slice(0,h)),!1))},e}(nT),uT=function(t){function e(e){var r=t.call(this)||this;return r.code=WM.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return JM(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(eT||(eT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(rT||(rT={}));var pT=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return fT(this,void 0,void 0,(function(){var n,i,o;return cT(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,rT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return fT(this,void 0,void 0,(function(){return cT(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(eT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),wt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return fT(this,void 0,void 0,(function(){var o,s;return cT(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new hT((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(eT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return fT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S;return cT(this,(function(I){switch(I.label){case 0:if(i=new YM(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new hT(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=lT(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){v={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(v)throw v.error}}try{for(a=lT(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(_=a.return)&&_.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new lI(i.inputMapCommitments.map((function(t){return pI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new lI(i.outputMapCommitments.map((function(t){return pI(t)}))).getRoot(),[4,this.makeRequest(eT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),HI(i.getGlobalInputCount()),c,HI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=lT(p),m=g.next();!m.done;m=g.next())y=m.value,d.set(y[0],y.slice(1))}catch(t){E={error:t}}finally{try{m&&!m.done&&(S=g.return)&&S.call(g)}finally{if(E)throw E.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return fT(this,void 0,void 0,(function(){return cT(this,(function(t){return[2,this.makeRequest(eT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var dT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},gT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof WI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||yT(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),m=g.slice(a,a+4),y=m.equals(Buffer.from([3,0,0,128]))||m.equals(Buffer.from([4,0,0,128])),v=m.equals(Buffer.from([1,0,0,0]))||m.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&v)&&(h=g.slice(a,4+a),a+=4),y&&(c=g.slice(a,4+a),a+=4);var w=DI(g,a),b=w[0];a+=w[1];for(var _=0;_=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new jM(this.transport)},t.prototype.new=function(){return new WI(new pT(this.transport))},t}();function yT(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var vT=Object.freeze({__proto__:null,default:mT}),wT=function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},bT={},_T={},ET=function(t,e){_T[t]=e},ST=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,bT[t]=e,e},IT=function(t){if("object"==typeof t&&t){try{var e=JSON.parse(t.message);e.message&&e.name&&(t=e)}catch(t){}var r=void 0;if("string"==typeof t.name){var n=t.name,i=_T[n];if(i)r=i(t);else{var o="Error"===n?Error:bT[n];o||(console.warn("deserializing an unknown class '"+n+"'"),o=ST(n)),r=Object.create(o.prototype);try{for(var s in t)t.hasOwnProperty(s)&&(r[s]=t[s])}catch(t){}}}else r=new Error(t.message);return!r.stack&&Error.captureStackTrace&&Error.captureStackTrace(r,IT),r}return new Error(String(t))};function MT(t,e){var r,n,i={};e.push(t);try{for(var o=wT(Object.keys(t)),s=o.next();!s.done;s=o.next()){var u=s.value,a=t[u];"function"!=typeof a&&(a&&"object"==typeof a?-1!==e.indexOf(t[u])?i[u]="[Circular]":i[u]=MT(t[u],e.slice(0)):i[u]=a)}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return"string"==typeof t.name&&(i.name=t.name),"string"==typeof t.message&&(i.message=t.message),"string"==typeof t.stack&&(i.stack=t.stack),i}var TT=ST("AccountNameRequired"),OT=ST("AccountNotSupported"),AT=ST("AmountRequired"),PT=ST("BluetoothRequired"),kT=ST("BtcUnmatchedApp"),RT=ST("CantOpenDevice"),NT=ST("CashAddrNotSupported"),xT=ST("CurrencyNotSupported"),BT=ST("DeviceAppVerifyNotSupported"),LT=ST("DeviceGenuineSocketEarlyClose"),UT=ST("DeviceNotGenuine"),CT=ST("DeviceOnDashboardExpected"),DT=ST("DeviceOnDashboardUnexpected"),HT=ST("DeviceInOSUExpected"),FT=ST("DeviceHalted"),jT=ST("DeviceNameInvalid"),qT=ST("DeviceSocketFail"),GT=ST("DeviceSocketNoBulkStatus"),KT=ST("DisconnectedDevice"),WT=ST("DisconnectedDeviceDuringOperation"),VT=ST("EnpointConfig"),$T=ST("EthAppPleaseEnableContractData"),zT=ST("FeeEstimationFailed"),XT=ST("FirmwareNotRecognized"),YT=ST("HardResetFail"),JT=ST("InvalidXRPTag"),ZT=ST("InvalidAddress"),QT=ST("InvalidAddressBecauseDestinationIsAlsoSource"),tO=ST("LatestMCUInstalledError"),eO=ST("UnknownMCU"),rO=ST("LedgerAPIError"),nO=ST("LedgerAPIErrorWithMessage"),iO=ST("LedgerAPINotAvailable"),oO=ST("ManagerAppAlreadyInstalled"),sO=ST("ManagerAppRelyOnBTC"),uO=ST("ManagerAppDepInstallRequired"),aO=ST("ManagerAppDepUninstallRequired"),hO=ST("ManagerDeviceLocked"),fO=ST("ManagerFirmwareNotEnoughSpace"),cO=ST("ManagerNotEnoughSpace"),lO=ST("ManagerUninstallBTCDep"),pO=ST("NetworkDown"),dO=ST("NoAddressesFound"),gO=ST("NotEnoughBalance"),mO=ST("NotEnoughBalanceToDelegate"),yO=ST("NotEnoughBalanceInParentAccount"),vO=ST("NotEnoughSpendableBalance"),wO=ST("NotEnoughBalanceBecauseDestinationNotCreated"),bO=ST("NoAccessToCamera"),_O=ST("NotEnoughGas"),EO=ST("NotSupportedLegacyAddress"),SO=ST("GasLessThanEstimate"),IO=ST("PasswordsDontMatch"),MO=ST("PasswordIncorrect"),TO=ST("RecommendSubAccountsToEmpty"),OO=ST("RecommendUndelegation"),AO=ST("TimeoutTagged"),PO=ST("UnexpectedBootloader"),kO=ST("MCUNotGenuineToDashboard"),RO=ST("RecipientRequired"),NO=ST("UnavailableTezosOriginatedAccountReceive"),xO=ST("UnavailableTezosOriginatedAccountSend"),BO=ST("UpdateFetchFileFail"),LO=ST("UpdateIncorrectHash"),UO=ST("UpdateIncorrectSig"),CO=ST("UpdateYourApp"),DO=ST("UserRefusedDeviceNameChange"),HO=ST("UserRefusedAddress"),FO=ST("UserRefusedFirmwareUpdate"),jO=ST("UserRefusedAllowManager"),qO=ST("UserRefusedOnDevice"),GO=ST("TransportOpenUserCancelled"),KO=ST("TransportInterfaceNotAvailable"),WO=ST("TransportRaceCondition"),VO=ST("TransportWebUSBGestureRequired"),$O=ST("DeviceShouldStayInApp"),zO=ST("WebsocketConnectionError"),XO=ST("WebsocketConnectionFailed"),YO=ST("WrongDeviceForAccount"),JO=ST("WrongAppForCurrency"),ZO=ST("ETHAddressNonEIP"),QO=ST("CantScanQRCode"),tA=ST("FeeNotLoaded"),eA=ST("FeeRequired"),rA=ST("FeeTooHigh"),nA=ST("SyncError"),iA=ST("PairingFailed"),oA=ST("GenuineCheckFailed"),sA=ST("LedgerAPI4xx"),uA=ST("LedgerAPI5xx"),aA=ST("FirmwareOrAppUpdateRequired"),hA=ST("NoDBPathGiven"),fA=ST("DBWrongPassword"),cA=ST("DBNotReset");function lA(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}lA.prototype=new Error,ET("TransportError",(function(t){return new lA(t.message,t.id)}));var pA={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,MISSING_CRITICAL_PARAMETER:26624,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function dA(t){switch(t){case 26368:return"Incorrect length";case 26624:return"Missing critical parameter";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function gA(t){this.name="TransportStatusError";var e=Object.keys(pA).find((function(e){return pA[e]===t}))||"UNKNOWN_ERROR",r=dA(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}gA.prototype=new Error,ET("TransportStatusError",(function(t){return new gA(t.statusCode)}));var mA=Object.freeze({__proto__:null,serializeError:function(t){return t?"object"==typeof t?MT(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},deserializeError:IT,createCustomErrorClass:ST,addCustomErrorDeserializer:ET,AccountNameRequiredError:TT,AccountNotSupported:OT,AmountRequired:AT,BluetoothRequired:PT,BtcUnmatchedApp:kT,CantOpenDevice:RT,CashAddrNotSupported:NT,CurrencyNotSupported:xT,DeviceAppVerifyNotSupported:BT,DeviceGenuineSocketEarlyClose:LT,DeviceNotGenuineError:UT,DeviceOnDashboardExpected:CT,DeviceOnDashboardUnexpected:DT,DeviceInOSUExpected:HT,DeviceHalted:FT,DeviceNameInvalid:jT,DeviceSocketFail:qT,DeviceSocketNoBulkStatus:GT,DisconnectedDevice:KT,DisconnectedDeviceDuringOperation:WT,EnpointConfigError:VT,EthAppPleaseEnableContractData:$T,FeeEstimationFailed:zT,FirmwareNotRecognized:XT,HardResetFail:YT,InvalidXRPTag:JT,InvalidAddress:ZT,InvalidAddressBecauseDestinationIsAlsoSource:QT,LatestMCUInstalledError:tO,UnknownMCU:eO,LedgerAPIError:rO,LedgerAPIErrorWithMessage:nO,LedgerAPINotAvailable:iO,ManagerAppAlreadyInstalledError:oO,ManagerAppRelyOnBTCError:sO,ManagerAppDepInstallRequired:uO,ManagerAppDepUninstallRequired:aO,ManagerDeviceLockedError:hO,ManagerFirmwareNotEnoughSpaceError:fO,ManagerNotEnoughSpaceError:cO,ManagerUninstallBTCDep:lO,NetworkDown:pO,NoAddressesFound:dO,NotEnoughBalance:gO,NotEnoughBalanceToDelegate:mO,NotEnoughBalanceInParentAccount:yO,NotEnoughSpendableBalance:vO,NotEnoughBalanceBecauseDestinationNotCreated:wO,NoAccessToCamera:bO,NotEnoughGas:_O,NotSupportedLegacyAddress:EO,GasLessThanEstimate:SO,PasswordsDontMatchError:IO,PasswordIncorrectError:MO,RecommendSubAccountsToEmpty:TO,RecommendUndelegation:OO,TimeoutTagged:AO,UnexpectedBootloader:PO,MCUNotGenuineToDashboard:kO,RecipientRequired:RO,UnavailableTezosOriginatedAccountReceive:NO,UnavailableTezosOriginatedAccountSend:xO,UpdateFetchFileFail:BO,UpdateIncorrectHash:LO,UpdateIncorrectSig:UO,UpdateYourApp:CO,UserRefusedDeviceNameChange:DO,UserRefusedAddress:HO,UserRefusedFirmwareUpdate:FO,UserRefusedAllowManager:jO,UserRefusedOnDevice:qO,TransportOpenUserCancelled:GO,TransportInterfaceNotAvailable:KO,TransportRaceCondition:WO,TransportWebUSBGestureRequired:VO,DeviceShouldStayInApp:$O,WebsocketConnectionError:zO,WebsocketConnectionFailed:XO,WrongDeviceForAccount:YO,WrongAppForCurrency:JO,ETHAddressNonEIP:ZO,CantScanQRCode:QO,FeeNotLoaded:tA,FeeRequired:eA,FeeTooHigh:rA,SyncError:nA,PairingFailed:iA,GenuineCheckFailed:oA,LedgerAPI4xx:sA,LedgerAPI5xx:uA,FirmwareOrAppUpdateRequired:aA,NoDBPathGiven:hA,DBWrongPassword:fA,DBNotReset:cA,TransportError:lA,StatusCodes:pA,getAltStatusMessage:dA,TransportStatusError:gA}),yA=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vA=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},bA=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},EA=function(){function t(){var t=this;this.exchangeTimeout=3e4,this.unresponsiveTimeout=15e3,this.deviceModel=null,this._events=new wy,this.send=function(e,r,n,i,o,s){return void 0===o&&(o=Buffer.alloc(0)),void 0===s&&(s=[pA.OK]),yA(t,void 0,void 0,(function(){var t,u;return vA(this,(function(a){switch(a.label){case 0:if(o.length>=256)throw new lA("data.length exceed 256 bytes limit. Got: "+o.length,"DataLengthTooBig");return[4,this.exchange(Buffer.concat([Buffer.from([e,r,n,i]),Buffer.from([o.length]),o]))];case 1:if(t=a.sent(),u=t.readUInt16BE(t.length-2),!s.some((function(t){return t===u})))throw new gA(u);return[2,t]}}))}))},this.exchangeAtomicImpl=function(e){return yA(t,void 0,void 0,(function(){var t,r,n,i,o,s=this;return vA(this,(function(u){switch(u.label){case 0:if(this.exchangeBusyPromise)throw new WO("An action was already pending on the Ledger device. Please deny or reconnect.");r=new Promise((function(e){t=e})),this.exchangeBusyPromise=r,n=!1,i=setTimeout((function(){n=!0,s.emit("unresponsive")}),this.unresponsiveTimeout),u.label=1;case 1:return u.trys.push([1,,3,4]),[4,e()];case 2:return o=u.sent(),n&&this.emit("responsive"),[2,o];case 3:return clearTimeout(i),t&&t(),this.exchangeBusyPromise=null,[7];case 4:return[2]}}))}))},this._appAPIlock=null}return t.prototype.exchange=function(t){throw new Error("exchange not implemented")},t.prototype.setScrambleKey=function(t){},t.prototype.close=function(){return Promise.resolve()},t.prototype.on=function(t,e){this._events.on(t,e)},t.prototype.off=function(t,e){this._events.removeListener(t,e)},t.prototype.emit=function(t){for(var e,r=[],n=1;nu&&(s=s.slice(0,u)),{data:s,dataLength:u,sequence:a}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}}}(SA);var MA,TA,OA=n(SA),AA=function(){return AA=Object.assign||function(t){for(var e,r=1,n=arguments.length;r>8;return kA.find((function(t){return t.productIdMM===r}))},NA=[],xA={};for(var BA in PA){var LA=PA[BA],UA=LA.bluetoothSpec;if(UA)for(var CA=0;CA0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1] "+t.toString("hex")),i=OA(r,n),o=i.makeBlocks(t),s=0,c.label=1;case 1:return s0?[2,t[0]]:[2,qA()]}}))}))}().then((function(r){if(!e){var n=RA(r.productId);t.next({type:"add",descriptor:r,deviceModel:n}),t.complete()}}),(function(e){window.DOMException&&e instanceof window.DOMException&&18===e.code?t.error(new VO(e.message)):t.error(new GO(e.message))})),{unsubscribe:function(){e=!0}}},e}(EA);function XA(t){return VA(this,void 0,void 0,(function(){var e;return $A(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,t.reset()];case 1:return r.sent(),[3,3];case 2:return e=r.sent(),console.warn(e),[3,3];case 3:return[2]}}))}))}var YA=Object.freeze({__proto__:null,default:zA}),JA=JA||{},ZA=JA;JA.EXTENSION_ID="kmendfapggjehodndflmmgagdbamhnfd",JA.MessageTypes={U2F_REGISTER_REQUEST:"u2f_register_request",U2F_SIGN_REQUEST:"u2f_sign_request",U2F_REGISTER_RESPONSE:"u2f_register_response",U2F_SIGN_RESPONSE:"u2f_sign_response"},JA.ErrorCodes={OK:0,OTHER_ERROR:1,BAD_REQUEST:2,CONFIGURATION_UNSUPPORTED:3,DEVICE_INELIGIBLE:4,TIMEOUT:5},JA.Request,JA.Response,JA.Error,JA.SignRequest,JA.SignResponse,JA.RegisterRequest,JA.RegisterResponse,JA.disconnect=function(){JA.port_&&JA.port_.port_&&(JA.port_.port_.disconnect(),JA.port_=null)},JA.getMessagePort=function(t){if("undefined"!=typeof chrome&&chrome.runtime){var e={type:JA.MessageTypes.U2F_SIGN_REQUEST,signRequests:[]};chrome.runtime.sendMessage(JA.EXTENSION_ID,e,(function(){chrome.runtime.lastError?JA.getIframePort_(t):JA.getChromeRuntimePort_(t)}))}else JA.getIframePort_(t)},JA.getChromeRuntimePort_=function(t){var e=chrome.runtime.connect(JA.EXTENSION_ID,{includeTlsChannelId:!0});setTimeout((function(){t(null,new JA.WrappedChromeRuntimePort_(e))}),0)},JA.WrappedChromeRuntimePort_=function(t){this.port_=t},JA.WrappedChromeRuntimePort_.prototype.postMessage=function(t){this.port_.postMessage(t)},JA.WrappedChromeRuntimePort_.prototype.addEventListener=function(t,e){var r=t.toLowerCase();"message"==r||"onmessage"==r?this.port_.onMessage.addListener((function(t){e({data:t})})):console.error("WrappedChromeRuntimePort only supports onMessage")},JA.getIframePort_=function(t){var e="chrome-extension://"+JA.EXTENSION_ID,r=document.createElement("iframe");r.src=e+"/u2f-comms.html",r.setAttribute("style","display:none"),document.body.appendChild(r);var n=!1,i=new MessageChannel,o=function(e){"ready"==e.data?(i.port1.removeEventListener("message",o),n||(n=!0,t(null,i.port1))):console.error('First event on iframe port was not "ready"')};i.port1.addEventListener("message",o),i.port1.start(),r.addEventListener("load",(function(){r.contentWindow.postMessage("init",e,[i.port2])})),setTimeout((function(){n||(n=!0,t(new Error("IFrame extension not supported")))}),200)},JA.EXTENSION_TIMEOUT_SEC=30,JA.port_=null,JA.waitingForPort_=[],JA.reqCounter_=0,JA.callbackMap_={},JA.getPortSingleton_=function(t){JA.port_?t(null,JA.port_):(0==JA.waitingForPort_.length&&JA.getMessagePort((function(t,e){for(t||(JA.port_=e,JA.port_.addEventListener("message",JA.responseHandler_));JA.waitingForPort_.length;)JA.waitingForPort_.shift()(t,e)})),JA.waitingForPort_.push(t))},JA.responseHandler_=function(t){var e=t.data,r=e.requestId;if(r&&JA.callbackMap_[r]){var n=JA.callbackMap_[r];delete JA.callbackMap_[r],n(null,e.responseData)}else console.error("Unknown or missing requestId in response.")},JA.isSupported=function(t){JA.getPortSingleton_((function(e,r){t(!e)}))},JA.sign=function(t,e,r){JA.getPortSingleton_((function(n,i){if(n)return e(n);var o=++JA.reqCounter_;JA.callbackMap_[o]=e;var s={type:JA.MessageTypes.U2F_SIGN_REQUEST,signRequests:t,timeoutSeconds:void 0!==r?r:JA.EXTENSION_TIMEOUT_SEC,requestId:o};i.postMessage(s)}))},JA.register=function(t,e,r,n){JA.getPortSingleton_((function(i,o){if(i)return r(i);var s=++JA.reqCounter_;JA.callbackMap_[s]=r;var u={type:JA.MessageTypes.U2F_REGISTER_REQUEST,signRequests:e,registerRequests:t,timeoutSeconds:void 0!==n?n:JA.EXTENSION_TIMEOUT_SEC,requestId:s};o.postMessage(u)}))};var QA=sP,tP=ZA,eP="undefined"!=typeof navigator&&!!navigator.userAgent,rP=eP&&navigator.userAgent.match(/Safari\//)&&!navigator.userAgent.match(/Chrome\//),nP=eP&&navigator.userAgent.match(/Edge\/1[2345]/),iP=null;function oP(t){return iP||(iP=new t((function(t,e){function r(){t({u2f:null,native:!0})}return eP?rP?r():(void 0!==window.u2f&&"function"==typeof window.u2f.sign&&t({u2f:window.u2f,native:!0}),nP||"http:"===location.protocol||"undefined"==typeof MessageChannel?r():void tP.isSupported((function(e){e?t({u2f:tP,native:!1}):r()}))):r()}))),iP}function sP(t){return{isSupported:hP.bind(t),ensureSupport:cP.bind(t),register:lP.bind(t),sign:pP.bind(t),ErrorCodes:sP.ErrorCodes,ErrorNames:sP.ErrorNames}}function uP(t,e){var r=null!=e?e.errorCode:1,n=sP.ErrorNames[""+r],i=new Error(t);return i.metaData={type:n,code:r},i}function aP(t,e){var r={};return r.promise=new t((function(t,n){r.resolve=t,r.reject=n,e.then(t,n)})),r.promise.cancel=function(e,n){oP(t).then((function(t){n&&!t.native&&t.u2f.disconnect(),r.reject(uP(e,{errorCode:-1}))}))},r}function hP(){return oP(this).then((function(t){return!!t.u2f}))}function fP(t){if(!t.u2f){if("http:"===location.protocol)throw new Error("U2F isn't supported over http, only https");throw new Error("U2F not supported")}}function cP(){return oP(this).then(fP)}function lP(t,e,r){var n=this;return Array.isArray(t)||(t=[t]),"number"==typeof e&&void 0===r&&(r=e,e=null),e||(e=[]),aP(n,oP(n).then((function(i){fP(i);var o=i.native,s=i.u2f;return new n((function(n,i){if(o){var u=t[0].appId;s.register(u,t,e,(function(t){t.errorCode?i(uP("Registration failed",t)):(delete t.errorCode,n(t))}),r)}else s.register(t,e,(function(t,e){t?i(t):e.errorCode?i(uP("Registration failed",e)):n(e)}),r)}))}))).promise}function pP(t,e){var r=this;return Array.isArray(t)||(t=[t]),aP(r,oP(r).then((function(n){fP(n);var i=n.native,o=n.u2f;return new r((function(r,n){if(i){var s=t[0].appId,u=t[0].challenge;o.sign(s,u,t,(function(t){t.errorCode?n(uP("Sign failed",t)):(delete t.errorCode,r(t))}),e)}else o.sign(t,(function(t,e){t?n(t):e.errorCode?n(uP("Sign failed",e)):r(e)}),e)}))}))).promise}function dP(t){sP[t]=function(){if(!r.Promise)throw new Error("The platform doesn't natively support promises");var e=[].slice.call(arguments);return sP(r.Promise)[t].apply(null,e)}}sP.ErrorCodes={CANCELLED:-1,OK:0,OTHER_ERROR:1,BAD_REQUEST:2,CONFIGURATION_UNSUPPORTED:3,DEVICE_INELIGIBLE:4,TIMEOUT:5},sP.ErrorNames={"-1":"CANCELLED",0:"OK",1:"OTHER_ERROR",2:"BAD_REQUEST",3:"CONFIGURATION_UNSUPPORTED",4:"DEVICE_INELIGIBLE",5:"TIMEOUT"},dP("isSupported"),dP("ensureSupport"),dP("register"),dP("sign");var gP=QA,mP={},yP={},vP=function(t,e){yP[t]=e},wP=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,mP[t]=e,e};wP("AccountNameRequired"),wP("AccountNotSupported"),wP("AmountRequired"),wP("BluetoothRequired"),wP("BtcUnmatchedApp"),wP("CantOpenDevice"),wP("CashAddrNotSupported"),wP("CurrencyNotSupported"),wP("DeviceAppVerifyNotSupported"),wP("DeviceGenuineSocketEarlyClose"),wP("DeviceNotGenuine"),wP("DeviceOnDashboardExpected"),wP("DeviceOnDashboardUnexpected"),wP("DeviceInOSUExpected"),wP("DeviceHalted"),wP("DeviceNameInvalid"),wP("DeviceSocketFail"),wP("DeviceSocketNoBulkStatus"),wP("DisconnectedDevice"),wP("DisconnectedDeviceDuringOperation"),wP("EnpointConfig"),wP("EthAppPleaseEnableContractData"),wP("FeeEstimationFailed"),wP("FirmwareNotRecognized"),wP("HardResetFail"),wP("InvalidXRPTag"),wP("InvalidAddress"),wP("InvalidAddressBecauseDestinationIsAlsoSource"),wP("LatestMCUInstalledError"),wP("UnknownMCU"),wP("LedgerAPIError"),wP("LedgerAPIErrorWithMessage"),wP("LedgerAPINotAvailable"),wP("ManagerAppAlreadyInstalled"),wP("ManagerAppRelyOnBTC"),wP("ManagerAppDepInstallRequired"),wP("ManagerAppDepUninstallRequired"),wP("ManagerDeviceLocked"),wP("ManagerFirmwareNotEnoughSpace"),wP("ManagerNotEnoughSpace"),wP("ManagerUninstallBTCDep"),wP("NetworkDown"),wP("NoAddressesFound"),wP("NotEnoughBalance"),wP("NotEnoughBalanceToDelegate"),wP("NotEnoughBalanceInParentAccount"),wP("NotEnoughSpendableBalance"),wP("NotEnoughBalanceBecauseDestinationNotCreated"),wP("NoAccessToCamera"),wP("NotEnoughGas"),wP("NotSupportedLegacyAddress"),wP("GasLessThanEstimate"),wP("PasswordsDontMatch"),wP("PasswordIncorrect"),wP("RecommendSubAccountsToEmpty"),wP("RecommendUndelegation"),wP("TimeoutTagged"),wP("UnexpectedBootloader"),wP("MCUNotGenuineToDashboard"),wP("RecipientRequired"),wP("UnavailableTezosOriginatedAccountReceive"),wP("UnavailableTezosOriginatedAccountSend"),wP("UpdateFetchFileFail"),wP("UpdateIncorrectHash"),wP("UpdateIncorrectSig"),wP("UpdateYourApp"),wP("UserRefusedDeviceNameChange"),wP("UserRefusedAddress"),wP("UserRefusedFirmwareUpdate"),wP("UserRefusedAllowManager"),wP("UserRefusedOnDevice"),wP("TransportOpenUserCancelled"),wP("TransportInterfaceNotAvailable");var bP=wP("TransportRaceCondition");function _P(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}wP("TransportWebUSBGestureRequired"),wP("DeviceShouldStayInApp"),wP("WebsocketConnectionError"),wP("WebsocketConnectionFailed"),wP("WrongDeviceForAccount"),wP("WrongAppForCurrency"),wP("ETHAddressNonEIP"),wP("CantScanQRCode"),wP("FeeNotLoaded"),wP("FeeRequired"),wP("FeeTooHigh"),wP("SyncError"),wP("PairingFailed"),wP("GenuineCheckFailed"),wP("LedgerAPI4xx"),wP("LedgerAPI5xx"),wP("FirmwareOrAppUpdateRequired"),wP("NoDBPathGiven"),wP("DBWrongPassword"),wP("DBNotReset"),_P.prototype=new Error,vP("TransportError",(function(t){return new _P(t.message,t.id)}));var EP={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,MISSING_CRITICAL_PARAMETER:26624,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function SP(t){this.name="TransportStatusError";var e=Object.keys(EP).find((function(e){return EP[e]===t}))||"UNKNOWN_ERROR",r=function(t){switch(t){case 26368:return"Incorrect length";case 26624:return"Missing critical parameter";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}SP.prototype=new Error,vP("TransportStatusError",(function(t){return new SP(t.statusCode)}));class IP{constructor(){this.exchangeTimeout=3e4,this.unresponsiveTimeout=15e3,this.deviceModel=null,this._events=new wy,this.send=async(t,e,r,n,i=Buffer.alloc(0),o=[EP.OK])=>{if(i.length>=256)throw new _P("data.length exceed 256 bytes limit. Got: "+i.length,"DataLengthTooBig");const s=await this.exchange(Buffer.concat([Buffer.from([t,e,r,n]),Buffer.from([i.length]),i])),u=s.readUInt16BE(s.length-2);if(!o.some((t=>t===u)))throw new SP(u);return s},this.exchangeBusyPromise=void 0,this.exchangeAtomicImpl=async t=>{if(this.exchangeBusyPromise)throw new bP("An action was already pending on the Ledger device. Please deny or reconnect.");let e;const r=new Promise((t=>{e=t}));this.exchangeBusyPromise=r;let n=!1;const i=setTimeout((()=>{n=!0,this.emit("unresponsive")}),this.unresponsiveTimeout);try{const r=await t();return n&&this.emit("responsive"),r}finally{clearTimeout(i),e&&e(),this.exchangeBusyPromise=null}},this._appAPIlock=null}exchange(t){throw new Error("exchange not implemented")}setScrambleKey(t){}close(){return Promise.resolve()}on(t,e){this._events.on(t,e)}off(t,e){this._events.removeListener(t,e)}emit(t,...e){this._events.emit(t,...e)}setDebugMode(){console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore.")}setExchangeTimeout(t){this.exchangeTimeout=t}setExchangeUnresponsiveTimeout(t){this.unresponsiveTimeout=t}static create(t=3e3,e){return new Promise(((r,n)=>{let i=!1;const o=this.listen({next:e=>{i=!0,o&&o.unsubscribe(),s&&clearTimeout(s),this.open(e.descriptor,t).then(r,n)},error:t=>{s&&clearTimeout(s),n(t)},complete:()=>{s&&clearTimeout(s),i||n(new _P(this.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),s=e?setTimeout((()=>{o.unsubscribe(),n(new _P(this.ErrorMessage_ListenTimeout,"ListenTimeout"))}),e):null}))}decorateAppAPIMethods(t,e,r){for(let n of e)t[n]=this.decorateAppAPIMethod(n,t[n],t,r)}decorateAppAPIMethod(t,e,r,n){return async(...i)=>{const{_appAPIlock:o}=this;if(o)return Promise.reject(new _P("Ledger Device is busy (lock "+o+")","TransportLocked"));try{return this._appAPIlock=t,this.setScrambleKey(n),await e.apply(r,i)}finally{this._appAPIlock=null}}}}IP.isSupported=void 0,IP.list=void 0,IP.listen=void 0,IP.open=void 0,IP.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",IP.ErrorMessage_NoDeviceFound="No Ledger device found";let MP=0;const TP=[],OP=(t,e,r)=>{const n={type:t,id:String(++MP),date:new Date};e&&(n.message=e),r&&(n.data=r),function(t){for(let e=0;e(TP.push(t),()=>{const e=TP.indexOf(t);-1!==e&&(TP[e]=TP[TP.length-1],TP.pop())});"undefined"!=typeof window&&(window.__ledgerLogsListen=AP);const PP=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function kP(t,e,r,n){const i=function(t,e){const r=Buffer.alloc(t.length);for(let n=0;n "+t.toString("hex")),gP.sign(s,e/1e3).then((t=>{const{signatureData:e}=t;if("string"==typeof e){const t=Buffer.from((r=e).replace(/-/g,"+").replace(/_/g,"/")+"==".substring(0,3*r.length%4),"base64");let i;return i=n?t.slice(5):t,OP("apdu","<= "+i.toString("hex")),i}throw t;var r}))}let RP=[];class NP extends IP{static async open(t,e=5e3){return new NP}constructor(){super(),this.scrambleKey=void 0,this.unwrap=!0,RP.push(this)}async exchange(t){try{return await kP(t,this.exchangeTimeout,this.scrambleKey,this.unwrap)}catch(t){throw"object"==typeof t.metaData?(5===t.metaData.code&&(RP.forEach((t=>t.emit("disconnect"))),RP=[]),function(t,e,r){const n=new _P(e,r);return n.originalError=t,n}(t,"Failed to sign with Ledger device: U2F "+t.metaData.type,"U2F_"+t.metaData.code)):t}}setScrambleKey(t){this.scrambleKey=Buffer.from(t,"ascii")}setUnwrap(t){this.unwrap=t}close(){return Promise.resolve()}}NP.isSupported=gP.isSupported,NP.list=()=>gP.isSupported().then((t=>t?[null]:[])),NP.listen=t=>{let e=!1;return gP.isSupported().then((r=>{e||(r?(t.next({type:"add",descriptor:null}),t.complete()):t.error(new _P("U2F browser support is needed for Ledger. Please use Chrome, Opera or Firefox with a U2F extension. Also make sure you're on an HTTPS connection","U2FNotSupported")))})),{unsubscribe:()=>{e=!0}}};var xP=Object.freeze({__proto__:null,default:NP}),BP=te.exports,LP=EE,UP=f.exports.Buffer,CP=new Array(16);function DP(){LP.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function HP(t,e){return t<>>32-e}function FP(t,e,r,n,i,o,s){return HP(t+(e&r|~e&n)+i+o|0,s)+e|0}function jP(t,e,r,n,i,o,s){return HP(t+(e&n|r&~n)+i+o|0,s)+e|0}function qP(t,e,r,n,i,o,s){return HP(t+(e^r^n)+i+o|0,s)+e|0}function GP(t,e,r,n,i,o,s){return HP(t+(r^(e|~n))+i+o|0,s)+e|0}BP(DP,LP),DP.prototype._update=function(){for(var t=CP,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);var r=this._a,n=this._b,i=this._c,o=this._d;r=FP(r,n,i,o,t[0],3614090360,7),o=FP(o,r,n,i,t[1],3905402710,12),i=FP(i,o,r,n,t[2],606105819,17),n=FP(n,i,o,r,t[3],3250441966,22),r=FP(r,n,i,o,t[4],4118548399,7),o=FP(o,r,n,i,t[5],1200080426,12),i=FP(i,o,r,n,t[6],2821735955,17),n=FP(n,i,o,r,t[7],4249261313,22),r=FP(r,n,i,o,t[8],1770035416,7),o=FP(o,r,n,i,t[9],2336552879,12),i=FP(i,o,r,n,t[10],4294925233,17),n=FP(n,i,o,r,t[11],2304563134,22),r=FP(r,n,i,o,t[12],1804603682,7),o=FP(o,r,n,i,t[13],4254626195,12),i=FP(i,o,r,n,t[14],2792965006,17),r=jP(r,n=FP(n,i,o,r,t[15],1236535329,22),i,o,t[1],4129170786,5),o=jP(o,r,n,i,t[6],3225465664,9),i=jP(i,o,r,n,t[11],643717713,14),n=jP(n,i,o,r,t[0],3921069994,20),r=jP(r,n,i,o,t[5],3593408605,5),o=jP(o,r,n,i,t[10],38016083,9),i=jP(i,o,r,n,t[15],3634488961,14),n=jP(n,i,o,r,t[4],3889429448,20),r=jP(r,n,i,o,t[9],568446438,5),o=jP(o,r,n,i,t[14],3275163606,9),i=jP(i,o,r,n,t[3],4107603335,14),n=jP(n,i,o,r,t[8],1163531501,20),r=jP(r,n,i,o,t[13],2850285829,5),o=jP(o,r,n,i,t[2],4243563512,9),i=jP(i,o,r,n,t[7],1735328473,14),r=qP(r,n=jP(n,i,o,r,t[12],2368359562,20),i,o,t[5],4294588738,4),o=qP(o,r,n,i,t[8],2272392833,11),i=qP(i,o,r,n,t[11],1839030562,16),n=qP(n,i,o,r,t[14],4259657740,23),r=qP(r,n,i,o,t[1],2763975236,4),o=qP(o,r,n,i,t[4],1272893353,11),i=qP(i,o,r,n,t[7],4139469664,16),n=qP(n,i,o,r,t[10],3200236656,23),r=qP(r,n,i,o,t[13],681279174,4),o=qP(o,r,n,i,t[0],3936430074,11),i=qP(i,o,r,n,t[3],3572445317,16),n=qP(n,i,o,r,t[6],76029189,23),r=qP(r,n,i,o,t[9],3654602809,4),o=qP(o,r,n,i,t[12],3873151461,11),i=qP(i,o,r,n,t[15],530742520,16),r=GP(r,n=qP(n,i,o,r,t[2],3299628645,23),i,o,t[0],4096336452,6),o=GP(o,r,n,i,t[7],1126891415,10),i=GP(i,o,r,n,t[14],2878612391,15),n=GP(n,i,o,r,t[5],4237533241,21),r=GP(r,n,i,o,t[12],1700485571,6),o=GP(o,r,n,i,t[3],2399980690,10),i=GP(i,o,r,n,t[10],4293915773,15),n=GP(n,i,o,r,t[1],2240044497,21),r=GP(r,n,i,o,t[8],1873313359,6),o=GP(o,r,n,i,t[15],4264355552,10),i=GP(i,o,r,n,t[6],2734768916,15),n=GP(n,i,o,r,t[13],1309151649,21),r=GP(r,n,i,o,t[4],4149444226,6),o=GP(o,r,n,i,t[11],3174756917,10),i=GP(i,o,r,n,t[2],718787259,15),n=GP(n,i,o,r,t[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0},DP.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=UP.allocUnsafe(16);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t};var KP=DP,WP=i(Bv),VP=f.exports.Buffer,$P=ww.Transform,zP=WP.StringDecoder;function XP(t){$P.call(this),this.hashMode="string"==typeof t,this.hashMode?this[t]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}(0,te.exports)(XP,$P),XP.prototype.update=function(t,e,r){"string"==typeof t&&(t=VP.from(t,e));var n=this._update(t);return this.hashMode?this:(r&&(n=this._toString(n,r)),n)},XP.prototype.setAutoPadding=function(){},XP.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},XP.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},XP.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},XP.prototype._transform=function(t,e,r){var n;try{this.hashMode?this._update(t):this.push(this._update(t))}catch(t){n=t}finally{r(n)}},XP.prototype._flush=function(t){var e;try{this.push(this.__final())}catch(t){e=t}t(e)},XP.prototype._finalOrDigest=function(t){var e=this.__final()||VP.alloc(0);return t&&(e=this._toString(e,t,!0)),e},XP.prototype._toString=function(t,e,r){if(this._decoder||(this._decoder=new zP(e),this._encoding=e),this._encoding!==e)throw new Error("can't switch encodings");var n=this._decoder.write(t);return r&&(n+=this._decoder.end()),n};var YP=XP,JP=te.exports,ZP=KP,QP=FE,tk=jE.exports,ek=YP;function rk(t){ek.call(this,"digest"),this._hash=t}JP(rk,ek),rk.prototype._update=function(t){this._hash.update(t)},rk.prototype._final=function(){return this._hash.digest()};var nk=function(t){return"md5"===(t=t.toLowerCase())?new ZP:"rmd160"===t||"ripemd160"===t?new QP:new rk(tk(t))},ik=Object.freeze(e({__proto__:null,default:nk},[nk]));t.Btc=vT,t.Log=JI,t.TransportU2F=xP,t.TransportWebUSB=YA,t.createHash=ik,Object.defineProperty(t,"__esModule",{value:!0})})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; From 5db983635b4764ae6db80366583c41dd7dbd8d41 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 22:06:15 +1100 Subject: [PATCH 17/78] . --- js/ledger.js | 38657 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 38654 insertions(+), 3 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index f145aaf8..b6caa9d7 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2,9 +2,38660 @@ window.global = window; window.Buffer = buffer.Buffer; -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).NewLedger={})}(this,(function(t){"use strict";function e(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(r){if("default"!==r&&!(r in t)){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}))})),Object.freeze(t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t){if(t.__esModule)return t;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(t).forEach((function(r){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})})),e}!function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof m?e:m,o=Object.create(i.prototype),s=new A(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===i)throw o;return k()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var u=M(s,r);if(u){if(u===g)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=d,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=p;var a=f(t,e,r);if("normal"===a.type){if(n=r.done?d:l,a.arg===g)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n=d,r.method="throw",r.arg=a.arg)}}}(t,r,s),o}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",l="suspendedYield",p="executing",d="completed",g={};function m(){}function y(){}function v(){}var w={};a(w,o,(function(){return this}));var b=Object.getPrototypeOf,_=b&&b(b(P([])));_&&_!==r&&n.call(_,o)&&(w=_);var E=v.prototype=m.prototype=Object.create(w);function S(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function I(t,e){function r(i,o,s,u){var a=f(t[i],t,o);if("throw"!==a.type){var h=a.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,u)}))}u(a.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function M(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,M(t,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var i=f(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,g;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,g):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function O(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function A(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function P(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i=0;--o){var s=this.tryEntries[o],u=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var a=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(a&&h){if(this.prev=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),O(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;O(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:P(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}({exports:{}});const o=2147483648;var s=function(t){if(!Array.isArray(t))throw new Error("Input must be an Array");if(0===t.length)throw new Error("Path must contain at least one level");for(var e=0;e=o)throw new Error("Invalid child index");if("h"===u[2]||"H"===u[2]||"'"===u[2])n[i]+=o;else if(0!=u[2].length)throw new Error("Invalid modifier")}return new s(n)},s.prototype.toPathArray=function(){return this.path},s.prototype.toString=function(t,e){for(var r=new Array(this.path.length),n=0;n"};var u=s,a=i(Object.freeze({__proto__:null,default:{}})),h=a.createHash,f={exports:{}},c=[],l=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,d=!1;function g(){d=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;e>18&63]+c[i>>12&63]+c[i>>6&63]+c[63&i]);return o.join("")}function y(t){var e;d||g();for(var r=t.length,n=r%3,i="",o=[],s=16383,u=0,a=r-n;ua?a:u+s));return 1===n?(e=t[r-1],i+=c[e>>2],i+=c[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=c[e>>10],i+=c[e>>4&63],i+=c[e<<2&63],i+="="),o.push(i),o.join("")}function v(t,e,r,n,i){var o,s,u=8*i-n-1,a=(1<>1,f=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-f)-1,p>>=-f,f+=u;f>0;o=256*o+t[e+c],c+=l,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+c],c+=l,f-=8);if(0===o)o=1-h;else{if(o===a)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)}function w(t,e,r,n,i,o){var s,u,a,h=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),(e+=s+c>=1?l/a:l*Math.pow(2,1-c))*a>=2&&(s++,a/=2),s+c>=f?(u=0,s=f):s+c>=1?(u=(e*a-1)*Math.pow(2,i),s+=c):(u=e*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&u,p+=d,u/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,h-=8);t[r+p-d]|=128*g}var b={}.toString,_=Array.isArray||function(t){return"[object Array]"==b.call(t)};M.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT;var E=S();function S(){return M.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function I(t,e){if(S()=S())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+S().toString(16)+" bytes");return 0|t}function R(t){return!(null==t||!t._isBuffer)}function N(t,e){if(R(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ot(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return st(t).length;default:if(n)return ot(t).length;e=(""+e).toLowerCase(),n=!0}}function x(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return z(this,e,r);case"utf8":case"utf-8":return K(this,e,r);case"ascii":return V(this,e,r);case"latin1":case"binary":return $(this,e,r);case"base64":return G(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function B(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function L(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=M.from(e,n)),R(e))return 0===e.length?-1:U(t,e,r,n,i);if("number"==typeof e)return e&=255,M.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):U(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function U(t,e,r,n,i){var o,s=1,u=t.length,a=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,u/=2,a/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;ou&&(r=u-a),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function G(t,e,r){return 0===e&&r===t.length?y(t):y(t.slice(e,r))}function K(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(a=(31&h)<<6|63&o)>127&&(f=a);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(a=(15&h)<<12|(63&o)<<6|63&s)>2047&&(a<55296||a>57343)&&(f=a);break;case 4:o=t[i+1],s=t[i+2],u=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&u)&&(a=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&u)>65535&&a<1114112&&(f=a)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=W)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),""},M.prototype.compare=function(t,e,r,n,i){if(!R(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(e>>>=0),u=Math.min(o,s),a=this.slice(n,i),h=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return C(this,t,e,r);case"utf8":case"utf-8":return D(this,t,e,r);case"ascii":return H(this,t,e,r);case"latin1":case"binary":return F(this,t,e,r);case"base64":return j(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},M.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var W=4096;function V(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function J(t,e,r,n,i,o){if(!R(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function Z(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function Q(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function tt(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function et(t,e,r,n,i){return i||tt(t,0,r,4),w(t,e,r,n,23,4),r+4}function rt(t,e,r,n,i){return i||tt(t,0,r,8),w(t,e,r,n,52,8),r+8}M.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},M.prototype.readUInt8=function(t,e){return e||Y(t,1,this.length),this[t]},M.prototype.readUInt16LE=function(t,e){return e||Y(t,2,this.length),this[t]|this[t+1]<<8},M.prototype.readUInt16BE=function(t,e){return e||Y(t,2,this.length),this[t]<<8|this[t+1]},M.prototype.readUInt32LE=function(t,e){return e||Y(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},M.prototype.readUInt32BE=function(t,e){return e||Y(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},M.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||Y(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},M.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||Y(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},M.prototype.readInt8=function(t,e){return e||Y(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},M.prototype.readInt16LE=function(t,e){e||Y(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},M.prototype.readInt16BE=function(t,e){e||Y(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},M.prototype.readInt32LE=function(t,e){return e||Y(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},M.prototype.readInt32BE=function(t,e){return e||Y(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},M.prototype.readFloatLE=function(t,e){return e||Y(t,4,this.length),v(this,t,!0,23,4)},M.prototype.readFloatBE=function(t,e){return e||Y(t,4,this.length),v(this,t,!1,23,4)},M.prototype.readDoubleLE=function(t,e){return e||Y(t,8,this.length),v(this,t,!0,52,8)},M.prototype.readDoubleBE=function(t,e){return e||Y(t,8,this.length),v(this,t,!1,52,8)},M.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||J(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},M.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,1,255,0),M.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},M.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,65535,0),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Z(this,t,e,!0),e+2},M.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,65535,0),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Z(this,t,e,!1),e+2},M.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,4294967295,0),M.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Q(this,t,e,!0),e+4},M.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,4294967295,0),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Q(this,t,e,!1),e+4},M.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);J(this,t,e,r,i-1,-i)}var o=0,s=1,u=0;for(this[e]=255&t;++o>0)-u&255;return e+r},M.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);J(this,t,e,r,i-1,-i)}var o=r-1,s=1,u=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===u&&0!==this[e+o+1]&&(u=1),this[e+o]=(t/s>>0)-u&255;return e+r},M.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,1,127,-128),M.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},M.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,32767,-32768),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):Z(this,t,e,!0),e+2},M.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,2,32767,-32768),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):Z(this,t,e,!1),e+2},M.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,2147483647,-2147483648),M.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Q(this,t,e,!0),e+4},M.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||J(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),M.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Q(this,t,e,!1),e+4},M.prototype.writeFloatLE=function(t,e,r){return et(this,t,e,!0,r)},M.prototype.writeFloatBE=function(t,e,r){return et(this,t,e,!1,r)},M.prototype.writeDoubleLE=function(t,e,r){return rt(this,t,e,!0,r)},M.prototype.writeDoubleBE=function(t,e,r){return rt(this,t,e,!1,r)},M.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!M.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function st(t){return function(t){var e,r,n,i,o,s;d||g();var u=t.length;if(u%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===t[u-2]?2:"="===t[u-1]?1:0,s=new p(3*u/4-o),n=o>0?u-4:u;var a=0;for(e=0,r=0;e>16&255,s[a++]=i>>8&255,s[a++]=255&i;return 2===o?(i=l[t.charCodeAt(e)]<<2|l[t.charCodeAt(e+1)]>>4,s[a++]=255&i):1===o&&(i=l[t.charCodeAt(e)]<<10|l[t.charCodeAt(e+1)]<<4|l[t.charCodeAt(e+2)]>>2,s[a++]=i>>8&255,s[a++]=255&i),s}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(nt,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function ut(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function at(t){return null!=t&&(!!t._isBuffer||ht(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&ht(t.slice(0,0))}(t))}function ht(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}var ft=i(Object.freeze({__proto__:null,INSPECT_MAX_BYTES:50,kMaxLength:E,Buffer:M,SlowBuffer:function(t){return+t!=t&&(t=0),M.alloc(+t)},isBuffer:at})); -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -!function(t,e){var r=ft,n=r.Buffer;function i(t,e){for(var r in t)e[r]=t[r]}function o(t,e,r){return n(t,e,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?t.exports=r:(i(r,e),e.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return n(t,e,r)},o.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=n(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},o.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return n(t)},o.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}}(f,f.exports);var ct=f.exports.Buffer;var lt=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r>>0,h=new Uint8Array(o);t[r];){var f=e[t.charCodeAt(r)];if(255===f)return;for(var c=0,l=o-1;(0!==f||c>>0,h[l]=f%256>>>0,f=f/256>>>0;if(0!==f)throw new Error("Non-zero carry");i=c,r++}for(var p=o-i;p!==o&&0===h[p];)p++;var d=ct.allocUnsafe(n+(o-p));d.fill(0,0,n);for(var g=n;p!==o;)d[g++]=h[p++];return d}return{encode:function(e){if((Array.isArray(e)||e instanceof Uint8Array)&&(e=ct.from(e)),!ct.isBuffer(e))throw new TypeError("Expected Buffer");if(0===e.length)return"";for(var r=0,n=0,i=0,o=e.length;i!==o&&0===e[i];)i++,r++;for(var a=(o-i)*h+1>>>0,f=new Uint8Array(a);i!==o;){for(var c=e[i],l=0,p=a-1;(0!==c||l>>0,f[p]=c%s>>>0,c=c/s>>>0;if(0!==c)throw new Error("Non-zero carry");n=l,i++}for(var d=a-n;d!==a&&0===f[d];)d++;for(var g=u.repeat(r);d=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,m=0|s[2],y=8191&m,v=m>>>13,w=0|s[3],b=8191&w,_=w>>>13,E=0|s[4],S=8191&E,I=E>>>13,M=0|s[5],T=8191&M,O=M>>>13,A=0|s[6],P=8191&A,k=A>>>13,R=0|s[7],N=8191&R,x=R>>>13,B=0|s[8],L=8191&B,U=B>>>13,C=0|s[9],D=8191&C,H=C>>>13,F=0|u[0],j=8191&F,q=F>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var mt=(h+(n=Math.imul(c,j))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,j)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(d,j),i=(i=Math.imul(d,q))+Math.imul(g,j)|0,o=Math.imul(g,q);var yt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(y,j),i=(i=Math.imul(y,q))+Math.imul(v,j)|0,o=Math.imul(v,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var vt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(b,j),i=(i=Math.imul(b,q))+Math.imul(_,j)|0,o=Math.imul(_,q),n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,j),i=(i=Math.imul(S,q))+Math.imul(I,j)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,W)|0,n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,j),i=(i=Math.imul(T,q))+Math.imul(O,j)|0,o=Math.imul(O,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var _t=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(P,j),i=(i=Math.imul(P,q))+Math.imul(k,j)|0,o=Math.imul(k,q),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,tt)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var Et=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(N,j),i=(i=Math.imul(N,q))+Math.imul(x,j)|0,o=Math.imul(x,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,W)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,z)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,n=n+Math.imul(y,rt)|0,i=(i=i+Math.imul(y,nt)|0)+Math.imul(v,rt)|0,o=o+Math.imul(v,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(L,j),i=(i=Math.imul(L,q))+Math.imul(U,j)|0,o=Math.imul(U,q),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(O,Y)|0,o=o+Math.imul(O,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,o=o+Math.imul(_,nt)|0,n=n+Math.imul(y,ot)|0,i=(i=i+Math.imul(y,st)|0)+Math.imul(v,ot)|0,o=o+Math.imul(v,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,j),i=(i=Math.imul(D,q))+Math.imul(H,j)|0,o=Math.imul(H,q),n=n+Math.imul(L,K)|0,i=(i=i+Math.imul(L,W)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(_,ot)|0,o=o+Math.imul(_,st)|0,n=n+Math.imul(y,at)|0,i=(i=i+Math.imul(y,ht)|0)+Math.imul(v,at)|0,o=o+Math.imul(v,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Mt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(O,rt)|0,o=o+Math.imul(O,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(_,at)|0,o=o+Math.imul(_,ht)|0,n=n+Math.imul(y,ct)|0,i=(i=i+Math.imul(y,lt)|0)+Math.imul(v,ct)|0,o=o+Math.imul(v,lt)|0;var Tt=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(L,Y)|0,i=(i=i+Math.imul(L,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(T,ot)|0,i=(i=i+Math.imul(T,st)|0)+Math.imul(O,ot)|0,o=o+Math.imul(O,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(_,ct)|0,o=o+Math.imul(_,lt)|0;var Ot=(h+(n=n+Math.imul(y,dt)|0)|0)+((8191&(i=(i=i+Math.imul(y,gt)|0)+Math.imul(v,dt)|0))<<13)|0;h=((o=o+Math.imul(v,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(x,rt)|0,o=o+Math.imul(x,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ht)|0)+Math.imul(O,at)|0,o=o+Math.imul(O,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var At=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;h=((o=o+Math.imul(_,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(x,ot)|0,o=o+Math.imul(x,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(T,ct)|0,i=(i=i+Math.imul(T,lt)|0)+Math.imul(O,ct)|0,o=o+Math.imul(O,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(L,ot)|0,i=(i=i+Math.imul(L,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(x,at)|0,o=o+Math.imul(x,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(k,ct)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(O,dt)|0))<<13)|0;h=((o=o+Math.imul(O,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(x,ct)|0,o=o+Math.imul(x,lt)|0;var Rt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(L,ct)|0,i=(i=i+Math.imul(L,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(x,dt)|0))<<13)|0;h=((o=o+Math.imul(x,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var xt=(h+(n=n+Math.imul(L,dt)|0)|0)+((8191&(i=(i=i+Math.imul(L,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=mt,a[1]=yt,a[2]=vt,a[3]=wt,a[4]=bt,a[5]=_t,a[6]=Et,a[7]=St,a[8]=It,a[9]=Mt,a[10]=Tt,a[11]=Ot,a[12]=At,a[13]=Pt,a[14]=kt,a[15]=Rt,a[16]=Nt,a[17]=xt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new E(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};function y(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){E.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}y.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},y.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},y.prototype.split=function(t,e){t.iushrn(this.n,0,e)},y.prototype.imulK=function(t){return t.imul(this.k)},n(v,y),v.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},v.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(m[t])return m[t];var e;if("k256"===t)e=new v;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return m[t]=e,e},E.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},E.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},E.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},E.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},E.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},E.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},E.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},E.prototype.isqr=function(t){return this.imul(t,t.clone())},E.prototype.sqr=function(t){return this.mul(t,t)},E.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,m=0;0!==g.cmp(u);m++)g=g.redSqr();r(m=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},E.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},E.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,E),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(xt);var Bt={},Lt="6.5.4",Ut={},Ct={exports:{}};!function(t){!function(t,e){function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){if(i.isBN(t))return t;this.negative=0,this.words=null,this.length=0,this.red=null,null!==t&&("le"!==e&&"be"!==e||(r=e,e=10),this._init(t||0,e||10,r||"be"))}var o;"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:require("buffer").Buffer}catch(t){}function s(t,e){var r=t.charCodeAt(e);return r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function u(t,e,r){var n=s(t,r);return r-1>=e&&(n|=s(t,r-1)<<4),n}function a(t,e,r,n){for(var i=0,o=Math.min(t.length,r),s=e;s=49?u-49+10:u>=17?u-17+10:u}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i=0;i-=3)s=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[o]|=s<>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);else if("le"===n)for(i=0,o=0;i>>26-u&67108863,(u+=24)>=26&&(u-=26,o++);return this.strip()},i.prototype._parseHex=function(t,e,r){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var n=0;n=e;n-=2)i=u(t,e,n)<=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(t.length-e)%2==0?e+1:e;n=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var o=t.length-r,s=o%n,u=Math.min(o,o-s)+r,h=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var h=["","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"],f=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],o=0|e.words[0],s=i*o,u=67108863&s,a=s/67108864|0;r.words[0]=u;for(var h=1;h>>26,c=67108863&a,l=Math.min(h,e.length-1),p=Math.max(0,h-t.length+1);p<=l;p++){var d=h-p|0;f+=(s=(i=0|t.words[d])*(o=0|e.words[p])+c)/67108864|0,c=67108863&s}r.words[h]=0|c,a=0|f}return 0!==a?r.words[h]=0|a:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(e=0|e||1,16===(t=t||10)||"hex"===t){n="";for(var i=0,o=0,s=0;s>>24-i&16777215)||s!==this.length-1?h[6-a.length]+a+n:a+n,(i+=2)>=26&&(i-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var l=f[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:h[l-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==o),this.toArrayLike(o,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0"),this.strip();var s,u,a="le"===e,h=new t(o),f=this.clone();if(a){for(u=0;!f.isZero();u++)s=f.andln(255),f.iushrn(8),h[u]=s;for(;u=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;ot.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&e;for(;0!==o&&s>26,this.words[s]=67108863&e;if(0===o&&s>>13,p=0|s[1],d=8191&p,g=p>>>13,m=0|s[2],y=8191&m,v=m>>>13,w=0|s[3],b=8191&w,_=w>>>13,E=0|s[4],S=8191&E,I=E>>>13,M=0|s[5],T=8191&M,O=M>>>13,A=0|s[6],P=8191&A,k=A>>>13,R=0|s[7],N=8191&R,x=R>>>13,B=0|s[8],L=8191&B,U=B>>>13,C=0|s[9],D=8191&C,H=C>>>13,F=0|u[0],j=8191&F,q=F>>>13,G=0|u[1],K=8191&G,W=G>>>13,V=0|u[2],$=8191&V,z=V>>>13,X=0|u[3],Y=8191&X,J=X>>>13,Z=0|u[4],Q=8191&Z,tt=Z>>>13,et=0|u[5],rt=8191&et,nt=et>>>13,it=0|u[6],ot=8191&it,st=it>>>13,ut=0|u[7],at=8191&ut,ht=ut>>>13,ft=0|u[8],ct=8191&ft,lt=ft>>>13,pt=0|u[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var mt=(h+(n=Math.imul(c,j))|0)+((8191&(i=(i=Math.imul(c,q))+Math.imul(l,j)|0))<<13)|0;h=((o=Math.imul(l,q))+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(d,j),i=(i=Math.imul(d,q))+Math.imul(g,j)|0,o=Math.imul(g,q);var yt=(h+(n=n+Math.imul(c,K)|0)|0)+((8191&(i=(i=i+Math.imul(c,W)|0)+Math.imul(l,K)|0))<<13)|0;h=((o=o+Math.imul(l,W)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(y,j),i=(i=Math.imul(y,q))+Math.imul(v,j)|0,o=Math.imul(v,q),n=n+Math.imul(d,K)|0,i=(i=i+Math.imul(d,W)|0)+Math.imul(g,K)|0,o=o+Math.imul(g,W)|0;var vt=(h+(n=n+Math.imul(c,$)|0)|0)+((8191&(i=(i=i+Math.imul(c,z)|0)+Math.imul(l,$)|0))<<13)|0;h=((o=o+Math.imul(l,z)|0)+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(b,j),i=(i=Math.imul(b,q))+Math.imul(_,j)|0,o=Math.imul(_,q),n=n+Math.imul(y,K)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,W)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,z)|0)+Math.imul(g,$)|0,o=o+Math.imul(g,z)|0;var wt=(h+(n=n+Math.imul(c,Y)|0)|0)+((8191&(i=(i=i+Math.imul(c,J)|0)+Math.imul(l,Y)|0))<<13)|0;h=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(S,j),i=(i=Math.imul(S,q))+Math.imul(I,j)|0,o=Math.imul(I,q),n=n+Math.imul(b,K)|0,i=(i=i+Math.imul(b,W)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,W)|0,n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,z)|0)+Math.imul(v,$)|0,o=o+Math.imul(v,z)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,J)|0)+Math.imul(g,Y)|0,o=o+Math.imul(g,J)|0;var bt=(h+(n=n+Math.imul(c,Q)|0)|0)+((8191&(i=(i=i+Math.imul(c,tt)|0)+Math.imul(l,Q)|0))<<13)|0;h=((o=o+Math.imul(l,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,j),i=(i=Math.imul(T,q))+Math.imul(O,j)|0,o=Math.imul(O,q),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,W)|0)+Math.imul(I,K)|0,o=o+Math.imul(I,W)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,z)|0)+Math.imul(_,$)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(d,Q)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,tt)|0;var _t=(h+(n=n+Math.imul(c,rt)|0)|0)+((8191&(i=(i=i+Math.imul(c,nt)|0)+Math.imul(l,rt)|0))<<13)|0;h=((o=o+Math.imul(l,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(P,j),i=(i=Math.imul(P,q))+Math.imul(k,j)|0,o=Math.imul(k,q),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,W)|0)+Math.imul(O,K)|0,o=o+Math.imul(O,W)|0,n=n+Math.imul(S,$)|0,i=(i=i+Math.imul(S,z)|0)+Math.imul(I,$)|0,o=o+Math.imul(I,z)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,J)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,tt)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,o=o+Math.imul(g,nt)|0;var Et=(h+(n=n+Math.imul(c,ot)|0)|0)+((8191&(i=(i=i+Math.imul(c,st)|0)+Math.imul(l,ot)|0))<<13)|0;h=((o=o+Math.imul(l,st)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(N,j),i=(i=Math.imul(N,q))+Math.imul(x,j)|0,o=Math.imul(x,q),n=n+Math.imul(P,K)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(k,K)|0,o=o+Math.imul(k,W)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,z)|0)+Math.imul(O,$)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(S,Y)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(I,Y)|0,o=o+Math.imul(I,J)|0,n=n+Math.imul(b,Q)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,tt)|0,n=n+Math.imul(y,rt)|0,i=(i=i+Math.imul(y,nt)|0)+Math.imul(v,rt)|0,o=o+Math.imul(v,nt)|0,n=n+Math.imul(d,ot)|0,i=(i=i+Math.imul(d,st)|0)+Math.imul(g,ot)|0,o=o+Math.imul(g,st)|0;var St=(h+(n=n+Math.imul(c,at)|0)|0)+((8191&(i=(i=i+Math.imul(c,ht)|0)+Math.imul(l,at)|0))<<13)|0;h=((o=o+Math.imul(l,ht)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(L,j),i=(i=Math.imul(L,q))+Math.imul(U,j)|0,o=Math.imul(U,q),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,W)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,W)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,z)|0)+Math.imul(k,$)|0,o=o+Math.imul(k,z)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(O,Y)|0,o=o+Math.imul(O,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,tt)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,o=o+Math.imul(_,nt)|0,n=n+Math.imul(y,ot)|0,i=(i=i+Math.imul(y,st)|0)+Math.imul(v,ot)|0,o=o+Math.imul(v,st)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ht)|0)+Math.imul(g,at)|0,o=o+Math.imul(g,ht)|0;var It=(h+(n=n+Math.imul(c,ct)|0)|0)+((8191&(i=(i=i+Math.imul(c,lt)|0)+Math.imul(l,ct)|0))<<13)|0;h=((o=o+Math.imul(l,lt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863,n=Math.imul(D,j),i=(i=Math.imul(D,q))+Math.imul(H,j)|0,o=Math.imul(H,q),n=n+Math.imul(L,K)|0,i=(i=i+Math.imul(L,W)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,W)|0,n=n+Math.imul(N,$)|0,i=(i=i+Math.imul(N,z)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,z)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,J)|0)+Math.imul(k,Y)|0,o=o+Math.imul(k,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,tt)|0,n=n+Math.imul(S,rt)|0,i=(i=i+Math.imul(S,nt)|0)+Math.imul(I,rt)|0,o=o+Math.imul(I,nt)|0,n=n+Math.imul(b,ot)|0,i=(i=i+Math.imul(b,st)|0)+Math.imul(_,ot)|0,o=o+Math.imul(_,st)|0,n=n+Math.imul(y,at)|0,i=(i=i+Math.imul(y,ht)|0)+Math.imul(v,at)|0,o=o+Math.imul(v,ht)|0,n=n+Math.imul(d,ct)|0,i=(i=i+Math.imul(d,lt)|0)+Math.imul(g,ct)|0,o=o+Math.imul(g,lt)|0;var Mt=(h+(n=n+Math.imul(c,dt)|0)|0)+((8191&(i=(i=i+Math.imul(c,gt)|0)+Math.imul(l,dt)|0))<<13)|0;h=((o=o+Math.imul(l,gt)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(D,K),i=(i=Math.imul(D,W))+Math.imul(H,K)|0,o=Math.imul(H,W),n=n+Math.imul(L,$)|0,i=(i=i+Math.imul(L,z)|0)+Math.imul(U,$)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(N,Y)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(O,rt)|0,o=o+Math.imul(O,nt)|0,n=n+Math.imul(S,ot)|0,i=(i=i+Math.imul(S,st)|0)+Math.imul(I,ot)|0,o=o+Math.imul(I,st)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ht)|0)+Math.imul(_,at)|0,o=o+Math.imul(_,ht)|0,n=n+Math.imul(y,ct)|0,i=(i=i+Math.imul(y,lt)|0)+Math.imul(v,ct)|0,o=o+Math.imul(v,lt)|0;var Tt=(h+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;h=((o=o+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(D,$),i=(i=Math.imul(D,z))+Math.imul(H,$)|0,o=Math.imul(H,z),n=n+Math.imul(L,Y)|0,i=(i=i+Math.imul(L,J)|0)+Math.imul(U,Y)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(k,rt)|0,o=o+Math.imul(k,nt)|0,n=n+Math.imul(T,ot)|0,i=(i=i+Math.imul(T,st)|0)+Math.imul(O,ot)|0,o=o+Math.imul(O,st)|0,n=n+Math.imul(S,at)|0,i=(i=i+Math.imul(S,ht)|0)+Math.imul(I,at)|0,o=o+Math.imul(I,ht)|0,n=n+Math.imul(b,ct)|0,i=(i=i+Math.imul(b,lt)|0)+Math.imul(_,ct)|0,o=o+Math.imul(_,lt)|0;var Ot=(h+(n=n+Math.imul(y,dt)|0)|0)+((8191&(i=(i=i+Math.imul(y,gt)|0)+Math.imul(v,dt)|0))<<13)|0;h=((o=o+Math.imul(v,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(D,Y),i=(i=Math.imul(D,J))+Math.imul(H,Y)|0,o=Math.imul(H,J),n=n+Math.imul(L,Q)|0,i=(i=i+Math.imul(L,tt)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,tt)|0,n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(x,rt)|0,o=o+Math.imul(x,nt)|0,n=n+Math.imul(P,ot)|0,i=(i=i+Math.imul(P,st)|0)+Math.imul(k,ot)|0,o=o+Math.imul(k,st)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ht)|0)+Math.imul(O,at)|0,o=o+Math.imul(O,ht)|0,n=n+Math.imul(S,ct)|0,i=(i=i+Math.imul(S,lt)|0)+Math.imul(I,ct)|0,o=o+Math.imul(I,lt)|0;var At=(h+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;h=((o=o+Math.imul(_,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(D,Q),i=(i=Math.imul(D,tt))+Math.imul(H,Q)|0,o=Math.imul(H,tt),n=n+Math.imul(L,rt)|0,i=(i=i+Math.imul(L,nt)|0)+Math.imul(U,rt)|0,o=o+Math.imul(U,nt)|0,n=n+Math.imul(N,ot)|0,i=(i=i+Math.imul(N,st)|0)+Math.imul(x,ot)|0,o=o+Math.imul(x,st)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ht)|0)+Math.imul(k,at)|0,o=o+Math.imul(k,ht)|0,n=n+Math.imul(T,ct)|0,i=(i=i+Math.imul(T,lt)|0)+Math.imul(O,ct)|0,o=o+Math.imul(O,lt)|0;var Pt=(h+(n=n+Math.imul(S,dt)|0)|0)+((8191&(i=(i=i+Math.imul(S,gt)|0)+Math.imul(I,dt)|0))<<13)|0;h=((o=o+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(D,rt),i=(i=Math.imul(D,nt))+Math.imul(H,rt)|0,o=Math.imul(H,nt),n=n+Math.imul(L,ot)|0,i=(i=i+Math.imul(L,st)|0)+Math.imul(U,ot)|0,o=o+Math.imul(U,st)|0,n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ht)|0)+Math.imul(x,at)|0,o=o+Math.imul(x,ht)|0,n=n+Math.imul(P,ct)|0,i=(i=i+Math.imul(P,lt)|0)+Math.imul(k,ct)|0,o=o+Math.imul(k,lt)|0;var kt=(h+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(O,dt)|0))<<13)|0;h=((o=o+Math.imul(O,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(D,ot),i=(i=Math.imul(D,st))+Math.imul(H,ot)|0,o=Math.imul(H,st),n=n+Math.imul(L,at)|0,i=(i=i+Math.imul(L,ht)|0)+Math.imul(U,at)|0,o=o+Math.imul(U,ht)|0,n=n+Math.imul(N,ct)|0,i=(i=i+Math.imul(N,lt)|0)+Math.imul(x,ct)|0,o=o+Math.imul(x,lt)|0;var Rt=(h+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(k,dt)|0))<<13)|0;h=((o=o+Math.imul(k,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(D,at),i=(i=Math.imul(D,ht))+Math.imul(H,at)|0,o=Math.imul(H,ht),n=n+Math.imul(L,ct)|0,i=(i=i+Math.imul(L,lt)|0)+Math.imul(U,ct)|0,o=o+Math.imul(U,lt)|0;var Nt=(h+(n=n+Math.imul(N,dt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(x,dt)|0))<<13)|0;h=((o=o+Math.imul(x,gt)|0)+(i>>>13)|0)+(Nt>>>26)|0,Nt&=67108863,n=Math.imul(D,ct),i=(i=Math.imul(D,lt))+Math.imul(H,ct)|0,o=Math.imul(H,lt);var xt=(h+(n=n+Math.imul(L,dt)|0)|0)+((8191&(i=(i=i+Math.imul(L,gt)|0)+Math.imul(U,dt)|0))<<13)|0;h=((o=o+Math.imul(U,gt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863;var Bt=(h+(n=Math.imul(D,dt))|0)+((8191&(i=(i=Math.imul(D,gt))+Math.imul(H,dt)|0))<<13)|0;return h=((o=Math.imul(H,gt))+(i>>>13)|0)+(Bt>>>26)|0,Bt&=67108863,a[0]=mt,a[1]=yt,a[2]=vt,a[3]=wt,a[4]=bt,a[5]=_t,a[6]=Et,a[7]=St,a[8]=It,a[9]=Mt,a[10]=Tt,a[11]=Ot,a[12]=At,a[13]=Pt,a[14]=kt,a[15]=Rt,a[16]=Nt,a[17]=xt,a[18]=Bt,0!==h&&(a[19]=h,r.length++),r};function d(t,e,r){return(new g).mulp(t,e,r)}function g(t,e){this.x=t,this.y=e}Math.imul||(p=l),i.prototype.mulTo=function(t,e){var r,n=this.length+t.length;return r=10===this.length&&10===t.length?p(this,t,e):n<63?l(this,t,e):n<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,s&=67108863}r.words[o]=u,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,t,e):d(this,t,e),r},g.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},g.prototype.permute=function(t,e,r,n,i,o){for(var s=0;s>>=1)i++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*e;s>=26,e+=i/67108864|0,e+=o>>>26,this.words[n]=67108863&o}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(e=0;e>>26-n}s&&(this.words[e]=s,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var o=t%26,s=Math.min((t-o)/26,this.length),u=67108863^67108863>>>o<s)for(this.length-=s,h=0;h=0&&(0!==f||h>=i);h--){var c=0|this.words[h];this.words[h]=f<<26-o|c>>>o,f=c&u}return a&&0!==f&&(a.words[a.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(a/67108864|0),this.words[i+n]=67108863&o}for(;i>26,this.words[i+n]=67108863&o;if(0===u)return this.strip();for(r(-1===u),u=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),o=t,s=0|o.words[o.length-1];0!==(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var u,a=n.length-o.length;if("mod"!==e){(u=new i(null)).length=a+1,u.words=new Array(u.length);for(var h=0;h=0;c--){var l=67108864*(0|n.words[o.length+c])+(0|n.words[o.length+c-1]);for(l=Math.min(l/s|0,67108863),n._ishlnsubmul(o,l,c);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(o,1,c),n.isZero()||(n.negative^=1);u&&(u.words[c]=l)}return u&&u.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:u||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(u=this.neg().divmod(t,e),"mod"!==e&&(o=u.div.neg()),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.iadd(t)),{div:o,mod:s}):0===this.negative&&0!==t.negative?(u=this.divmod(t.neg(),e),"mod"!==e&&(o=u.div.neg()),{div:o,mod:u.mod}):0!=(this.negative&t.negative)?(u=this.neg().divmod(t.neg(),e),"div"!==e&&(s=u.mod.neg(),n&&0!==s.negative&&s.isub(t)),{div:u.div,mod:s}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var o,s,u},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o=new i(1),s=new i(0),u=new i(0),a=new i(1),h=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++h;for(var f=n.clone(),c=e.clone();!e.isZero();){for(var l=0,p=1;0==(e.words[0]&p)&&l<26;++l,p<<=1);if(l>0)for(e.iushrn(l);l-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(f),s.isub(c)),o.iushrn(1),s.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(u.isOdd()||a.isOdd())&&(u.iadd(f),a.isub(c)),u.iushrn(1),a.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(u),s.isub(a)):(n.isub(e),u.isub(o),a.isub(s))}return{a:u,b:a,gcd:n.iushln(h)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var o,s=new i(1),u=new i(0),a=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var h=0,f=1;0==(e.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(e.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(a),s.iushrn(1);for(var c=0,l=1;0==(n.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(n.iushrn(c);c-- >0;)u.isOdd()&&u.iadd(a),u.iushrn(1);e.cmp(n)>=0?(e.isub(n),s.isub(u)):(n.isub(e),u.isub(s))}return(o=0===e.cmpn(1)?s:u).cmpn(0)<0&&o.iadd(t),o},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var o=e;e=r,r=o}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,u&=67108863,this.words[s]=u}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new E(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};function y(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function S(t){E.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}y.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},y.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},y.prototype.split=function(t,e){t.iushrn(this.n,0,e)},y.prototype.imulK=function(t){return t.imul(this.k)},n(v,y),v.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;i>>22,o=s}o>>>=22,t.words[i-10]=o,0===o&&t.length>10?t.length-=10:t.length-=9},v.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(m[t])return m[t];var e;if("k256"===t)e=new v;else if("p224"===t)e=new w;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new _}return m[t]=e,e},E.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},E.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},E.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},E.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},E.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},E.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},E.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},E.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},E.prototype.isqr=function(t){return this.imul(t,t.clone())},E.prototype.sqr=function(t){return this.mul(t,t)},E.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var u=new i(1).toRed(this),a=u.redNeg(),h=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,h).cmp(a);)f.redIAdd(a);for(var c=this.pow(f,o),l=this.pow(t,o.addn(1).iushrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(u);){for(var g=p,m=0;0!==g.cmp(u);m++)g=g.redSqr();r(m=0;n--){for(var h=e.words[n],f=a-1;f>=0;f--){var c=h>>f&1;o!==r[0]&&(o=this.sqr(o)),0!==c||0!==s?(s<<=1,s|=c,(4===++u||0===n&&0===f)&&(o=this.mul(o,r[s]),u=0,s=0)):u=0}a=26}return o},E.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},E.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new S(t)},n(S,E),S.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},S.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},S.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,r)}(Ct);var Dt=Ht;function Ht(t,e){if(!t)throw new Error(e||"Assertion failed")}Ht.equal=function(t,e,r){if(t!=e)throw new Error(r||"Assertion failed: "+t+" != "+e)};var Ft={};!function(t){var e=t;function r(t){return 1===t.length?"0"+t:t}function n(t){for(var e="",n=0;n>8,s=255&i;o?r.push(o,s):r.push(s)}return r},e.zero2=r,e.toHex=n,e.encode=function(t,e){return"hex"===e?n(t):t}}(Ft),function(t){var e=t,r=Ct.exports,n=Dt,i=Ft;e.assert=n,e.toArray=i.toArray,e.zero2=i.zero2,e.toHex=i.toHex,e.encode=i.encode,e.getNAF=function(t,e,r){var n=new Array(Math.max(t.bitLength(),r)+1);n.fill(0);for(var i=1<(i>>1)-1?(i>>1)-a:a,o.isubn(u)):u=0,n[s]=u,o.iushrn(1)}return n},e.getJSF=function(t,e){var r=[[],[]];t=t.clone(),e=e.clone();for(var n,i=0,o=0;t.cmpn(-i)>0||e.cmpn(-o)>0;){var s,u,a=t.andln(3)+i&3,h=e.andln(3)+o&3;3===a&&(a=-1),3===h&&(h=-1),s=0==(1&a)?0:3!==(n=t.andln(7)+i&7)&&5!==n||2!==h?a:-a,r[0].push(s),u=0==(1&h)?0:3!==(n=e.andln(7)+o&7)&&5!==n||2!==a?h:-h,r[1].push(u),2*i===s+1&&(i=1-i),2*o===u+1&&(o=1-o),t.iushrn(1),e.iushrn(1)}return r},e.cachedProperty=function(t,e,r){var n="_"+e;t.prototype[e]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},e.parseBytes=function(t){return"string"==typeof t?e.toArray(t,"hex"):t},e.intFromLE=function(t){return new r(t,"hex","le")}}(Ut);var jt,qt={exports:{}};function Gt(t){this.rand=t}if(qt.exports=function(t){return jt||(jt=new Gt(null)),jt.generate(t)},qt.exports.Rand=Gt,Gt.prototype.generate=function(t){return this._rand(t)},Gt.prototype._rand=function(t){if(this.rand.getBytes)return this.rand.getBytes(t);for(var e=new Uint8Array(t),r=0;r0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var Zt=Jt;function Qt(t,e){this.curve=t,this.type=e,this.precomputed=null}Jt.prototype.point=function(){throw new Error("Not implemented")},Jt.prototype.validate=function(){throw new Error("Not implemented")},Jt.prototype._fixedNafMul=function(t,e){Yt(t.precomputed);var r=t._getDoubles(),n=zt(e,1,this._bitLength),i=(1<=o;a--)s=(s<<1)+n[a];u.push(s)}for(var h=this.jpoint(null,null,null),f=this.jpoint(null,null,null),c=i;c>0;c--){for(o=0;o=0;u--){for(var a=0;u>=0&&0===o[u];u--)a++;if(u>=0&&a++,s=s.dblp(a),u<0)break;var h=o[u];Yt(0!==h),s="affine"===t.type?h>0?s.mixedAdd(i[h-1>>1]):s.mixedAdd(i[-h-1>>1].neg()):h>0?s.add(i[h-1>>1]):s.add(i[-h-1>>1].neg())}return"affine"===t.type?s.toP():s},Jt.prototype._wnafMulAdd=function(t,e,r,n,i){var o,s,u,a=this._wnafT1,h=this._wnafT2,f=this._wnafT3,c=0;for(o=0;o=1;o-=2){var p=o-1,d=o;if(1===a[p]&&1===a[d]){var g=[e[p],null,null,e[d]];0===e[p].y.cmp(e[d].y)?(g[1]=e[p].add(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg())):0===e[p].y.cmp(e[d].y.redNeg())?(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].add(e[d].neg())):(g[1]=e[p].toJ().mixedAdd(e[d]),g[2]=e[p].toJ().mixedAdd(e[d].neg()));var m=[-3,-1,-5,-7,0,7,5,1,3],y=Xt(r[p],r[d]);for(c=Math.max(y[0].length,c),f[p]=new Array(c),f[d]=new Array(c),s=0;s=0;o--){for(var E=0;o>=0;){var S=!0;for(s=0;s=0&&E++,b=b.dblp(E),o<0)break;for(s=0;s0?u=h[s][I-1>>1]:I<0&&(u=h[s][-I-1>>1].neg()),b="affine"===u.type?b.mixedAdd(u):b.add(u))}}for(o=0;o=Math.ceil((t.bitLength()+1)/e.step)},Qt.prototype._getDoubles=function(t,e){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i=0&&(o=e,s=r),n.negative&&(n=n.neg(),i=i.neg()),o.negative&&(o=o.neg(),s=s.neg()),[{a:n,b:i},{a:o,b:s}]},ae.prototype._endoSplit=function(t){var e=this.endo.basis,r=e[0],n=e[1],i=n.b.mul(t).divRound(this.n),o=r.b.neg().mul(t).divRound(this.n),s=i.mul(r.a),u=o.mul(n.a),a=i.mul(r.b),h=o.mul(n.b);return{k1:t.sub(s).sub(u),k2:a.add(h).neg()}},ae.prototype.pointFromX=function(t,e){(t=new ie(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr().redMul(t).redIAdd(t.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(e&&!i||!e&&i)&&(n=n.redNeg()),this.point(t,n)},ae.prototype.validate=function(t){if(t.inf)return!0;var e=t.x,r=t.y,n=this.a.redMul(e),i=e.redSqr().redMul(e).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},ae.prototype._endoWnafMulAdd=function(t,e,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},fe.prototype.isInfinity=function(){return this.inf},fe.prototype.add=function(t){if(this.inf)return t;if(t.inf)return this;if(this.eq(t))return this.dbl();if(this.neg().eq(t))return this.curve.point(null,null);if(0===this.x.cmp(t.x))return this.curve.point(null,null);var e=this.y.redSub(t.y);0!==e.cmpn(0)&&(e=e.redMul(this.x.redSub(t.x).redInvm()));var r=e.redSqr().redISub(this.x).redISub(t.x),n=e.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},fe.prototype.dbl=function(){if(this.inf)return this;var t=this.y.redAdd(this.y);if(0===t.cmpn(0))return this.curve.point(null,null);var e=this.curve.a,r=this.x.redSqr(),n=t.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(e).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),s=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},fe.prototype.getX=function(){return this.x.fromRed()},fe.prototype.getY=function(){return this.y.fromRed()},fe.prototype.mul=function(t){return t=new ie(t,16),this.isInfinity()?this:this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve.endo?this.curve._endoWnafMulAdd([this],[t]):this.curve._wnafMul(this,t)},fe.prototype.mulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},fe.prototype.jmulAdd=function(t,e,r){var n=[this,e],i=[t,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},fe.prototype.eq=function(t){return this===t||this.inf===t.inf&&(this.inf||0===this.x.cmp(t.x)&&0===this.y.cmp(t.y))},fe.prototype.neg=function(t){if(this.inf)return this;var e=this.curve.point(this.x,this.y.redNeg());if(t&&this.precomputed){var r=this.precomputed,n=function(t){return t.neg()};e.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return e},fe.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},oe(ce,se.BasePoint),ae.prototype.jpoint=function(t,e,r){return new ce(this,t,e,r)},ce.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var t=this.z.redInvm(),e=t.redSqr(),r=this.x.redMul(e),n=this.y.redMul(e).redMul(t);return this.curve.point(r,n)},ce.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},ce.prototype.add=function(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(e),i=t.x.redMul(r),o=this.y.redMul(e.redMul(t.z)),s=t.y.redMul(r.redMul(this.z)),u=n.redSub(i),a=o.redSub(s);if(0===u.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h=u.redSqr(),f=h.redMul(u),c=n.redMul(h),l=a.redSqr().redIAdd(f).redISub(c).redISub(c),p=a.redMul(c.redISub(l)).redISub(o.redMul(f)),d=this.z.redMul(t.z).redMul(u);return this.curve.jpoint(l,p,d)},ce.prototype.mixedAdd=function(t){if(this.isInfinity())return t.toJ();if(t.isInfinity())return this;var e=this.z.redSqr(),r=this.x,n=t.x.redMul(e),i=this.y,o=t.y.redMul(e).redMul(this.z),s=r.redSub(n),u=i.redSub(o);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var a=s.redSqr(),h=a.redMul(s),f=r.redMul(a),c=u.redSqr().redIAdd(h).redISub(f).redISub(f),l=u.redMul(f.redISub(c)).redISub(i.redMul(h)),p=this.z.redMul(s);return this.curve.jpoint(c,l,p)},ce.prototype.dblp=function(t){if(0===t)return this;if(this.isInfinity())return this;if(!t)return this.dbl();var e;if(this.curve.zeroA||this.curve.threeA){var r=this;for(e=0;e=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},ce.prototype.inspect=function(){return this.isInfinity()?"":""},ce.prototype.isInfinity=function(){return 0===this.z.cmpn(0)};var le=Ct.exports,pe=te.exports,de=Zt,ge=Ut;function me(t){de.call(this,"mont",t),this.a=new le(t.a,16).toRed(this.red),this.b=new le(t.b,16).toRed(this.red),this.i4=new le(4).toRed(this.red).redInvm(),this.two=new le(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}pe(me,de);var ye=me;function ve(t,e,r){de.BasePoint.call(this,t,"projective"),null===e&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new le(e,16),this.z=new le(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}me.prototype.validate=function(t){var e=t.normalize().x,r=e.redSqr(),n=r.redMul(e).redAdd(r.redMul(this.a)).redAdd(e);return 0===n.redSqrt().redSqr().cmp(n)},pe(ve,de.BasePoint),me.prototype.decodePoint=function(t,e){return this.point(ge.toArray(t,e),1)},me.prototype.point=function(t,e){return new ve(this,t,e)},me.prototype.pointFromJSON=function(t){return ve.fromJSON(this,t)},ve.prototype.precompute=function(){},ve.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},ve.fromJSON=function(t,e){return new ve(t,e[0],e[1]||t.one)},ve.prototype.inspect=function(){return this.isInfinity()?"":""},ve.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},ve.prototype.dbl=function(){var t=this.x.redAdd(this.z).redSqr(),e=this.x.redSub(this.z).redSqr(),r=t.redSub(e),n=t.redMul(e),i=r.redMul(e.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},ve.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.diffAdd=function(t,e){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=t.x.redAdd(t.z),o=t.x.redSub(t.z).redMul(r),s=i.redMul(n),u=e.z.redMul(o.redAdd(s).redSqr()),a=e.x.redMul(o.redISub(s).redSqr());return this.curve.point(u,a)},ve.prototype.mul=function(t){for(var e=t.clone(),r=this,n=this.curve.point(null,null),i=[];0!==e.cmpn(0);e.iushrn(1))i.push(e.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},ve.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},ve.prototype.eq=function(t){return 0===this.getX().cmp(t.getX())},ve.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},ve.prototype.getX=function(){return this.normalize(),this.x.fromRed()};var we=Ut,be=Ct.exports,_e=te.exports,Ee=Zt,Se=we.assert;function Ie(t){this.twisted=1!=(0|t.a),this.mOneA=this.twisted&&-1==(0|t.a),this.extended=this.mOneA,Ee.call(this,"edwards",t),this.a=new be(t.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new be(t.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new be(t.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Se(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|t.c)}_e(Ie,Ee);var Me=Ie;function Te(t,e,r,n,i){Ee.BasePoint.call(this,t,"projective"),null===e&&null===r&&null===n?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new be(e,16),this.y=new be(r,16),this.z=n?new be(n,16):this.curve.one,this.t=i&&new be(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}Ie.prototype._mulA=function(t){return this.mOneA?t.redNeg():this.a.redMul(t)},Ie.prototype._mulC=function(t){return this.oneC?t:this.c.redMul(t)},Ie.prototype.jpoint=function(t,e,r,n){return this.point(t,e,r,n)},Ie.prototype.pointFromX=function(t,e){(t=new be(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=this.c2.redSub(this.a.redMul(r)),i=this.one.redSub(this.c2.redMul(this.d).redMul(r)),o=n.redMul(i.redInvm()),s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");var u=s.fromRed().isOdd();return(e&&!u||!e&&u)&&(s=s.redNeg()),this.point(t,s)},Ie.prototype.pointFromY=function(t,e){(t=new be(t,16)).red||(t=t.toRed(this.red));var r=t.redSqr(),n=r.redSub(this.c2),i=r.redMul(this.d).redMul(this.c2).redSub(this.a),o=n.redMul(i.redInvm());if(0===o.cmp(this.zero)){if(e)throw new Error("invalid point");return this.point(this.zero,t)}var s=o.redSqrt();if(0!==s.redSqr().redSub(o).cmp(this.zero))throw new Error("invalid point");return s.fromRed().isOdd()!==e&&(s=s.redNeg()),this.point(s,t)},Ie.prototype.validate=function(t){if(t.isInfinity())return!0;t.normalize();var e=t.x.redSqr(),r=t.y.redSqr(),n=e.redMul(this.a).redAdd(r),i=this.c2.redMul(this.one.redAdd(this.d.redMul(e).redMul(r)));return 0===n.cmp(i)},_e(Te,Ee.BasePoint),Ie.prototype.pointFromJSON=function(t){return Te.fromJSON(this,t)},Ie.prototype.point=function(t,e,r,n){return new Te(this,t,e,r,n)},Te.fromJSON=function(t,e){return new Te(t,e[0],e[1],e[2])},Te.prototype.inspect=function(){return this.isInfinity()?"":""},Te.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Te.prototype._extDbl=function(){var t=this.x.redSqr(),e=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(t),i=this.x.redAdd(this.y).redSqr().redISub(t).redISub(e),o=n.redAdd(e),s=o.redSub(r),u=n.redSub(e),a=i.redMul(s),h=o.redMul(u),f=i.redMul(u),c=s.redMul(o);return this.curve.point(a,h,c,f)},Te.prototype._projDbl=function(){var t,e,r,n,i,o,s=this.x.redAdd(this.y).redSqr(),u=this.x.redSqr(),a=this.y.redSqr();if(this.curve.twisted){var h=(n=this.curve._mulA(u)).redAdd(a);this.zOne?(t=s.redSub(u).redSub(a).redMul(h.redSub(this.curve.two)),e=h.redMul(n.redSub(a)),r=h.redSqr().redSub(h).redSub(h)):(i=this.z.redSqr(),o=h.redSub(i).redISub(i),t=s.redSub(u).redISub(a).redMul(o),e=h.redMul(n.redSub(a)),r=h.redMul(o))}else n=u.redAdd(a),i=this.curve._mulC(this.z).redSqr(),o=n.redSub(i).redSub(i),t=this.curve._mulC(s.redISub(n)).redMul(o),e=this.curve._mulC(n).redMul(u.redISub(a)),r=n.redMul(o);return this.curve.point(t,e,r)},Te.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Te.prototype._extAdd=function(t){var e=this.y.redSub(this.x).redMul(t.y.redSub(t.x)),r=this.y.redAdd(this.x).redMul(t.y.redAdd(t.x)),n=this.t.redMul(this.curve.dd).redMul(t.t),i=this.z.redMul(t.z.redAdd(t.z)),o=r.redSub(e),s=i.redSub(n),u=i.redAdd(n),a=r.redAdd(e),h=o.redMul(s),f=u.redMul(a),c=o.redMul(a),l=s.redMul(u);return this.curve.point(h,f,l,c)},Te.prototype._projAdd=function(t){var e,r,n=this.z.redMul(t.z),i=n.redSqr(),o=this.x.redMul(t.x),s=this.y.redMul(t.y),u=this.curve.d.redMul(o).redMul(s),a=i.redSub(u),h=i.redAdd(u),f=this.x.redAdd(this.y).redMul(t.x.redAdd(t.y)).redISub(o).redISub(s),c=n.redMul(a).redMul(f);return this.curve.twisted?(e=n.redMul(h).redMul(s.redSub(this.curve._mulA(o))),r=a.redMul(h)):(e=n.redMul(h).redMul(s.redSub(o)),r=this.curve._mulC(a).redMul(h)),this.curve.point(c,e,r)},Te.prototype.add=function(t){return this.isInfinity()?t:t.isInfinity()?this:this.curve.extended?this._extAdd(t):this._projAdd(t)},Te.prototype.mul=function(t){return this._hasDoubles(t)?this.curve._fixedNafMul(this,t):this.curve._wnafMul(this,t)},Te.prototype.mulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!1)},Te.prototype.jmulAdd=function(t,e,r){return this.curve._wnafMulAdd(1,[this,e],[t,r],2,!0)},Te.prototype.normalize=function(){if(this.zOne)return this;var t=this.z.redInvm();return this.x=this.x.redMul(t),this.y=this.y.redMul(t),this.t&&(this.t=this.t.redMul(t)),this.z=this.curve.one,this.zOne=!0,this},Te.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Te.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Te.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Te.prototype.eq=function(t){return this===t||0===this.getX().cmp(t.getX())&&0===this.getY().cmp(t.getY())},Te.prototype.eqXToP=function(t){var e=t.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(e))return!0;for(var r=t.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(e.redIAdd(n),0===this.x.cmp(e))return!0}},Te.prototype.toP=Te.prototype.normalize,Te.prototype.mixedAdd=Te.prototype.add,function(t){var e=t;e.base=Zt,e.short=he,e.mont=ye,e.edwards=Me}(Wt);var Oe={},Ae={},Pe={},ke=Dt,Re=te.exports;function Ne(t,e){return 55296==(64512&t.charCodeAt(e))&&(!(e<0||e+1>=t.length)&&56320==(64512&t.charCodeAt(e+1)))}function xe(t){return(t>>>24|t>>>8&65280|t<<8&16711680|(255&t)<<24)>>>0}function Be(t){return 1===t.length?"0"+t:t}function Le(t){return 7===t.length?"0"+t:6===t.length?"00"+t:5===t.length?"000"+t:4===t.length?"0000"+t:3===t.length?"00000"+t:2===t.length?"000000"+t:1===t.length?"0000000"+t:t}Pe.inherits=Re,Pe.toArray=function(t,e){if(Array.isArray(t))return t.slice();if(!t)return[];var r=[];if("string"==typeof t)if(e){if("hex"===e)for((t=t.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(t="0"+t),i=0;i>6|192,r[n++]=63&o|128):Ne(t,i)?(o=65536+((1023&o)<<10)+(1023&t.charCodeAt(++i)),r[n++]=o>>18|240,r[n++]=o>>12&63|128,r[n++]=o>>6&63|128,r[n++]=63&o|128):(r[n++]=o>>12|224,r[n++]=o>>6&63|128,r[n++]=63&o|128)}else for(i=0;i>>0}return o},Pe.split32=function(t,e){for(var r=new Array(4*t.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},Pe.rotr32=function(t,e){return t>>>e|t<<32-e},Pe.rotl32=function(t,e){return t<>>32-e},Pe.sum32=function(t,e){return t+e>>>0},Pe.sum32_3=function(t,e,r){return t+e+r>>>0},Pe.sum32_4=function(t,e,r,n){return t+e+r+n>>>0},Pe.sum32_5=function(t,e,r,n,i){return t+e+r+n+i>>>0},Pe.sum64=function(t,e,r,n){var i=t[e],o=n+t[e+1]>>>0,s=(o>>0,t[e+1]=o},Pe.sum64_hi=function(t,e,r,n){return(e+n>>>0>>0},Pe.sum64_lo=function(t,e,r,n){return e+n>>>0},Pe.sum64_4_hi=function(t,e,r,n,i,o,s,u){var a=0,h=e;return a+=(h=h+n>>>0)>>0)>>0)>>0},Pe.sum64_4_lo=function(t,e,r,n,i,o,s,u){return e+n+o+u>>>0},Pe.sum64_5_hi=function(t,e,r,n,i,o,s,u,a,h){var f=0,c=e;return f+=(c=c+n>>>0)>>0)>>0)>>0)>>0},Pe.sum64_5_lo=function(t,e,r,n,i,o,s,u,a,h){return e+n+o+u+h>>>0},Pe.rotr64_hi=function(t,e,r){return(e<<32-r|t>>>r)>>>0},Pe.rotr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0},Pe.shr64_hi=function(t,e,r){return t>>>r},Pe.shr64_lo=function(t,e,r){return(t<<32-r|e>>>r)>>>0};var Ue={},Ce=Pe,De=Dt;function He(){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}Ue.BlockHash=He,He.prototype.update=function(t,e){if(t=Ce.toArray(t,e),this.pending?this.pending=this.pending.concat(t):this.pending=t,this.pendingTotal+=t.length,this.pending.length>=this._delta8){var r=(t=this.pending).length%this._delta8;this.pending=t.slice(t.length-r,t.length),0===this.pending.length&&(this.pending=null),t=Ce.join32(t,0,t.length-r,this.endian);for(var n=0;n>>24&255,n[i++]=t>>>16&255,n[i++]=t>>>8&255,n[i++]=255&t}else for(n[i++]=255&t,n[i++]=t>>>8&255,n[i++]=t>>>16&255,n[i++]=t>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;o>>3},je.g1_256=function(t){return qe(t,17)^qe(t,19)^t>>>10};var Ve=Pe,$e=Ue,ze=je,Xe=Ve.rotl32,Ye=Ve.sum32,Je=Ve.sum32_5,Ze=ze.ft_1,Qe=$e.BlockHash,tr=[1518500249,1859775393,2400959708,3395469782];function er(){if(!(this instanceof er))return new er;Qe.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}Ve.inherits(er,Qe);var rr=er;er.blockSize=512,er.outSize=160,er.hmacStrength=80,er.padLength=64,er.prototype._update=function(t,e){for(var r=this.W,n=0;n<16;n++)r[n]=t[e+n];for(;nthis.blockSize&&(t=(new this.Hash).update(t).digest()),En(t.length<=this.blockSize);for(var e=t.length;e=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(e,r,n)}var Pn=An;An.prototype._init=function(t,e,r){var n=t.concat(e).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(t.concat(r||[])),this._reseed=1},An.prototype.generate=function(t,e,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof e&&(n=r,r=e,e=null),r&&(r=Tn.toArray(r,n||"hex"),this._update(r));for(var i=[];i.length"};var Bn=Ct.exports,Ln=Ut,Un=Ln.assert;function Cn(t,e){if(t instanceof Cn)return t;this._importDER(t,e)||(Un(t.r&&t.s,"Signature without r or s"),this.r=new Bn(t.r,16),this.s=new Bn(t.s,16),void 0===t.recoveryParam?this.recoveryParam=null:this.recoveryParam=t.recoveryParam)}var Dn=Cn;function Hn(){this.place=0}function Fn(t,e){var r=t[e.place++];if(!(128&r))return r;var n=15&r;if(0===n||n>4)return!1;for(var i=0,o=0,s=e.place;o>>=0;return!(i<=127)&&(e.place=s,i)}function jn(t){for(var e=0,r=t.length-1;!t[e]&&!(128&t[e+1])&&e>>3);for(t.push(128|r);--r;)t.push(e>>>(r<<3)&255);t.push(e)}}Cn.prototype._importDER=function(t,e){t=Ln.toArray(t,e);var r=new Hn;if(48!==t[r.place++])return!1;var n=Fn(t,r);if(!1===n)return!1;if(n+r.place!==t.length)return!1;if(2!==t[r.place++])return!1;var i=Fn(t,r);if(!1===i)return!1;var o=t.slice(r.place,i+r.place);if(r.place+=i,2!==t[r.place++])return!1;var s=Fn(t,r);if(!1===s)return!1;if(t.length!==s+r.place)return!1;var u=t.slice(r.place,s+r.place);if(0===o[0]){if(!(128&o[1]))return!1;o=o.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new Bn(o),this.s=new Bn(u),this.recoveryParam=null,!0},Cn.prototype.toDER=function(t){var e=this.r.toArray(),r=this.s.toArray();for(128&e[0]&&(e=[0].concat(e)),128&r[0]&&(r=[0].concat(r)),e=jn(e),r=jn(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];qn(n,e.length),(n=n.concat(e)).push(2),qn(n,r.length);var i=n.concat(r),o=[48];return qn(o,i.length),o=o.concat(i),Ln.encode(o,t)};var Gn=Ct.exports,Kn=Pn,Wn=Ut,Vn=Oe,$n=qt.exports,zn=Wn.assert,Xn=xn,Yn=Dn;function Jn(t){if(!(this instanceof Jn))return new Jn(t);"string"==typeof t&&(zn(Object.prototype.hasOwnProperty.call(Vn,t),"Unknown curve "+t),t=Vn[t]),t instanceof Vn.PresetCurve&&(t={curve:t}),this.curve=t.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=t.curve.g,this.g.precompute(t.curve.n.bitLength()+1),this.hash=t.hash||t.curve.hash}var Zn=Jn;Jn.prototype.keyPair=function(t){return new Xn(this,t)},Jn.prototype.keyFromPrivate=function(t,e){return Xn.fromPrivate(this,t,e)},Jn.prototype.keyFromPublic=function(t,e){return Xn.fromPublic(this,t,e)},Jn.prototype.genKeyPair=function(t){t||(t={});for(var e=new Kn({hash:this.hash,pers:t.pers,persEnc:t.persEnc||"utf8",entropy:t.entropy||$n(this.hash.hmacStrength),entropyEnc:t.entropy&&t.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),n=this.n.sub(new Gn(2));;){var i=new Gn(e.generate(r));if(!(i.cmp(n)>0))return i.iaddn(1),this.keyFromPrivate(i)}},Jn.prototype._truncateToN=function(t,e){var r=8*t.byteLength()-this.n.bitLength();return r>0&&(t=t.ushrn(r)),!e&&t.cmp(this.n)>=0?t.sub(this.n):t},Jn.prototype.sign=function(t,e,r,n){"object"==typeof r&&(n=r,r=null),n||(n={}),e=this.keyFromPrivate(e,r),t=this._truncateToN(new Gn(t,16));for(var i=this.n.byteLength(),o=e.getPrivate().toArray("be",i),s=t.toArray("be",i),u=new Kn({hash:this.hash,entropy:o,nonce:s,pers:n.pers,persEnc:n.persEnc||"utf8"}),a=this.n.sub(new Gn(1)),h=0;;h++){var f=n.k?n.k(h):new Gn(u.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(a)>=0)){var c=this.g.mul(f);if(!c.isInfinity()){var l=c.getX(),p=l.umod(this.n);if(0!==p.cmpn(0)){var d=f.invm(this.n).mul(p.mul(e.getPrivate()).iadd(t));if(0!==(d=d.umod(this.n)).cmpn(0)){var g=(c.getY().isOdd()?1:0)|(0!==l.cmp(p)?2:0);return n.canonical&&d.cmp(this.nh)>0&&(d=this.n.sub(d),g^=1),new Yn({r:p,s:d,recoveryParam:g})}}}}}},Jn.prototype.verify=function(t,e,r,n){t=this._truncateToN(new Gn(t,16)),r=this.keyFromPublic(r,n);var i=(e=new Yn(e,"hex")).r,o=e.s;if(i.cmpn(1)<0||i.cmp(this.n)>=0)return!1;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;var s,u=o.invm(this.n),a=u.mul(t).umod(this.n),h=u.mul(i).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(a,r.getPublic(),h)).isInfinity()&&s.eqXToP(i):!(s=this.g.mulAdd(a,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(i)},Jn.prototype.recoverPubKey=function(t,e,r,n){zn((3&r)===r,"The recovery param is more than two bits"),e=new Yn(e,n);var i=this.n,o=new Gn(t),s=e.r,u=e.s,a=1&r,h=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");s=h?this.curve.pointFromX(s.add(this.curve.n),a):this.curve.pointFromX(s,a);var f=e.r.invm(i),c=i.sub(o).mul(f).umod(i),l=u.mul(f).umod(i);return this.g.mulAdd(c,s,l)},Jn.prototype.getKeyRecoveryParam=function(t,e,r,n){if(null!==(e=new Yn(e,n)).recoveryParam)return e.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(t,e,i)}catch(t){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")};var Qn=Ut,ti=Qn.assert,ei=Qn.parseBytes,ri=Qn.cachedProperty;function ni(t,e){this.eddsa=t,this._secret=ei(e.secret),t.isPoint(e.pub)?this._pub=e.pub:this._pubBytes=ei(e.pub)}ni.fromPublic=function(t,e){return e instanceof ni?e:new ni(t,{pub:e})},ni.fromSecret=function(t,e){return e instanceof ni?e:new ni(t,{secret:e})},ni.prototype.secret=function(){return this._secret},ri(ni,"pubBytes",(function(){return this.eddsa.encodePoint(this.pub())})),ri(ni,"pub",(function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),ri(ni,"privBytes",(function(){var t=this.eddsa,e=this.hash(),r=t.encodingLength-1,n=e.slice(0,t.encodingLength);return n[0]&=248,n[r]&=127,n[r]|=64,n})),ri(ni,"priv",(function(){return this.eddsa.decodeInt(this.privBytes())})),ri(ni,"hash",(function(){return this.eddsa.hash().update(this.secret()).digest()})),ri(ni,"messagePrefix",(function(){return this.hash().slice(this.eddsa.encodingLength)})),ni.prototype.sign=function(t){return ti(this._secret,"KeyPair can only verify"),this.eddsa.sign(t,this)},ni.prototype.verify=function(t,e){return this.eddsa.verify(t,e,this)},ni.prototype.getSecret=function(t){return ti(this._secret,"KeyPair is public only"),Qn.encode(this.secret(),t)},ni.prototype.getPublic=function(t){return Qn.encode(this.pubBytes(),t)};var ii=ni,oi=Ct.exports,si=Ut,ui=si.assert,ai=si.cachedProperty,hi=si.parseBytes;function fi(t,e){this.eddsa=t,"object"!=typeof e&&(e=hi(e)),Array.isArray(e)&&(e={R:e.slice(0,t.encodingLength),S:e.slice(t.encodingLength)}),ui(e.R&&e.S,"Signature without R or S"),t.isPoint(e.R)&&(this._R=e.R),e.S instanceof oi&&(this._S=e.S),this._Rencoded=Array.isArray(e.R)?e.R:e.Rencoded,this._Sencoded=Array.isArray(e.S)?e.S:e.Sencoded}ai(fi,"S",(function(){return this.eddsa.decodeInt(this.Sencoded())})),ai(fi,"R",(function(){return this.eddsa.decodePoint(this.Rencoded())})),ai(fi,"Rencoded",(function(){return this.eddsa.encodePoint(this.R())})),ai(fi,"Sencoded",(function(){return this.eddsa.encodeInt(this.S())})),fi.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},fi.prototype.toHex=function(){return si.encode(this.toBytes(),"hex").toUpperCase()};var ci=fi,li=Ae,pi=Oe,di=Ut,gi=di.assert,mi=di.parseBytes,yi=ii,vi=ci;function wi(t){if(gi("ed25519"===t,"only tested with ed25519 so far"),!(this instanceof wi))return new wi(t);t=pi[t].curve,this.curve=t,this.g=t.g,this.g.precompute(t.n.bitLength()+1),this.pointClass=t.point().constructor,this.encodingLength=Math.ceil(t.n.bitLength()/8),this.hash=li.sha512}var bi=wi;wi.prototype.sign=function(t,e){t=mi(t);var r=this.keyFromSecret(e),n=this.hashInt(r.messagePrefix(),t),i=this.g.mul(n),o=this.encodePoint(i),s=this.hashInt(o,r.pubBytes(),t).mul(r.priv()),u=n.add(s).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},wi.prototype.verify=function(t,e,r){t=mi(t),e=this.makeSignature(e);var n=this.keyFromPublic(r),i=this.hashInt(e.Rencoded(),n.pubBytes(),t),o=this.g.mul(e.S());return e.R().add(n.pub().mul(i)).eq(o)},wi.prototype.hashInt=function(){for(var t=this.hash(),e=0;e=0)return!1;if((2===e||3===e)&&33===t.length){try{Vi(t)}catch(t){return!1}return!0}const n=t.slice(33);return 0!==n.compare(Ai)&&(!(n.compare(ki)>=0)&&(4===e&&65===t.length))}function ji(t){return 4!==t[0]}function qi(t){return!!Di(t)&&(t.compare(Ai)>0&&t.compare(Pi)<0)}function Gi(t,e){return void 0===t&&void 0!==e?ji(e):void 0===t||t}function Ki(t){return new Mi(t)}function Wi(t){return t.toArrayLike(Buffer,"be",32)}function Vi(t){return Ti.curve.decodePoint(t)}function $i(t,e){return Buffer.from(t._encode(e))}function zi(t,e,r){if(!Di(t))throw new TypeError(Ci);if(!qi(e))throw new TypeError(Bi);if(void 0!==r&&!Di(r))throw new TypeError("Expected Extra Data (32 bytes)");const n=Ki(e),i=Ki(t);let o,s;Oi(t,e,(function(t){const e=Ki(t),r=xi.mul(e);return!r.isInfinity()&&(o=r.x.umod(Ri),0!==o.isZero()&&(s=e.invm(Ri).mul(i.add(n.mul(o))).umod(Ri),0!==s.isZero()))}),qi,r),s.cmp(Ni)>0&&(s=Ri.sub(s));const u=Buffer.allocUnsafe(64);return Wi(o).copy(u,0),Wi(s).copy(u,32),u}var Xi={isPoint:Fi,isPointCompressed:function(t){return!!Fi(t)&&ji(t)},isPrivate:qi,pointAdd:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Fi(e))throw new TypeError(Li);const n=Vi(t),i=Vi(e),o=n.add(i);return o.isInfinity()?null:$i(o,Gi(r,t))},pointAddScalar:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Hi(e))throw new TypeError(Ui);const n=Gi(r,t),i=Vi(t);if(0===e.compare(Ai))return $i(i,n);const o=Ki(e),s=xi.mul(o),u=i.add(s);return u.isInfinity()?null:$i(u,n)},pointCompress:function(t,e){if(!Fi(t))throw new TypeError(Li);const r=Vi(t);if(r.isInfinity())throw new TypeError(Li);return $i(r,Gi(e,t))},pointFromScalar:function(t,e){if(!qi(t))throw new TypeError(Bi);const r=Ki(t),n=xi.mul(r);return n.isInfinity()?null:$i(n,Gi(e))},pointMultiply:function(t,e,r){if(!Fi(t))throw new TypeError(Li);if(!Hi(e))throw new TypeError(Ui);const n=Gi(r,t),i=Vi(t),o=Ki(e),s=i.mul(o);return s.isInfinity()?null:$i(s,n)},privateAdd:function(t,e){if(!qi(t))throw new TypeError(Bi);if(!Hi(e))throw new TypeError(Ui);const r=Ki(t),n=Ki(e),i=Wi(r.add(n).umod(Ri));return qi(i)?i:null},privateSub:function(t,e){if(!qi(t))throw new TypeError(Bi);if(!Hi(e))throw new TypeError(Ui);const r=Ki(t),n=Ki(e),i=Wi(r.sub(n).umod(Ri));return qi(i)?i:null},sign:function(t,e){return zi(t,e)},signWithEntropy:function(t,e,r){return zi(t,e,r)},verify:function(t,e,r,n){if(!Di(t))throw new TypeError(Ci);if(!Fi(e))throw new TypeError(Li);if(!function(t){const e=t.slice(0,32),r=t.slice(32,64);return Buffer.isBuffer(t)&&64===t.length&&e.compare(Pi)<0&&r.compare(Pi)<0}(r))throw new TypeError("Expected Signature");const i=Vi(e),o=Ki(r.slice(0,32)),s=Ki(r.slice(32,64));if(n&&s.cmp(Ni)>0)return!1;if(o.gtn(0)<=0)return!1;if(s.gtn(0)<=0)return!1;const u=Ki(t),a=s.invm(Ri),h=u.mul(a).umod(Ri),f=o.mul(a).umod(Ri),c=xi.mulAdd(h,i,f);return!c.isInfinity()&&c.x.umod(Ri).eq(o)}};try{Nt.exports=require("./native")}catch(t){Nt.exports=Xi}var Yi={Array:function(t){return null!=t&&t.constructor===Array},Boolean:function(t){return"boolean"==typeof t},Function:function(t){return"function"==typeof t},Nil:function(t){return null==t},Number:function(t){return"number"==typeof t},Object:function(t){return"object"==typeof t},String:function(t){return"string"==typeof t},"":function(){return!0}};for(var Ji in Yi.Null=Yi.Nil,Yi)Yi[Ji].toJSON=function(t){return t}.bind(null,Ji);var Zi=Yi,Qi=Zi;function to(t){return t.name||t.toString().match(/function (.*?)\s*\(/)[1]}function eo(t){return Qi.Nil(t)?"":to(t.constructor)}function ro(t,e){Error.captureStackTrace&&Error.captureStackTrace(t,e)}function no(t){return Qi.Function(t)?t.toJSON?t.toJSON():to(t):Qi.Array(t)?"Array":t&&Qi.Object(t)?"Object":void 0!==t?t:""}function io(t,e,r){var n=function(t){return Qi.Function(t)?"":Qi.String(t)?JSON.stringify(t):t&&Qi.Object(t)?"":t}(e);return"Expected "+no(t)+", got"+(""!==r?" "+r:"")+(""!==n?" "+n:"")}function oo(t,e,r){r=r||eo(e),this.message=io(t,e,r),ro(this,oo),this.__type=t,this.__value=e,this.__valueTypeName=r}function so(t,e,r,n,i){t?(i=i||eo(n),this.message=function(t,e,r,n,i){var o='" of type ';return"key"===e&&(o='" with key type '),io('property "'+no(r)+o+no(t),n,i)}(t,r,e,n,i)):this.message='Unexpected property "'+e+'"',ro(this,oo),this.__label=r,this.__property=e,this.__type=t,this.__value=n,this.__valueTypeName=i}oo.prototype=Object.create(Error.prototype),oo.prototype.constructor=oo,so.prototype=Object.create(Error.prototype),so.prototype.constructor=oo;var uo={TfTypeError:oo,TfPropertyTypeError:so,tfCustomError:function(t,e){return new oo(t,{},e)},tfSubError:function(t,e,r){return t instanceof so?(e=e+"."+t.__property,t=new so(t.__type,e,t.__label,t.__value,t.__valueTypeName)):t instanceof oo&&(t=new so(t.__type,e,r,t.__value,t.__valueTypeName)),ro(t),t},tfJSON:no,getValueTypeName:eo},ao=Zi,ho=uo;function fo(t){return Buffer.isBuffer(t)}function co(t){return"string"==typeof t&&/^([0-9a-f]{2})+$/i.test(t)}function lo(t,e){var r=t.toJSON();function n(n){if(!t(n))return!1;if(n.length===e)return!0;throw ho.tfCustomError(r+"(Length: "+e+")",r+"(Length: "+n.length+")")}return n.toJSON=function(){return r},n}var po=lo.bind(null,ao.Array),go=lo.bind(null,fo),mo=lo.bind(null,co),yo=lo.bind(null,ao.String);var vo=Math.pow(2,53)-1;var wo={ArrayN:po,Buffer:fo,BufferN:go,Finite:function(t){return"number"==typeof t&&isFinite(t)},Hex:co,HexN:mo,Int8:function(t){return t<<24>>24===t},Int16:function(t){return t<<16>>16===t},Int32:function(t){return(0|t)===t},Int53:function(t){return"number"==typeof t&&t>=-vo&&t<=vo&&Math.floor(t)===t},Range:function(t,e,r){function n(n,i){return r(n,i)&&n>t&&n>>0===t},UInt53:function(t){return"number"==typeof t&&t>=0&&t<=vo&&Math.floor(t)===t}};for(var bo in wo)wo[bo].toJSON=function(t){return t}.bind(null,bo);var _o=wo,Eo=Zi,So=uo.tfJSON,Io=uo.TfTypeError,Mo=uo.TfPropertyTypeError,To=uo.tfSubError,Oo=uo.getValueTypeName,Ao={arrayOf:function(t,e){function r(r,n){return!!Eo.Array(r)&&(!Eo.Nil(r)&&(!(void 0!==e.minLength&&r.lengthe.maxLength)&&((void 0===e.length||r.length===e.length)&&r.every((function(e,r){try{return ko(t,e,n)}catch(t){throw To(t,r)}}))))))}return t=Po(t),e=e||{},r.toJSON=function(){var r="["+So(t)+"]";return void 0!==e.length?r+="{"+e.length+"}":void 0===e.minLength&&void 0===e.maxLength||(r+="{"+(void 0===e.minLength?0:e.minLength)+","+(void 0===e.maxLength?1/0:e.maxLength)+"}"),r},r},maybe:function t(e){function r(r,n){return Eo.Nil(r)||e(r,n,t)}return e=Po(e),r.toJSON=function(){return"?"+So(e)},r},map:function(t,e){function r(r,n){if(!Eo.Object(r))return!1;if(Eo.Nil(r))return!1;for(var i in r){try{e&&ko(e,i,n)}catch(t){throw To(t,i,"key")}try{var o=r[i];ko(t,o,n)}catch(t){throw To(t,i)}}return!0}return t=Po(t),e&&(e=Po(e)),r.toJSON=e?function(){return"{"+So(e)+": "+So(t)+"}"}:function(){return"{"+So(t)+"}"},r},object:function(t){var e={};for(var r in t)e[r]=Po(t[r]);function n(t,r){if(!Eo.Object(t))return!1;if(Eo.Nil(t))return!1;var n;try{for(n in e){ko(e[n],t[n],r)}}catch(t){throw To(t,n)}if(r)for(n in t)if(!e[n])throw new Mo(void 0,n);return!0}return n.toJSON=function(){return So(e)},n},anyOf:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return t.some((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(So).join("|")},e},allOf:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return t.every((function(t){try{return ko(t,e,r)}catch(t){return!1}}))}return e.toJSON=function(){return t.map(So).join(" & ")},e},quacksLike:function(t){function e(e){return t===Oo(e)}return e.toJSON=function(){return t},e},tuple:function(){var t=[].slice.call(arguments).map(Po);function e(e,r){return!Eo.Nil(e)&&(!Eo.Nil(e.length)&&((!r||e.length===t.length)&&t.every((function(t,n){try{return ko(t,e[n],r)}catch(t){throw To(t,n)}}))))}return e.toJSON=function(){return"("+t.map(So).join(", ")+")"},e},value:function(t){function e(e){return e===t}return e.toJSON=function(){return t},e}};function Po(t){if(Eo.String(t))return"?"===t[0]?Ao.maybe(t.slice(1)):Eo[t]||Ao.quacksLike(t);if(t&&Eo.Object(t)){if(Eo.Array(t)){if(1!==t.length)throw new TypeError("Expected compile() parameter of type Array of length 1");return Ao.arrayOf(t[0])}return Ao.object(t)}return Eo.Function(t)?t:Ao.value(t)}function ko(t,e,r,n){if(Eo.Function(t)){if(t(e,r))return!0;throw new Io(n||t,e)}return ko(Po(t),e,r)}for(var Ro in Ao.oneOf=Ao.anyOf,Eo)ko[Ro]=Eo[Ro];for(Ro in Ao)ko[Ro]=Ao[Ro];var No=_o;for(Ro in No)ko[Ro]=No[Ro];ko.compile=Po,ko.TfTypeError=Io,ko.TfPropertyTypeError=Mo;var xo=ko,Bo=vt;function Lo(t,e){if(void 0!==e&&t[0]!==e)throw new Error("Invalid network version");if(33===t.length)return{version:t[0],privateKey:t.slice(1,33),compressed:!1};if(34!==t.length)throw new Error("Invalid WIF length");if(1!==t[33])throw new Error("Invalid compression flag");return{version:t[0],privateKey:t.slice(1,33),compressed:!0}}function Uo(t,e,r){var n=new Buffer(r?34:33);return n.writeUInt8(t,0),e.copy(n,1),r&&(n[33]=1),n}var Co={decode:function(t,e){return Lo(Bo.decode(t),e)},decodeRaw:Lo,encode:function(t,e,r){return"number"==typeof t?Bo.encode(Uo(t,e,r)):Bo.encode(Uo(t.version,t.privateKey,t.compressed))},encodeRaw:Uo};Object.defineProperty(Ot,"__esModule",{value:!0});const Do=At,Ho=vt,Fo=Nt.exports,jo=xo,qo=Co,Go=jo.BufferN(32),Ko=jo.compile({wif:jo.UInt8,bip32:{public:jo.UInt32,private:jo.UInt32}}),Wo={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},Vo=2147483648,$o=Math.pow(2,31)-1;function zo(t){return jo.String(t)&&null!==t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}function Xo(t){return jo.UInt32(t)&&t<=$o}class Yo{constructor(t,e,r,n,i=0,o=0,s=0){this.__D=t,this.__Q=e,this.chainCode=r,this.network=n,this.__DEPTH=i,this.__INDEX=o,this.__PARENT_FINGERPRINT=s,jo(Ko,n),this.lowR=!1}get depth(){return this.__DEPTH}get index(){return this.__INDEX}get parentFingerprint(){return this.__PARENT_FINGERPRINT}get publicKey(){return void 0===this.__Q&&(this.__Q=Fo.pointFromScalar(this.__D,!0)),this.__Q}get privateKey(){return this.__D}get identifier(){return Do.hash160(this.publicKey)}get fingerprint(){return this.identifier.slice(0,4)}get compressed(){return!0}isNeutered(){return void 0===this.__D}neutered(){return Qo(this.publicKey,this.chainCode,this.network,this.depth,this.index,this.parentFingerprint)}toBase58(){const t=this.network,e=this.isNeutered()?t.bip32.public:t.bip32.private,r=Buffer.allocUnsafe(78);return r.writeUInt32BE(e,0),r.writeUInt8(this.depth,4),r.writeUInt32BE(this.parentFingerprint,5),r.writeUInt32BE(this.index,9),this.chainCode.copy(r,13),this.isNeutered()?this.publicKey.copy(r,45):(r.writeUInt8(0,45),this.privateKey.copy(r,46)),Ho.encode(r)}toWIF(){if(!this.privateKey)throw new TypeError("Missing private key");return qo.encode(this.network.wif,this.privateKey,!0)}derive(t){jo(jo.UInt32,t);const e=t>=Vo,r=Buffer.allocUnsafe(37);if(e){if(this.isNeutered())throw new TypeError("Missing private key for hardened child key");r[0]=0,this.privateKey.copy(r,1),r.writeUInt32BE(t,33)}else this.publicKey.copy(r,0),r.writeUInt32BE(t,33);const n=Do.hmacSHA512(this.chainCode,r),i=n.slice(0,32),o=n.slice(32);if(!Fo.isPrivate(i))return this.derive(t+1);let s;if(this.isNeutered()){const e=Fo.pointAddScalar(this.publicKey,i,!0);if(null===e)return this.derive(t+1);s=Qo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}else{const e=Fo.privateAdd(this.privateKey,i);if(null==e)return this.derive(t+1);s=Zo(e,o,this.network,this.depth+1,t,this.fingerprint.readUInt32BE(0))}return s}deriveHardened(t){return jo(Xo,t),this.derive(t+Vo)}derivePath(t){jo(zo,t);let e=t.split("/");if("m"===e[0]){if(this.parentFingerprint)throw new TypeError("Expected master, got child");e=e.slice(1)}return e.reduce(((t,e)=>{let r;return"'"===e.slice(-1)?(r=parseInt(e.slice(0,-1),10),t.deriveHardened(r)):(r=parseInt(e,10),t.derive(r))}),this)}sign(t,e){if(!this.privateKey)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return Fo.sign(t,this.privateKey);{let e=Fo.sign(t,this.privateKey);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=Fo.signWithEntropy(t,this.privateKey,r);return e}}verify(t,e){return Fo.verify(t,this.publicKey,e)}}function Jo(t,e,r){return Zo(t,e,r)}function Zo(t,e,r,n,i,o){if(jo({privateKey:Go,chainCode:Go},{privateKey:t,chainCode:e}),r=r||Wo,!Fo.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return new Yo(t,void 0,e,r,n,i,o)}function Qo(t,e,r,n,i,o){if(jo({publicKey:jo.BufferN(33),chainCode:Go},{publicKey:t,chainCode:e}),r=r||Wo,!Fo.isPoint(t))throw new TypeError("Point is not on the curve");return new Yo(void 0,t,e,r,n,i,o)}Ot.fromBase58=function(t,e){const r=Ho.decode(t);if(78!==r.length)throw new TypeError("Invalid buffer length");e=e||Wo;const n=r.readUInt32BE(0);if(n!==e.bip32.private&&n!==e.bip32.public)throw new TypeError("Invalid network version");const i=r[4],o=r.readUInt32BE(5);if(0===i&&0!==o)throw new TypeError("Invalid parent fingerprint");const s=r.readUInt32BE(9);if(0===i&&0!==s)throw new TypeError("Invalid index");const u=r.slice(13,45);let a;if(n===e.bip32.private){if(0!==r.readUInt8(45))throw new TypeError("Invalid private key");a=Zo(r.slice(46,78),u,e,i,s,o)}else{a=Qo(r.slice(45,78),u,e,i,s,o)}return a},Ot.fromPrivateKey=Jo,Ot.fromPublicKey=function(t,e,r){return Qo(t,e,r)},Ot.fromSeed=function(t,e){if(jo(jo.Buffer,t),t.length<16)throw new TypeError("Seed should be at least 128 bits");if(t.length>64)throw new TypeError("Seed should be at most 512 bits");e=e||Wo;const r=Do.hmacSHA512(Buffer.from("Bitcoin seed","utf8"),t);return Jo(r.slice(0,32),r.slice(32),e)},Object.defineProperty(Tt,"__esModule",{value:!0});var ts=Ot;Tt.fromSeed=ts.fromSeed,Tt.fromBase58=ts.fromBase58,Tt.fromPublicKey=ts.fromPublicKey,Tt.fromPrivateKey=ts.fromPrivateKey;var es={},rs={};Object.defineProperty(rs,"__esModule",{value:!0}),rs.bitcoin={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},rs.regtest={messagePrefix:"Bitcoin Signed Message:\n",bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},rs.testnet={messagePrefix:"Bitcoin Signed Message:\n",bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var ns={},is={},os={},ss={};Object.defineProperty(ss,"__esModule",{value:!0}),ss.decode=function(t,e,r){e=e||4,r=void 0===r||r;const n=t.length;if(0===n)return 0;if(n>e)throw new TypeError("Script number overflow");if(r&&0==(127&t[n-1])&&(n<=1||0==(128&t[n-2])))throw new Error("Non-minimally encoded script number");if(5===n){const e=t.readUInt32LE(0),r=t.readUInt8(4);return 128&r?-(4294967296*(-129&r)+e):4294967296*r+e}let i=0;for(let e=0;e2147483647?5:t>8388607?4:t>32767?3:t>127?2:t>0?1:0}(e),n=Buffer.allocUnsafe(r),i=t<0;for(let t=0;t>=8;return 128&n[r-1]?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n};var us={},as={};Object.defineProperty(as,"__esModule",{value:!0});const hs=xo,fs=Math.pow(2,31)-1;function cs(t){return hs.String(t)&&!!t.match(/^(m\/)?(\d+'?\/)*\d+'?$/)}as.UInt31=function(t){return hs.UInt32(t)&&t<=fs},as.BIP32Path=cs,cs.toJSON=()=>"BIP32 derivation path",as.Signer=function(t){return(hs.Buffer(t.publicKey)||"function"==typeof t.getPublicKey)&&"function"==typeof t.sign};as.Satoshi=function(t){return hs.UInt53(t)&&t<=21e14},as.ECPoint=hs.quacksLike("Point"),as.Network=hs.compile({messagePrefix:hs.oneOf(hs.Buffer,hs.String),bip32:{public:hs.UInt32,private:hs.UInt32},pubKeyHash:hs.UInt8,scriptHash:hs.UInt8,wif:hs.UInt8}),as.Buffer256bit=hs.BufferN(32),as.Hash160bit=hs.BufferN(20),as.Hash256bit=hs.BufferN(32),as.Number=hs.Number,as.Array=hs.Array,as.Boolean=hs.Boolean,as.String=hs.String,as.Buffer=hs.Buffer,as.Hex=hs.Hex,as.maybe=hs.maybe,as.tuple=hs.tuple,as.UInt8=hs.UInt8,as.UInt32=hs.UInt32,as.Function=hs.Function,as.BufferN=hs.BufferN,as.Null=hs.Null,as.oneOf=hs.oneOf;var ls=f.exports.Buffer;var ps={check:function(t){if(t.length<8)return!1;if(t.length>72)return!1;if(48!==t[0])return!1;if(t[1]!==t.length-2)return!1;if(2!==t[2])return!1;var e=t[3];if(0===e)return!1;if(5+e>=t.length)return!1;if(2!==t[4+e])return!1;var r=t[5+e];return 0!==r&&(6+e+r===t.length&&(!(128&t[4])&&(!(e>1&&0===t[4]&&!(128&t[5]))&&(!(128&t[e+6])&&!(r>1&&0===t[e+6]&&!(128&t[e+7]))))))},decode:function(t){if(t.length<8)throw new Error("DER sequence length is too short");if(t.length>72)throw new Error("DER sequence length is too long");if(48!==t[0])throw new Error("Expected DER sequence");if(t[1]!==t.length-2)throw new Error("DER sequence length is invalid");if(2!==t[2])throw new Error("Expected DER integer");var e=t[3];if(0===e)throw new Error("R length is zero");if(5+e>=t.length)throw new Error("R length is too long");if(2!==t[4+e])throw new Error("Expected DER integer (2)");var r=t[5+e];if(0===r)throw new Error("S length is zero");if(6+e+r!==t.length)throw new Error("S length is invalid");if(128&t[4])throw new Error("R value is negative");if(e>1&&0===t[4]&&!(128&t[5]))throw new Error("R value excessively padded");if(128&t[e+6])throw new Error("S value is negative");if(r>1&&0===t[e+6]&&!(128&t[e+7]))throw new Error("S value excessively padded");return{r:t.slice(4,4+e),s:t.slice(6+e)}},encode:function(t,e){var r=t.length,n=e.length;if(0===r)throw new Error("R length is zero");if(0===n)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(128&t[0])throw new Error("R value is negative");if(128&e[0])throw new Error("S value is negative");if(r>1&&0===t[0]&&!(128&t[1]))throw new Error("R value excessively padded");if(n>1&&0===e[0]&&!(128&e[1]))throw new Error("S value excessively padded");var i=ls.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=t.length,t.copy(i,4),i[4+r]=2,i[5+r]=e.length,e.copy(i,6+r),i}};Object.defineProperty(us,"__esModule",{value:!0});const ds=as,gs=ps,ms=xo,ys=Buffer.alloc(1,0);function vs(t){let e=0;for(;0===t[e];)++e;return e===t.length?ys:128&(t=t.slice(e))[0]?Buffer.concat([ys,t],1+t.length):t}function ws(t){0===t[0]&&(t=t.slice(1));const e=Buffer.alloc(32,0),r=Math.max(0,32-t.length);return t.copy(e,r),e}us.decode=function(t){const e=t.readUInt8(t.length-1),r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=gs.decode(t.slice(0,-1)),i=ws(n.r),o=ws(n.s);return{signature:Buffer.concat([i,o],64),hashType:e}},us.encode=function(t,e){ms({signature:ds.BufferN(64),hashType:ds.UInt8},{signature:t,hashType:e});const r=-129&e;if(r<=0||r>=4)throw new Error("Invalid hashType "+e);const n=Buffer.allocUnsafe(1);n.writeUInt8(e,0);const i=vs(t.slice(0,32)),o=vs(t.slice(32,64));return Buffer.concat([gs.encode(i,o),n])};var bs={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},_s=bs;function Es(t){return t<_s.OP_PUSHDATA1?1:t<=255?2:t<=65535?3:5}var Ss={encodingLength:Es,encode:function(t,e,r){var n=Es(e);return 1===n?t.writeUInt8(e,r):2===n?(t.writeUInt8(_s.OP_PUSHDATA1,r),t.writeUInt8(e,r+1)):3===n?(t.writeUInt8(_s.OP_PUSHDATA2,r),t.writeUInt16LE(e,r+1)):(t.writeUInt8(_s.OP_PUSHDATA4,r),t.writeUInt32LE(e,r+1)),n},decode:function(t,e){var r,n,i=t.readUInt8(e);if(i<_s.OP_PUSHDATA1)r=i,n=1;else if(i===_s.OP_PUSHDATA1){if(e+2>t.length)return null;r=t.readUInt8(e+1),n=2}else if(i===_s.OP_PUSHDATA2){if(e+3>t.length)return null;r=t.readUInt16LE(e+1),n=3}else{if(e+5>t.length)return null;if(i!==_s.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=t.readUInt32LE(e+1),n=5}return{opcode:i,number:r,size:n}}},Is=bs,Ms={};for(var Ts in Is){Ms[Is[Ts]]=Ts}var Os=Ms;!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ss,r=us,n=as,i=ps,o=Nt.exports,s=Ss,u=xo;t.OPS=bs;const a=Os,h=t.OPS.OP_RESERVED;function f(e){return n.Buffer(e)||function(e){return n.Number(e)&&(e===t.OPS.OP_0||e>=t.OPS.OP_1&&e<=t.OPS.OP_16||e===t.OPS.OP_1NEGATE)}(e)}function c(t){return n.Array(t)&&t.every(f)}function l(e){return 0===e.length?t.OPS.OP_0:1===e.length?e[0]>=1&&e[0]<=16?h+e[0]:129===e[0]?t.OPS.OP_1NEGATE:void 0:void 0}function p(t){return Buffer.isBuffer(t)}function d(t){return Buffer.isBuffer(t)}function g(t){if(p(t))return t;u(n.Array,t);const e=t.reduce(((t,e)=>d(e)?1===e.length&&void 0!==l(e)?t+1:t+s.encodingLength(e.length)+e.length:t+1),0),r=Buffer.allocUnsafe(e);let i=0;if(t.forEach((t=>{if(d(t)){const e=l(t);if(void 0!==e)return r.writeUInt8(e,i),void(i+=1);i+=s.encode(r,t.length,i),t.copy(r,i),i+=t.length}else r.writeUInt8(t,i),i+=1})),i!==r.length)throw new Error("Could not decode chunks");return r}function m(e){if(r=e,n.Array(r))return e;var r;u(n.Buffer,e);const i=[];let o=0;for(;ot.OPS.OP_0&&r<=t.OPS.OP_PUSHDATA4){const t=s.decode(e,o);if(null===t)return null;if(o+=t.size,o+t.number>e.length)return null;const r=e.slice(o,o+t.number);o+=t.number;const n=l(r);void 0!==n?i.push(n):i.push(r)}else i.push(r),o+=1}return i}function y(t){const e=-129&t;return e>0&&e<4}t.isPushOnly=c,t.compile=g,t.decompile=m,t.toASM=function(t){return p(t)&&(t=m(t)),t.map((t=>{if(d(t)){const e=l(t);if(void 0===e)return t.toString("hex");t=e}return a[t]})).join(" ")},t.fromASM=function(e){return u(n.String,e),g(e.split(" ").map((e=>void 0!==t.OPS[e]?t.OPS[e]:(u(n.Hex,e),Buffer.from(e,"hex")))))},t.toStack=function(r){return r=m(r),u(c,r),r.map((r=>d(r)?r:r===t.OPS.OP_0?Buffer.allocUnsafe(0):e.encode(r-h)))},t.isCanonicalPubKey=function(t){return o.isPoint(t)},t.isDefinedHashType=y,t.isCanonicalScriptSignature=function(t){return!!Buffer.isBuffer(t)&&(!!y(t[t.length-1])&&i.check(t.slice(0,-1)))},t.number=e,t.signature=r}(os);var As={};Object.defineProperty(As,"__esModule",{value:!0}),As.prop=function(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get(){const t=r.call(this);return this[e]=t,t},set(t){Object.defineProperty(this,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}})},As.value=function(t){let e;return()=>(void 0!==e||(e=t()),e)},Object.defineProperty(is,"__esModule",{value:!0});const Ps=rs,ks=os,Rs=As,Ns=xo,xs=ks.OPS;is.p2data=function(t,e){if(!t.data&&!t.output)throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ns({network:Ns.maybe(Ns.Object),output:Ns.maybe(Ns.Buffer),data:Ns.maybe(Ns.arrayOf(Ns.Buffer))},t);const r={name:"embed",network:t.network||Ps.bitcoin};if(Rs.prop(r,"output",(()=>{if(t.data)return ks.compile([xs.OP_RETURN].concat(t.data))})),Rs.prop(r,"data",(()=>{if(t.output)return ks.decompile(t.output).slice(1)})),e.validate&&t.output){const e=ks.decompile(t.output);if(e[0]!==xs.OP_RETURN)throw new TypeError("Output is invalid");if(!e.slice(1).every(Ns.Buffer))throw new TypeError("Output is invalid");if(t.data&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.data,r.data))throw new TypeError("Data mismatch")}return Object.assign(r,t)};var Bs={};Object.defineProperty(Bs,"__esModule",{value:!0});const Ls=rs,Us=os,Cs=As,Ds=Us.OPS,Hs=xo,Fs=Nt.exports,js=Ds.OP_RESERVED;function qs(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}Bs.p2ms=function(t,e){if(!(t.input||t.output||t.pubkeys&&void 0!==t.m||t.signatures))throw new TypeError("Not enough data");function r(t){return Us.isCanonicalScriptSignature(t)||void 0!==(e.allowIncomplete&&t===Ds.OP_0)}e=Object.assign({validate:!0},e||{}),Hs({network:Hs.maybe(Hs.Object),m:Hs.maybe(Hs.Number),n:Hs.maybe(Hs.Number),output:Hs.maybe(Hs.Buffer),pubkeys:Hs.maybe(Hs.arrayOf(Fs.isPoint)),signatures:Hs.maybe(Hs.arrayOf(r)),input:Hs.maybe(Hs.Buffer)},t);const n={network:t.network||Ls.bitcoin};let i=[],o=!1;function s(t){o||(o=!0,i=Us.decompile(t),n.m=i[0]-js,n.n=i[i.length-2]-js,n.pubkeys=i.slice(1,-2))}if(Cs.prop(n,"output",(()=>{if(t.m&&n.n&&t.pubkeys)return Us.compile([].concat(js+t.m,t.pubkeys,js+n.n,Ds.OP_CHECKMULTISIG))})),Cs.prop(n,"m",(()=>{if(n.output)return s(n.output),n.m})),Cs.prop(n,"n",(()=>{if(n.pubkeys)return n.pubkeys.length})),Cs.prop(n,"pubkeys",(()=>{if(t.output)return s(t.output),n.pubkeys})),Cs.prop(n,"signatures",(()=>{if(t.input)return Us.decompile(t.input).slice(1)})),Cs.prop(n,"input",(()=>{if(t.signatures)return Us.compile([Ds.OP_0].concat(t.signatures))})),Cs.prop(n,"witness",(()=>{if(n.input)return[]})),Cs.prop(n,"name",(()=>{if(n.m&&n.n)return`p2ms(${n.m} of ${n.n})`})),e.validate){if(t.output){if(s(t.output),!Hs.Number(i[0]))throw new TypeError("Output is invalid");if(!Hs.Number(i[i.length-2]))throw new TypeError("Output is invalid");if(i[i.length-1]!==Ds.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(n.m<=0||n.n>16||n.m>n.n||n.n!==i.length-3)throw new TypeError("Output is invalid");if(!n.pubkeys.every((t=>Fs.isPoint(t))))throw new TypeError("Output is invalid");if(void 0!==t.m&&t.m!==n.m)throw new TypeError("m mismatch");if(void 0!==t.n&&t.n!==n.n)throw new TypeError("n mismatch");if(t.pubkeys&&!qs(t.pubkeys,n.pubkeys))throw new TypeError("Pubkeys mismatch")}if(t.pubkeys){if(void 0!==t.n&&t.n!==t.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(n.n=t.pubkeys.length,n.nn.m)throw new TypeError("Too many signatures provided")}if(t.input){if(t.input[0]!==Ds.OP_0)throw new TypeError("Input is invalid");if(0===n.signatures.length||!n.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(t.signatures&&!qs(t.signatures,n.signatures))throw new TypeError("Signature mismatch");if(void 0!==t.m&&t.m!==t.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(n,t)};var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});const Ks=rs,Ws=os,Vs=As,$s=xo,zs=Ws.OPS,Xs=Nt.exports;Gs.p2pk=function(t,e){if(!(t.input||t.output||t.pubkey||t.input||t.signature))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),$s({network:$s.maybe($s.Object),output:$s.maybe($s.Buffer),pubkey:$s.maybe(Xs.isPoint),signature:$s.maybe(Ws.isCanonicalScriptSignature),input:$s.maybe($s.Buffer)},t);const r=Vs.value((()=>Ws.decompile(t.input))),n={name:"p2pk",network:t.network||Ks.bitcoin};if(Vs.prop(n,"output",(()=>{if(t.pubkey)return Ws.compile([t.pubkey,zs.OP_CHECKSIG])})),Vs.prop(n,"pubkey",(()=>{if(t.output)return t.output.slice(1,-1)})),Vs.prop(n,"signature",(()=>{if(t.input)return r()[0]})),Vs.prop(n,"input",(()=>{if(t.signature)return Ws.compile([t.signature])})),Vs.prop(n,"witness",(()=>{if(n.input)return[]})),e.validate){if(t.output){if(t.output[t.output.length-1]!==zs.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!Xs.isPoint(n.pubkey))throw new TypeError("Output pubkey is invalid");if(t.pubkey&&!t.pubkey.equals(n.pubkey))throw new TypeError("Pubkey mismatch")}if(t.signature&&t.input&&!t.input.equals(n.input))throw new TypeError("Signature mismatch");if(t.input){if(1!==r().length)throw new TypeError("Input is invalid");if(!Ws.isCanonicalScriptSignature(n.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(n,t)};var Ys={},Js={};Object.defineProperty(Js,"__esModule",{value:!0});const Zs=h;function Qs(t){try{return Zs("rmd160").update(t).digest()}catch(e){return Zs("ripemd160").update(t).digest()}}function tu(t){return Zs("sha256").update(t).digest()}Js.ripemd160=Qs,Js.sha1=function(t){return Zs("sha1").update(t).digest()},Js.sha256=tu,Js.hash160=function(t){return Qs(tu(t))},Js.hash256=function(t){return tu(tu(t))},Object.defineProperty(Ys,"__esModule",{value:!0});const eu=Js,ru=rs,nu=os,iu=As,ou=xo,su=nu.OPS,uu=Nt.exports,au=vt;Ys.p2pkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ou({network:ou.maybe(ou.Object),address:ou.maybe(ou.String),hash:ou.maybe(ou.BufferN(20)),output:ou.maybe(ou.BufferN(25)),pubkey:ou.maybe(uu.isPoint),signature:ou.maybe(nu.isCanonicalScriptSignature),input:ou.maybe(ou.Buffer)},t);const r=iu.value((()=>{const e=au.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),n=iu.value((()=>nu.decompile(t.input))),i=t.network||ru.bitcoin,o={name:"p2pkh",network:i};if(iu.prop(o,"address",(()=>{if(!o.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(i.pubKeyHash,0),o.hash.copy(t,1),au.encode(t)})),iu.prop(o,"hash",(()=>t.output?t.output.slice(3,23):t.address?r().hash:t.pubkey||o.pubkey?eu.hash160(t.pubkey||o.pubkey):void 0)),iu.prop(o,"output",(()=>{if(o.hash)return nu.compile([su.OP_DUP,su.OP_HASH160,o.hash,su.OP_EQUALVERIFY,su.OP_CHECKSIG])})),iu.prop(o,"pubkey",(()=>{if(t.input)return n()[1]})),iu.prop(o,"signature",(()=>{if(t.input)return n()[0]})),iu.prop(o,"input",(()=>{if(t.pubkey&&t.signature)return nu.compile([t.signature,t.pubkey])})),iu.prop(o,"witness",(()=>{if(o.input)return[]})),e.validate){let e=Buffer.from([]);if(t.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(20!==r().hash.length)throw new TypeError("Invalid address");e=r().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(25!==t.output.length||t.output[0]!==su.OP_DUP||t.output[1]!==su.OP_HASH160||20!==t.output[2]||t.output[23]!==su.OP_EQUALVERIFY||t.output[24]!==su.OP_CHECKSIG)throw new TypeError("Output is invalid");const r=t.output.slice(3,23);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.pubkey){const r=eu.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.input){const r=n();if(2!==r.length)throw new TypeError("Input is invalid");if(!nu.isCanonicalScriptSignature(r[0]))throw new TypeError("Input has invalid signature");if(!uu.isPoint(r[1]))throw new TypeError("Input has invalid pubkey");if(t.signature&&!t.signature.equals(r[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(r[1]))throw new TypeError("Pubkey mismatch");const i=eu.hash160(r[1]);if(e.length>0&&!e.equals(i))throw new TypeError("Hash mismatch")}}return Object.assign(o,t)};var hu={};Object.defineProperty(hu,"__esModule",{value:!0});const fu=Js,cu=rs,lu=os,pu=As,du=xo,gu=lu.OPS,mu=vt;hu.p2sh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.input))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),du({network:du.maybe(du.Object),address:du.maybe(du.String),hash:du.maybe(du.BufferN(20)),output:du.maybe(du.BufferN(23)),redeem:du.maybe({network:du.maybe(du.Object),output:du.maybe(du.Buffer),input:du.maybe(du.Buffer),witness:du.maybe(du.arrayOf(du.Buffer))}),input:du.maybe(du.Buffer),witness:du.maybe(du.arrayOf(du.Buffer))},t);let r=t.network;r||(r=t.redeem&&t.redeem.network||cu.bitcoin);const n={network:r},i=pu.value((()=>{const e=mu.decode(t.address);return{version:e.readUInt8(0),hash:e.slice(1)}})),o=pu.value((()=>lu.decompile(t.input))),s=pu.value((()=>{const e=o();return{network:r,output:e[e.length-1],input:lu.compile(e.slice(0,-1)),witness:t.witness||[]}}));if(pu.prop(n,"address",(()=>{if(!n.hash)return;const t=Buffer.allocUnsafe(21);return t.writeUInt8(n.network.scriptHash,0),n.hash.copy(t,1),mu.encode(t)})),pu.prop(n,"hash",(()=>t.output?t.output.slice(2,22):t.address?i().hash:n.redeem&&n.redeem.output?fu.hash160(n.redeem.output):void 0)),pu.prop(n,"output",(()=>{if(n.hash)return lu.compile([gu.OP_HASH160,n.hash,gu.OP_EQUAL])})),pu.prop(n,"redeem",(()=>{if(t.input)return s()})),pu.prop(n,"input",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.output)return lu.compile([].concat(lu.decompile(t.redeem.input),t.redeem.output))})),pu.prop(n,"witness",(()=>n.redeem&&n.redeem.witness?n.redeem.witness:n.input?[]:void 0)),pu.prop(n,"name",(()=>{const t=["p2sh"];return void 0!==n.redeem&&t.push(n.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(20!==i().hash.length)throw new TypeError("Invalid address");e=i().hash}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(23!==t.output.length||t.output[0]!==gu.OP_HASH160||20!==t.output[1]||t.output[22]!==gu.OP_EQUAL)throw new TypeError("Output is invalid");const r=t.output.slice(2,22);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}const n=t=>{if(t.output){const r=lu.decompile(t.output);if(!r||r.length<1)throw new TypeError("Redeem.output too short");const n=fu.hash160(t.output);if(e.length>0&&!e.equals(n))throw new TypeError("Hash mismatch");e=n}if(t.input){const e=t.input.length>0,r=t.witness&&t.witness.length>0;if(!e&&!r)throw new TypeError("Empty input");if(e&&r)throw new TypeError("Input and witness provided");if(e){const e=lu.decompile(t.input);if(!lu.isPushOnly(e))throw new TypeError("Non push-only scriptSig")}}};if(t.input){const t=o();if(!t||t.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(s().output))throw new TypeError("Input is invalid");n(s())}if(t.redeem){if(t.redeem.network&&t.redeem.network!==r)throw new TypeError("Network mismatch");if(t.input){const e=s();if(t.redeem.output&&!t.redeem.output.equals(e.output))throw new TypeError("Redeem.output mismatch");if(t.redeem.input&&!t.redeem.input.equals(e.input))throw new TypeError("Redeem.input mismatch")}n(t.redeem)}if(t.witness&&t.redeem&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.redeem.witness,t.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,t)};for(var yu={},vu="qpzry9x8gf2tvdw0s3jn54khce6mua7l",wu={},bu=0;bu>25;return(33554431&t)<<5^996825010&-(e>>0&1)^642813549&-(e>>1&1)^513874426&-(e>>2&1)^1027748829&-(e>>3&1)^705979059&-(e>>4&1)}function Su(t){for(var e=1,r=0;r126)return"Invalid prefix ("+t+")";e=Eu(e)^n>>5}for(e=Eu(e),r=0;re)return"Exceeds length limit";var r=t.toLowerCase(),n=t.toUpperCase();if(t!==r&&t!==n)return"Mixed-case string "+t;var i=(t=r).lastIndexOf("1");if(-1===i)return"No separator character for "+t;if(0===i)return"Missing prefix for "+t;var o=t.slice(0,i),s=t.slice(i+1);if(s.length<6)return"Data too short";var u=Su(o);if("string"==typeof u)return u;for(var a=[],h=0;h=s.length||a.push(c)}return 1!==u?"Invalid checksum for "+t:{prefix:o,words:a}}function Mu(t,e,r,n){for(var i=0,o=0,s=(1<=r;)o-=r,u.push(i>>o&s);if(n)o>0&&u.push(i<=e)return"Excess padding";if(i<r)throw new TypeError("Exceeds length limit");var n=Su(t=t.toLowerCase());if("string"==typeof n)throw new Error(n);for(var i=t+"1",o=0;o>5!=0)throw new Error("Non 5-bit word");n=Eu(n)^s,i+=vu.charAt(s)}for(o=0;o<6;++o)n=Eu(n);for(n^=1,o=0;o<6;++o){i+=vu.charAt(n>>5*(5-o)&31)}return i},toWordsUnsafe:function(t){var e=Mu(t,8,5,!0);if(Array.isArray(e))return e},toWords:function(t){var e=Mu(t,8,5,!0);if(Array.isArray(e))return e;throw new Error(e)},fromWordsUnsafe:function(t){var e=Mu(t,5,8,!1);if(Array.isArray(e))return e},fromWords:function(t){var e=Mu(t,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}};Object.defineProperty(yu,"__esModule",{value:!0});const Ou=Js,Au=rs,Pu=os,ku=As,Ru=xo,Nu=Pu.OPS,xu=Nt.exports,Bu=Tu,Lu=Buffer.alloc(0);yu.p2wpkh=function(t,e){if(!(t.address||t.hash||t.output||t.pubkey||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),Ru({address:Ru.maybe(Ru.String),hash:Ru.maybe(Ru.BufferN(20)),input:Ru.maybe(Ru.BufferN(0)),network:Ru.maybe(Ru.Object),output:Ru.maybe(Ru.BufferN(22)),pubkey:Ru.maybe(xu.isPoint),signature:Ru.maybe(Pu.isCanonicalScriptSignature),witness:Ru.maybe(Ru.arrayOf(Ru.Buffer))},t);const r=ku.value((()=>{const e=Bu.decode(t.address),r=e.words.shift(),n=Bu.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=t.network||Au.bitcoin,i={name:"p2wpkh",network:n};if(ku.prop(i,"address",(()=>{if(!i.hash)return;const t=Bu.toWords(i.hash);return t.unshift(0),Bu.encode(n.bech32,t)})),ku.prop(i,"hash",(()=>t.output?t.output.slice(2,22):t.address?r().data:t.pubkey||i.pubkey?Ou.hash160(t.pubkey||i.pubkey):void 0)),ku.prop(i,"output",(()=>{if(i.hash)return Pu.compile([Nu.OP_0,i.hash])})),ku.prop(i,"pubkey",(()=>t.pubkey?t.pubkey:t.witness?t.witness[1]:void 0)),ku.prop(i,"signature",(()=>{if(t.witness)return t.witness[0]})),ku.prop(i,"input",(()=>{if(i.witness)return Lu})),ku.prop(i,"witness",(()=>{if(t.pubkey&&t.signature)return[t.signature,t.pubkey]})),e.validate){let e=Buffer.from([]);if(t.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(20!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(22!==t.output.length||t.output[0]!==Nu.OP_0||20!==t.output[1])throw new TypeError("Output is invalid");if(e.length>0&&!e.equals(t.output.slice(2)))throw new TypeError("Hash mismatch");e=t.output.slice(2)}if(t.pubkey){const r=Ou.hash160(t.pubkey);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");if(e=r,!xu.isPoint(t.pubkey)||33!==t.pubkey.length)throw new TypeError("Invalid pubkey for p2wpkh")}if(t.witness){if(2!==t.witness.length)throw new TypeError("Witness is invalid");if(!Pu.isCanonicalScriptSignature(t.witness[0]))throw new TypeError("Witness has invalid signature");if(!xu.isPoint(t.witness[1])||33!==t.witness[1].length)throw new TypeError("Witness has invalid pubkey");if(t.signature&&!t.signature.equals(t.witness[0]))throw new TypeError("Signature mismatch");if(t.pubkey&&!t.pubkey.equals(t.witness[1]))throw new TypeError("Pubkey mismatch");const r=Ou.hash160(t.witness[1]);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch")}}return Object.assign(i,t)};var Uu={};Object.defineProperty(Uu,"__esModule",{value:!0});const Cu=Js,Du=rs,Hu=os,Fu=As,ju=xo,qu=Hu.OPS,Gu=Nt.exports,Ku=Tu,Wu=Buffer.alloc(0);function Vu(t){return!(!Buffer.isBuffer(t)||65!==t.length||4!==t[0]||!Gu.isPoint(t))}Uu.p2wsh=function(t,e){if(!(t.address||t.hash||t.output||t.redeem||t.witness))throw new TypeError("Not enough data");e=Object.assign({validate:!0},e||{}),ju({network:ju.maybe(ju.Object),address:ju.maybe(ju.String),hash:ju.maybe(ju.BufferN(32)),output:ju.maybe(ju.BufferN(34)),redeem:ju.maybe({input:ju.maybe(ju.Buffer),network:ju.maybe(ju.Object),output:ju.maybe(ju.Buffer),witness:ju.maybe(ju.arrayOf(ju.Buffer))}),input:ju.maybe(ju.BufferN(0)),witness:ju.maybe(ju.arrayOf(ju.Buffer))},t);const r=Fu.value((()=>{const e=Ku.decode(t.address),r=e.words.shift(),n=Ku.fromWords(e.words);return{version:r,prefix:e.prefix,data:Buffer.from(n)}})),n=Fu.value((()=>Hu.decompile(t.redeem.input)));let i=t.network;i||(i=t.redeem&&t.redeem.network||Du.bitcoin);const o={network:i};if(Fu.prop(o,"address",(()=>{if(!o.hash)return;const t=Ku.toWords(o.hash);return t.unshift(0),Ku.encode(i.bech32,t)})),Fu.prop(o,"hash",(()=>t.output?t.output.slice(2):t.address?r().data:o.redeem&&o.redeem.output?Cu.sha256(o.redeem.output):void 0)),Fu.prop(o,"output",(()=>{if(o.hash)return Hu.compile([qu.OP_0,o.hash])})),Fu.prop(o,"redeem",(()=>{if(t.witness)return{output:t.witness[t.witness.length-1],input:Wu,witness:t.witness.slice(0,-1)}})),Fu.prop(o,"input",(()=>{if(o.witness)return Wu})),Fu.prop(o,"witness",(()=>{if(t.redeem&&t.redeem.input&&t.redeem.input.length>0&&t.redeem.output&&t.redeem.output.length>0){const e=Hu.toStack(n());return o.redeem=Object.assign({witness:e},t.redeem),o.redeem.input=Wu,[].concat(e,t.redeem.output)}if(t.redeem&&t.redeem.output&&t.redeem.witness)return[].concat(t.redeem.witness,t.redeem.output)})),Fu.prop(o,"name",(()=>{const t=["p2wsh"];return void 0!==o.redeem&&t.push(o.redeem.name),t.join("-")})),e.validate){let e=Buffer.from([]);if(t.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(0!==r().version)throw new TypeError("Invalid address version");if(32!==r().data.length)throw new TypeError("Invalid address data");e=r().data}if(t.hash){if(e.length>0&&!e.equals(t.hash))throw new TypeError("Hash mismatch");e=t.hash}if(t.output){if(34!==t.output.length||t.output[0]!==qu.OP_0||32!==t.output[1])throw new TypeError("Output is invalid");const r=t.output.slice(2);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem){if(t.redeem.network&&t.redeem.network!==i)throw new TypeError("Network mismatch");if(t.redeem.input&&t.redeem.input.length>0&&t.redeem.witness&&t.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(t.redeem.output){if(0===Hu.decompile(t.redeem.output).length)throw new TypeError("Redeem.output is invalid");const r=Cu.sha256(t.redeem.output);if(e.length>0&&!e.equals(r))throw new TypeError("Hash mismatch");e=r}if(t.redeem.input&&!Hu.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(t.witness&&t.redeem.witness&&!function(t,e){return t.length===e.length&&t.every(((t,r)=>t.equals(e[r])))}(t.witness,t.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(t.redeem.input&&n().some(Vu)||t.redeem.output&&(Hu.decompile(t.redeem.output)||[]).some(Vu))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(t.witness&&t.witness.length>0){const e=t.witness[t.witness.length-1];if(t.redeem&&t.redeem.output&&!t.redeem.output.equals(e))throw new TypeError("Witness and redeem.output mismatch");if(t.witness.some(Vu)||(Hu.decompile(e)||[]).some(Vu))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(o,t)},Object.defineProperty(ns,"__esModule",{value:!0});const $u=is;ns.embed=$u.p2data;const zu=Bs;ns.p2ms=zu.p2ms;const Xu=Gs;ns.p2pk=Xu.p2pk;const Yu=Ys;ns.p2pkh=Yu.p2pkh;const Ju=hu;ns.p2sh=Ju.p2sh;const Zu=yu;ns.p2wpkh=Zu.p2wpkh;const Qu=Uu;ns.p2wsh=Qu.p2wsh,Object.defineProperty(es,"__esModule",{value:!0});const ta=rs,ea=ns,ra=os,na=as,ia=Tu,oa=vt,sa=xo;function ua(t){const e=oa.decode(t);if(e.length<21)throw new TypeError(t+" is too short");if(e.length>21)throw new TypeError(t+" is too long");return{version:e.readUInt8(0),hash:e.slice(1)}}function aa(t){const e=ia.decode(t),r=ia.fromWords(e.words.slice(1));return{version:e.words[0],prefix:e.prefix,data:Buffer.from(r)}}es.fromBase58Check=ua,es.fromBech32=aa,es.toBase58Check=function(t,e){sa(na.tuple(na.Hash160bit,na.UInt8),arguments);const r=Buffer.allocUnsafe(21);return r.writeUInt8(e,0),t.copy(r,1),oa.encode(r)},es.toBech32=function(t,e,r){const n=ia.toWords(t);return n.unshift(e),ia.encode(r,n)},es.fromOutputScript=function(t,e){e=e||ta.bitcoin;try{return ea.p2pkh({output:t,network:e}).address}catch(t){}try{return ea.p2sh({output:t,network:e}).address}catch(t){}try{return ea.p2wpkh({output:t,network:e}).address}catch(t){}try{return ea.p2wsh({output:t,network:e}).address}catch(t){}throw new Error(ra.toASM(t)+" has no matching Address")},es.toOutputScript=function(t,e){let r,n;e=e||ta.bitcoin;try{r=ua(t)}catch(t){}if(r){if(r.version===e.pubKeyHash)return ea.p2pkh({hash:r.hash}).output;if(r.version===e.scriptHash)return ea.p2sh({hash:r.hash}).output}else{try{n=aa(t)}catch(t){}if(n){if(n.prefix!==e.bech32)throw new Error(t+" has an invalid prefix");if(0===n.version){if(20===n.data.length)return ea.p2wpkh({hash:n.data}).output;if(32===n.data.length)return ea.p2wsh({hash:n.data}).output}}}throw new Error(t+" has no matching Script")};var ha={},fa=a.randomBytes;Object.defineProperty(ha,"__esModule",{value:!0});const ca=rs,la=as,pa=Nt.exports,da=fa,ga=xo,ma=Co,ya=ga.maybe(ga.compile({compressed:la.maybe(la.Boolean),network:la.maybe(la.Network)}));class va{constructor(t,e,r){this.__D=t,this.__Q=e,this.lowR=!1,void 0===r&&(r={}),this.compressed=void 0===r.compressed||r.compressed,this.network=r.network||ca.bitcoin,void 0!==e&&(this.__Q=pa.pointCompress(e,this.compressed))}get privateKey(){return this.__D}get publicKey(){return this.__Q||(this.__Q=pa.pointFromScalar(this.__D,this.compressed)),this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return ma.encode(this.network.wif,this.__D,this.compressed)}sign(t,e){if(!this.__D)throw new Error("Missing private key");if(void 0===e&&(e=this.lowR),!1===e)return pa.sign(t,this.__D);{let e=pa.sign(t,this.__D);const r=Buffer.alloc(32,0);let n=0;for(;e[0]>127;)n++,r.writeUIntLE(n,0,6),e=pa.signWithEntropy(t,this.__D,r);return e}}verify(t,e){return pa.verify(t,this.publicKey,e)}}function wa(t,e){if(ga(la.Buffer256bit,t),!pa.isPrivate(t))throw new TypeError("Private key not in range [1, n)");return ga(ya,e),new va(t,void 0,e)}ha.fromPrivateKey=wa,ha.fromPublicKey=function(t,e){return ga(pa.isPoint,t),ga(ya,e),new va(void 0,t,e)},ha.fromWIF=function(t,e){const r=ma.decode(t),n=r.version;if(la.Array(e)){if(e=e.filter((t=>n===t.wif)).pop(),!e)throw new Error("Unknown network version")}else if(e=e||ca.bitcoin,n!==e.wif)throw new Error("Invalid network version");return wa(r.privateKey,{compressed:r.compressed,network:e})},ha.makeRandom=function(t){ga(ya,t),void 0===t&&(t={});const e=t.rng||da;let r;do{r=e(32),ga(la.Buffer256bit,r)}while(!pa.isPrivate(r));return wa(r,t)};var ba={},_a={},Ea=f.exports.Buffer;function Sa(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Ia(t){return Sa(t),t<253?1:t<=65535?3:t<=4294967295?5:9}var Ma={encode:function t(e,r,n){if(Sa(e),r||(r=Ea.allocUnsafe(Ia(e))),!Ea.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),t.bytes=1):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),t.bytes=3):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),t.bytes=5):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),t.bytes=9),r},decode:function t(e,r){if(!Ea.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);var n=e.readUInt8(r);if(n<253)return t.bytes=1,n;if(253===n)return t.bytes=3,e.readUInt16LE(r+1);if(254===n)return t.bytes=5,e.readUInt32LE(r+1);t.bytes=9;var i=e.readUInt32LE(r+1),o=4294967296*e.readUInt32LE(r+5)+i;return Sa(o),o},encodingLength:Ia};Object.defineProperty(_a,"__esModule",{value:!0});const Ta=as,Oa=xo,Aa=Ma;function Pa(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}function ka(t,e){const r=t.readUInt32LE(e);let n=t.readUInt32LE(e+4);return n*=4294967296,Pa(n+r,9007199254740991),n+r}function Ra(t,e,r){return Pa(e,9007199254740991),t.writeInt32LE(-1&e,r),t.writeUInt32LE(Math.floor(e/4294967296),r+4),r+8}_a.readUInt64LE=ka,_a.writeUInt64LE=Ra,_a.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;nthis.writeVarSlice(t)))}};_a.BufferReader=class{constructor(t,e=0){this.buffer=t,this.offset=e,Oa(Ta.tuple(Ta.Buffer,Ta.UInt32),[t,e])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=ka(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=Aa.decode(this.buffer,this.offset);return this.offset+=Aa.decode.bytes,t}readSlice(t){if(this.buffer.length0!==t.witness.length))}weight(){return 3*this.byteLength(!1)+this.byteLength(!0)}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const e=t&&this.hasWitnesses();return(e?10:8)+Ha.encodingLength(this.ins.length)+Ha.encodingLength(this.outs.length)+this.ins.reduce(((t,e)=>t+40+Fa(e.script)),0)+this.outs.reduce(((t,e)=>t+8+Fa(e.script)),0)+(e?this.ins.reduce(((t,e)=>t+function(t){const e=t.length;return Ha.encodingLength(e)+t.reduce(((t,e)=>t+Fa(e)),0)}(e.witness)),0):0)}clone(){const t=new $a;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map((t=>({hash:t.hash,index:t.index,script:t.script,sequence:t.sequence,witness:t.witness}))),t.outs=this.outs.map((t=>({script:t.script,value:t.value}))),t}hashForSignature(t,e,r){if(Da(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Number),arguments),t>=this.ins.length)return Ka;const n=La.compile(La.decompile(e).filter((t=>t!==Ua.OPS.OP_CODESEPARATOR))),i=this.clone();if((31&r)===$a.SIGHASH_NONE)i.outs=[],i.ins.forEach(((e,r)=>{r!==t&&(e.sequence=0)}));else if((31&r)===$a.SIGHASH_SINGLE){if(t>=this.outs.length)return Ka;i.outs.length=t+1;for(let e=0;e{r!==t&&(e.sequence=0)}))}r&$a.SIGHASH_ANYONECANPAY?(i.ins=[i.ins[t]],i.ins[0].script=n):(i.ins.forEach((t=>{t.script=ja})),i.ins[t].script=n);const o=Buffer.allocUnsafe(i.byteLength(!1)+4);return o.writeInt32LE(r,o.length-4),i.__toBuffer(o,0,!1),Ba.hash256(o)}hashForWitnessV0(t,e,r,n){Da(Ca.tuple(Ca.UInt32,Ca.Buffer,Ca.Satoshi,Ca.UInt32),arguments);let i,o=Buffer.from([]),s=Ga,u=Ga,a=Ga;if(n&$a.SIGHASH_ANYONECANPAY||(o=Buffer.allocUnsafe(36*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeSlice(t.hash),i.writeUInt32(t.index)})),u=Ba.hash256(o)),n&$a.SIGHASH_ANYONECANPAY||(31&n)===$a.SIGHASH_SINGLE||(31&n)===$a.SIGHASH_NONE||(o=Buffer.allocUnsafe(4*this.ins.length),i=new xa.BufferWriter(o,0),this.ins.forEach((t=>{i.writeUInt32(t.sequence)})),a=Ba.hash256(o)),(31&n)!==$a.SIGHASH_SINGLE&&(31&n)!==$a.SIGHASH_NONE){const t=this.outs.reduce(((t,e)=>t+8+Fa(e.script)),0);o=Buffer.allocUnsafe(t),i=new xa.BufferWriter(o,0),this.outs.forEach((t=>{i.writeUInt64(t.value),i.writeVarSlice(t.script)})),s=Ba.hash256(o)}else if((31&n)===$a.SIGHASH_SINGLE&&t{n.writeSlice(t.hash),n.writeUInt32(t.index),n.writeVarSlice(t.script),n.writeUInt32(t.sequence)})),n.writeVarInt(this.outs.length),this.outs.forEach((t=>{void 0!==t.value?n.writeUInt64(t.value):n.writeSlice(t.valueBuffer),n.writeVarSlice(t.script)})),i&&this.ins.forEach((t=>{n.writeVector(t.witness)})),n.writeUInt32(this.locktime),void 0!==e?t.slice(e,n.offset):t}}$a.DEFAULT_SEQUENCE=4294967295,$a.SIGHASH_ALL=1,$a.SIGHASH_NONE=2,$a.SIGHASH_SINGLE=3,$a.SIGHASH_ANYONECANPAY=128,$a.ADVANCED_TRANSACTION_MARKER=0,$a.ADVANCED_TRANSACTION_FLAG=1,Na.Transaction=$a;Object.defineProperty(ba,"__esModule",{value:!0});const za=_a,Xa=Js,Ya=Na,Ja=as,Za=function(t,e){if(!Array.isArray(t))throw TypeError("Expected values Array");if("function"!=typeof e)throw TypeError("Expected digest Function");for(var r=t.length,n=t.concat();r>1;){for(var i=0,o=0;o{const t=Ya.Transaction.fromBuffer(e.buffer.slice(e.offset),!0);return e.offset+=t.byteLength(),t},i=e.readVarInt();r.transactions=[];for(let t=0;t>24)-3,r=8388607&t,n=Buffer.alloc(32,0);return n.writeUIntBE(r,29-e,3),n}static calculateMerkleRoot(t,e){if(Qa([{getHash:Ja.Function}],t),0===t.length)throw eh;if(e&&!ih(t))throw rh;const r=t.map((t=>t.getHash(e))),n=Za(r,Xa.hash256);return e?Xa.hash256(Buffer.concat([n,t[0].ins[0].witness[0]])):n}getWitnessCommit(){if(!ih(this.transactions))return null;const t=this.transactions[0].outs.filter((t=>t.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex")))).map((t=>t.script.slice(6,38)));if(0===t.length)return null;const e=t[t.length-1];return e instanceof Buffer&&32===e.length?e:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&32===this.witnessCommit.length||null!==this.getWitnessCommit()}hasWitness(){return(t=this.transactions)instanceof Array&&t.some((t=>"object"==typeof t&&t.ins instanceof Array&&t.ins.some((t=>"object"==typeof t&&t.witness instanceof Array&&t.witness.length>0))));var t}weight(){return 3*this.byteLength(!1,!1)+this.byteLength(!1,!0)}byteLength(t,e=!0){return t||!this.transactions?80:80+th.encodingLength(this.transactions.length)+this.transactions.reduce(((t,r)=>t+r.byteLength(e)),0)}getHash(){return Xa.hash256(this.toBuffer(!0))}getId(){return za.reverseBuffer(this.getHash()).toString("hex")}getUTCDate(){const t=new Date(0);return t.setUTCSeconds(this.timestamp),t}toBuffer(t){const e=Buffer.allocUnsafe(this.byteLength(t)),r=new za.BufferWriter(e);return r.writeInt32(this.version),r.writeSlice(this.prevHash),r.writeSlice(this.merkleRoot),r.writeUInt32(this.timestamp),r.writeUInt32(this.bits),r.writeUInt32(this.nonce),t||!this.transactions||(th.encode(this.transactions.length,e,r.offset),r.offset+=th.encode.bytes,this.transactions.forEach((t=>{const n=t.byteLength();t.toBuffer(e,r.offset),r.offset+=n}))),e}toHex(t){return this.toBuffer(t).toString("hex")}checkTxRoots(){const t=this.hasWitnessCommit();return!(!t&&this.hasWitness())&&(this.__checkMerkleRoot()&&(!t||this.__checkWitnessCommit()))}checkProofOfWork(){const t=za.reverseBuffer(this.getHash()),e=nh.calculateTarget(this.bits);return t.compare(e)<=0}__checkMerkleRoot(){if(!this.transactions)throw eh;const t=nh.calculateMerkleRoot(this.transactions);return 0===this.merkleRoot.compare(t)}__checkWitnessCommit(){if(!this.transactions)throw eh;if(!this.hasWitnessCommit())throw rh;const t=nh.calculateMerkleRoot(this.transactions,!0);return 0===this.witnessCommit.compare(t)}}function ih(t){return t instanceof Array&&t[0]&&t[0].ins&&t[0].ins instanceof Array&&t[0].ins[0]&&t[0].ins[0].witness&&t[0].ins[0].witness instanceof Array&&t[0].ins[0].witness.length>0}ba.Block=nh;var oh={},sh={},uh={},ah={},hh={},fh={},ch={};!function(t){var e,r,n;Object.defineProperty(t,"__esModule",{value:!0}),(e=t.GlobalTypes||(t.GlobalTypes={}))[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB",t.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(r=t.InputTypes||(t.InputTypes={}))[r.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",r[r.WITNESS_UTXO=1]="WITNESS_UTXO",r[r.PARTIAL_SIG=2]="PARTIAL_SIG",r[r.SIGHASH_TYPE=3]="SIGHASH_TYPE",r[r.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",r[r.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",r[r.BIP32_DERIVATION=6]="BIP32_DERIVATION",r[r.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",r[r.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",r[r.POR_COMMITMENT=9]="POR_COMMITMENT",t.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment"],(n=t.OutputTypes||(t.OutputTypes={}))[n.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",n[n.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",n[n.BIP32_DERIVATION=2]="BIP32_DERIVATION",t.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation"]}(ch);var lh={};Object.defineProperty(lh,"__esModule",{value:!0});const ph=ch;lh.decode=function(t){if(t.key[0]!==ph.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+t.key.toString("hex"));if(79!==t.key.length||![2,3].includes(t.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+t.key.toString("hex"));if(t.value.length/4%1!=0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const e=t.key.slice(1),r={masterFingerprint:t.value.slice(0,4),extendedPubkey:e,path:"m"};for(const e of(t=>[...Array(t).keys()])(t.value.length/4-1)){const n=t.value.readUInt32LE(4*e+4),i=!!(2147483648&n),o=2147483647&n;r.path+="/"+o.toString(10)+(i?"'":"")}return r},lh.encode=function(t){const e=Buffer.from([ph.GlobalTypes.GLOBAL_XPUB]),r=Buffer.concat([e,t.extendedPubkey]),n=t.path.split("/"),i=Buffer.allocUnsafe(4*n.length);t.masterFingerprint.copy(i,0);let o=4;return n.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),i.writeUInt32LE(r,o),o+=4})),{key:r,value:i}},lh.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }",lh.check=function(t){const e=t.extendedPubkey,r=t.masterFingerprint,n=t.path;return Buffer.isBuffer(e)&&78===e.length&&[2,3].indexOf(e[45])>-1&&Buffer.isBuffer(r)&&4===r.length&&"string"==typeof n&&!!n.match(/^m(\/\d+'?)+$/)},lh.canAddToArray=function(t,e,r){const n=e.extendedPubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.extendedPubkey.equals(e.extendedPubkey))).length)};var dh={};Object.defineProperty(dh,"__esModule",{value:!0});const gh=ch;dh.encode=function(t){return{key:Buffer.from([gh.GlobalTypes.UNSIGNED_TX]),value:t.toBuffer()}};var mh={};Object.defineProperty(mh,"__esModule",{value:!0});const yh=ch;mh.decode=function(t){if(t.key[0]!==yh.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+t.key.toString("hex"));return t.value},mh.encode=function(t){return{key:Buffer.from([yh.InputTypes.FINAL_SCRIPTSIG]),value:t}},mh.expected="Buffer",mh.check=function(t){return Buffer.isBuffer(t)},mh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptSig};var vh={};Object.defineProperty(vh,"__esModule",{value:!0});const wh=ch;vh.decode=function(t){if(t.key[0]!==wh.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+t.key.toString("hex"));return t.value},vh.encode=function(t){return{key:Buffer.from([wh.InputTypes.FINAL_SCRIPTWITNESS]),value:t}},vh.expected="Buffer",vh.check=function(t){return Buffer.isBuffer(t)},vh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.finalScriptWitness};var bh={};Object.defineProperty(bh,"__esModule",{value:!0});const _h=ch;bh.decode=function(t){if(t.key[0]!==_h.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+t.key.toString("hex"));return t.value},bh.encode=function(t){return{key:Buffer.from([_h.InputTypes.NON_WITNESS_UTXO]),value:t}},bh.expected="Buffer",bh.check=function(t){return Buffer.isBuffer(t)},bh.canAdd=function(t,e){return!!t&&!!e&&void 0===t.nonWitnessUtxo};var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0});const Sh=ch;Eh.decode=function(t){if(t.key[0]!==Sh.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+t.key.toString("hex"));if(34!==t.key.length&&66!==t.key.length||![2,3,4].includes(t.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+t.key.toString("hex"));return{pubkey:t.key.slice(1),signature:t.value}},Eh.encode=function(t){const e=Buffer.from([Sh.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([e,t.pubkey]),value:t.signature}},Eh.expected="{ pubkey: Buffer; signature: Buffer; }",Eh.check=function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.signature)&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&function(t){if(!Buffer.isBuffer(t)||t.length<9)return!1;if(48!==t[0])return!1;if(t.length!==t[1]+3)return!1;if(2!==t[2])return!1;const e=t[3];if(e>33||e<1)return!1;if(2!==t[3+e+1])return!1;const r=t[3+e+2];return!(r>33||r<1)&&t.length===3+e+2+r+2}(t.signature)},Eh.canAddToArray=function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)};var Ih={};Object.defineProperty(Ih,"__esModule",{value:!0});const Mh=ch;Ih.decode=function(t){if(t.key[0]!==Mh.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+t.key.toString("hex"));return t.value.toString("utf8")},Ih.encode=function(t){return{key:Buffer.from([Mh.InputTypes.POR_COMMITMENT]),value:Buffer.from(t,"utf8")}},Ih.expected="string",Ih.check=function(t){return"string"==typeof t},Ih.canAdd=function(t,e){return!!t&&!!e&&void 0===t.porCommitment};var Th={};Object.defineProperty(Th,"__esModule",{value:!0});const Oh=ch;Th.decode=function(t){if(t.key[0]!==Oh.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+t.key.toString("hex"));return t.value.readUInt32LE(0)},Th.encode=function(t){const e=Buffer.from([Oh.InputTypes.SIGHASH_TYPE]),r=Buffer.allocUnsafe(4);return r.writeUInt32LE(t,0),{key:e,value:r}},Th.expected="number",Th.check=function(t){return"number"==typeof t},Th.canAdd=function(t,e){return!!t&&!!e&&void 0===t.sighashType};var Ah={},Ph={},kh={};Object.defineProperty(kh,"__esModule",{value:!0});function Rh(t){if(t<0||t>9007199254740991||t%1!=0)throw new RangeError("value out of range")}function Nh(t){return Rh(t),t<253?1:t<=65535?3:t<=4294967295?5:9}kh.encode=function t(e,r,n){if(Rh(e),r||(r=Buffer.allocUnsafe(Nh(e))),!Buffer.isBuffer(r))throw new TypeError("buffer must be a Buffer instance");return n||(n=0),e<253?(r.writeUInt8(e,n),Object.assign(t,{bytes:1})):e<=65535?(r.writeUInt8(253,n),r.writeUInt16LE(e,n+1),Object.assign(t,{bytes:3})):e<=4294967295?(r.writeUInt8(254,n),r.writeUInt32LE(e,n+1),Object.assign(t,{bytes:5})):(r.writeUInt8(255,n),r.writeUInt32LE(e>>>0,n+1),r.writeUInt32LE(e/4294967296|0,n+5),Object.assign(t,{bytes:9})),r},kh.decode=function t(e,r){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");r||(r=0);const n=e.readUInt8(r);if(n<253)return Object.assign(t,{bytes:1}),n;if(253===n)return Object.assign(t,{bytes:3}),e.readUInt16LE(r+1);if(254===n)return Object.assign(t,{bytes:5}),e.readUInt32LE(r+1);{Object.assign(t,{bytes:9});const n=e.readUInt32LE(r+1),i=4294967296*e.readUInt32LE(r+5)+n;return Rh(i),i}},kh.encodingLength=Nh,Object.defineProperty(Ph,"__esModule",{value:!0});const xh=kh;function Bh(t){const e=t.key.length,r=t.value.length,n=xh.encodingLength(e),i=xh.encodingLength(r),o=Buffer.allocUnsafe(n+e+i+r);return xh.encode(e,o,0),t.key.copy(o,n),xh.encode(r,o,n+e),t.value.copy(o,n+e+i),o}function Lh(t,e){if("number"!=typeof t)throw new Error("cannot write a non-number as a number");if(t<0)throw new Error("specified a negative value for writing an unsigned value");if(t>e)throw new Error("RangeError: value out of range");if(Math.floor(t)!==t)throw new Error("value has a fractional component")}Ph.range=t=>[...Array(t).keys()],Ph.reverseBuffer=function(t){if(t.length<1)return t;let e=t.length-1,r=0;for(let n=0;n[...Array(t).keys()])(e.value.length/4-1)){const r=e.value.readUInt32LE(4*t+4),i=!!(2147483648&r),o=2147483647&r;n.path+="/"+o.toString(10)+(i?"'":"")}return n},encode:function(e){const r=Buffer.from([t]),n=Buffer.concat([r,e.pubkey]),i=e.path.split("/"),o=Buffer.allocUnsafe(4*i.length);e.masterFingerprint.copy(o,0);let s=4;return i.slice(1).forEach((t=>{const e="'"===t.slice(-1);let r=2147483647&parseInt(e?t.slice(0,-1):t,10);e&&(r+=2147483648),o.writeUInt32LE(r,s),s+=4})),{key:n,value:o}},check:function(t){return Buffer.isBuffer(t.pubkey)&&Buffer.isBuffer(t.masterFingerprint)&&"string"==typeof t.path&&[33,65].includes(t.pubkey.length)&&[2,3,4].includes(t.pubkey[0])&&4===t.masterFingerprint.length},expected:"{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }",canAddToArray:function(t,e,r){const n=e.pubkey.toString("hex");return!r.has(n)&&(r.add(n),0===t.filter((t=>t.pubkey.equals(e.pubkey))).length)}}};var Fh={};Object.defineProperty(Fh,"__esModule",{value:!0}),Fh.makeChecker=function(t){return function(e){let r;if(t.includes(e.key[0])&&(r=e.key.slice(1),33!==r.length&&65!==r.length||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+e.key.toString("hex"));return r}};var jh={};Object.defineProperty(jh,"__esModule",{value:!0}),jh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.redeemScript}}};var qh={};Object.defineProperty(qh,"__esModule",{value:!0}),qh.makeConverter=function(t){return{decode:function(e){if(e.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+e.key.toString("hex"));return e.value},encode:function(e){return{key:Buffer.from([t]),value:e}},check:function(t){return Buffer.isBuffer(t)},expected:"Buffer",canAdd:function(t,e){return!!t&&!!e&&void 0===t.witnessScript}}},Object.defineProperty(fh,"__esModule",{value:!0});const Gh=ch,Kh=mh,Wh=vh,Vh=bh,$h=Eh,zh=Ih,Xh=Th,Yh=Ah,Jh=Hh,Zh=Fh,Qh=jh,tf=qh,ef={unsignedTx:dh,globalXpub:lh,checkPubkey:Zh.makeChecker([])};fh.globals=ef;const rf={nonWitnessUtxo:Vh,partialSig:$h,sighashType:Xh,finalScriptSig:Kh,finalScriptWitness:Wh,porCommitment:zh,witnessUtxo:Yh,bip32Derivation:Jh.makeConverter(Gh.InputTypes.BIP32_DERIVATION),redeemScript:Qh.makeConverter(Gh.InputTypes.REDEEM_SCRIPT),witnessScript:tf.makeConverter(Gh.InputTypes.WITNESS_SCRIPT),checkPubkey:Zh.makeChecker([Gh.InputTypes.PARTIAL_SIG,Gh.InputTypes.BIP32_DERIVATION])};fh.inputs=rf;const nf={bip32Derivation:Jh.makeConverter(Gh.OutputTypes.BIP32_DERIVATION),redeemScript:Qh.makeConverter(Gh.OutputTypes.REDEEM_SCRIPT),witnessScript:tf.makeConverter(Gh.OutputTypes.WITNESS_SCRIPT),checkPubkey:Zh.makeChecker([Gh.OutputTypes.BIP32_DERIVATION])};fh.outputs=nf,Object.defineProperty(hh,"__esModule",{value:!0});const of=fh,sf=Ph,uf=kh,af=ch;function hf(t,e,r){if(!e.equals(Buffer.from([r])))throw new Error(`Format Error: Invalid ${t} key: ${e.toString("hex")}`)}function ff(t,{globalMapKeyVals:e,inputKeyVals:r,outputKeyVals:n}){const i={unsignedTx:t};let o=0;for(const t of e)switch(t.key[0]){case af.GlobalTypes.UNSIGNED_TX:if(hf("global",t.key,af.GlobalTypes.UNSIGNED_TX),o>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");o++;break;case af.GlobalTypes.GLOBAL_XPUB:void 0===i.globalXpub&&(i.globalXpub=[]),i.globalXpub.push(of.globals.globalXpub.decode(t));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(t)}const s=r.length,u=n.length,a=[],h=[];for(const t of sf.range(s)){const e={};for(const n of r[t])switch(of.inputs.checkPubkey(n),n.key[0]){case af.InputTypes.NON_WITNESS_UTXO:if(hf("input",n.key,af.InputTypes.NON_WITNESS_UTXO),void 0!==e.nonWitnessUtxo)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");e.nonWitnessUtxo=of.inputs.nonWitnessUtxo.decode(n);break;case af.InputTypes.WITNESS_UTXO:if(hf("input",n.key,af.InputTypes.WITNESS_UTXO),void 0!==e.witnessUtxo)throw new Error("Format Error: Input has multiple WITNESS_UTXO");e.witnessUtxo=of.inputs.witnessUtxo.decode(n);break;case af.InputTypes.PARTIAL_SIG:void 0===e.partialSig&&(e.partialSig=[]),e.partialSig.push(of.inputs.partialSig.decode(n));break;case af.InputTypes.SIGHASH_TYPE:if(hf("input",n.key,af.InputTypes.SIGHASH_TYPE),void 0!==e.sighashType)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");e.sighashType=of.inputs.sighashType.decode(n);break;case af.InputTypes.REDEEM_SCRIPT:if(hf("input",n.key,af.InputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");e.redeemScript=of.inputs.redeemScript.decode(n);break;case af.InputTypes.WITNESS_SCRIPT:if(hf("input",n.key,af.InputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");e.witnessScript=of.inputs.witnessScript.decode(n);break;case af.InputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(of.inputs.bip32Derivation.decode(n));break;case af.InputTypes.FINAL_SCRIPTSIG:hf("input",n.key,af.InputTypes.FINAL_SCRIPTSIG),e.finalScriptSig=of.inputs.finalScriptSig.decode(n);break;case af.InputTypes.FINAL_SCRIPTWITNESS:hf("input",n.key,af.InputTypes.FINAL_SCRIPTWITNESS),e.finalScriptWitness=of.inputs.finalScriptWitness.decode(n);break;case af.InputTypes.POR_COMMITMENT:hf("input",n.key,af.InputTypes.POR_COMMITMENT),e.porCommitment=of.inputs.porCommitment.decode(n);break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(n)}a.push(e)}for(const t of sf.range(u)){const e={};for(const r of n[t])switch(of.outputs.checkPubkey(r),r.key[0]){case af.OutputTypes.REDEEM_SCRIPT:if(hf("output",r.key,af.OutputTypes.REDEEM_SCRIPT),void 0!==e.redeemScript)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");e.redeemScript=of.outputs.redeemScript.decode(r);break;case af.OutputTypes.WITNESS_SCRIPT:if(hf("output",r.key,af.OutputTypes.WITNESS_SCRIPT),void 0!==e.witnessScript)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");e.witnessScript=of.outputs.witnessScript.decode(r);break;case af.OutputTypes.BIP32_DERIVATION:void 0===e.bip32Derivation&&(e.bip32Derivation=[]),e.bip32Derivation.push(of.outputs.bip32Derivation.decode(r));break;default:e.unknownKeyVals||(e.unknownKeyVals=[]),e.unknownKeyVals.push(r)}h.push(e)}return{globalMap:i,inputs:a,outputs:h}}hh.psbtFromBuffer=function(t,e){let r=0;function n(){const e=uf.decode(t,r);r+=uf.encodingLength(e);const n=t.slice(r,r+e);return r+=e,n}function i(){return{key:n(),value:n()}}function o(){if(r>=t.length)throw new Error("Format Error: Unexpected End of PSBT");const e=0===t.readUInt8(r);return e&&r++,e}if(1886610036!==function(){const e=t.readUInt32BE(r);return r+=4,e}())throw new Error("Format Error: Invalid Magic Number");if(255!==function(){const e=t.readUInt8(r);return r+=1,e}())throw new Error("Format Error: Magic Number must be followed by 0xff separator");const s=[],u={};for(;!o();){const t=i(),e=t.key.toString("hex");if(u[e])throw new Error("Format Error: Keys must be unique for global keymap: key "+e);u[e]=1,s.push(t)}const a=s.filter((t=>t.key[0]===af.GlobalTypes.UNSIGNED_TX));if(1!==a.length)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const h=e(a[0].value),{inputCount:f,outputCount:c}=h.getInputOutputCounts(),l=[],p=[];for(const t of sf.range(f)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each input: input index "+t+" key "+o);e[o]=1,r.push(n)}l.push(r)}for(const t of sf.range(c)){const e={},r=[];for(;!o();){const n=i(),o=n.key.toString("hex");if(e[o])throw new Error("Format Error: Keys must be unique for each output: output index "+t+" key "+o);e[o]=1,r.push(n)}p.push(r)}return ff(h,{globalMapKeyVals:s,inputKeyVals:l,outputKeyVals:p})},hh.checkKeyBuffer=hf,hh.psbtFromKeyVals=ff;var cf={};Object.defineProperty(cf,"__esModule",{value:!0});const lf=fh,pf=Ph;cf.psbtToBuffer=function({globalMap:t,inputs:e,outputs:r}){const{globalKeyVals:n,inputKeyVals:i,outputKeyVals:o}=mf({globalMap:t,inputs:e,outputs:r}),s=pf.keyValsToBuffer(n),u=t=>0===t.length?[Buffer.from([0])]:t.map(pf.keyValsToBuffer),a=u(i),h=u(o),f=Buffer.allocUnsafe(5);return f.writeUIntBE(482972169471,0,5),Buffer.concat([f,s].concat(a,h))};const df=(t,e)=>t.key.compare(e.key);function gf(t,e){const r=new Set,n=Object.entries(t).reduce(((t,[n,i])=>{if("unknownKeyVals"===n)return t;const o=e[n];if(void 0===o)return t;const s=(Array.isArray(i)?i:[i]).map(o.encode);return s.map((t=>t.key.toString("hex"))).forEach((t=>{if(r.has(t))throw new Error("Serialize Error: Duplicate key: "+t);r.add(t)})),t.concat(s)}),[]),i=t.unknownKeyVals?t.unknownKeyVals.filter((t=>!r.has(t.key.toString("hex")))):[];return n.concat(i).sort(df)}function mf({globalMap:t,inputs:e,outputs:r}){return{globalKeyVals:gf(t,lf.globals),inputKeyVals:e.map((t=>gf(t,lf.inputs))),outputKeyVals:r.map((t=>gf(t,lf.outputs)))}}cf.psbtToKeyVals=mf,function(t){function e(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),e(hh),e(cf)}(ah),Object.defineProperty(uh,"__esModule",{value:!0});const yf=ah;function vf(t,e,r){return n=>{if(t.has(n))return;const i=r.filter((t=>t.key.toString("hex")===n))[0];e.push(i),t.add(n)}}function wf(t){return t.globalMap.unsignedTx}function bf(t){const e=new Set;return t.forEach((t=>{const r=t.key.toString("hex");if(e.has(r))throw new Error("Combine: KeyValue Map keys should be unique");e.add(r)})),e}uh.combine=function(t){const e=t[0],r=yf.psbtToKeyVals(e),n=t.slice(1);if(0===n.length)throw new Error("Combine: Nothing to combine");const i=wf(e);if(void 0===i)throw new Error("Combine: Self missing transaction");const o=bf(r.globalKeyVals),s=r.inputKeyVals.map(bf),u=r.outputKeyVals.map(bf);for(const t of n){const e=wf(t);if(void 0===e||!e.toBuffer().equals(i.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const n=yf.psbtToKeyVals(t);bf(n.globalKeyVals).forEach(vf(o,r.globalKeyVals,n.globalKeyVals));n.inputKeyVals.map(bf).forEach(((t,e)=>t.forEach(vf(s[e],r.inputKeyVals[e],n.inputKeyVals[e]))));n.outputKeyVals.map(bf).forEach(((t,e)=>t.forEach(vf(u[e],r.outputKeyVals[e],n.outputKeyVals[e]))))}return yf.psbtFromKeyVals(i,{globalMapKeyVals:r.globalKeyVals,inputKeyVals:r.inputKeyVals,outputKeyVals:r.outputKeyVals})};var _f={};!function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fh;function r(t,e){const r=t[e];if(void 0===r)throw new Error(`No input #${e}`);return r}function n(t,e,r,n){throw new Error(`Data for ${t} key ${e} is incorrect: Expected ${r} and got ${JSON.stringify(n)}`)}function i(t){return(r,i)=>{for(const o of Object.keys(r)){const s=r[o],{canAdd:u,canAddToArray:a,check:h,expected:f}=e[t+"s"][o]||{},c=!!a;if(h)if(c){if(!Array.isArray(s)||i[o]&&!Array.isArray(i[o]))throw new Error(`Key type ${o} must be an array`);s.every(h)||n(t,o,f,s);const e=i[o]||[],r=new Set;if(!s.every((t=>a(e,t,r))))throw new Error("Can not add duplicate data to array");i[o]=e.concat(s)}else{if(h(s)||n(t,o,f,s),!u(i,s))throw new Error(`Can not add duplicate data to ${t}`);i[o]=s}}}}t.checkForInput=r,t.checkForOutput=function(t,e){const r=t[e];if(void 0===r)throw new Error(`No output #${e}`);return r},t.checkHasKey=function(t,e,r){if(t.key[0]e.key.equals(t.key))).length)throw new Error(`Duplicate Key: ${t.key.toString("hex")}`)},t.getEnumLength=function(t){let e=0;return Object.keys(t).forEach((t=>{Number(isNaN(Number(t)))&&e++})),e},t.inputCheckUncleanFinalized=function(t,e){let r=!1;if(e.nonWitnessUtxo||e.witnessUtxo){const t=!!e.redeemScript,n=!!e.witnessScript,i=!t||!!e.finalScriptSig,o=!n||!!e.finalScriptWitness,s=!!e.finalScriptSig||!!e.finalScriptWitness;r=i&&o&&s}if(!1===r)throw new Error(`Input #${t} has too much or too little data to clean`)},t.updateGlobal=i("global"),t.updateInput=i("input"),t.updateOutput=i("output"),t.addInputAttributes=function(e,n){const i=r(e,e.length-1);t.updateInput(n,i)},t.addOutputAttributes=function(e,n){const i=r(e,e.length-1);t.updateOutput(n,i)},t.defaultVersionSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Version: Invalid Transaction");return e.writeUInt32LE(t,0),e},t.defaultLocktimeSetter=function(t,e){if(!Buffer.isBuffer(e)||e.length<4)throw new Error("Set Locktime: Invalid Transaction");return e.writeUInt32LE(t,e.length-4),e}}(_f),Object.defineProperty(sh,"__esModule",{value:!0});const Ef=uh,Sf=ah,If=ch,Mf=_f;sh.Psbt=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,e){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e){const r=Sf.psbtFromBuffer(t,e),n=new this(r.globalMap.unsignedTx);return Object.assign(n,r),n}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return Sf.psbtToBuffer(this)}updateGlobal(t){return Mf.updateGlobal(t,this.globalMap),this}updateInput(t,e){const r=Mf.checkForInput(this.inputs,t);return Mf.updateInput(e,r),this}updateOutput(t,e){const r=Mf.checkForOutput(this.outputs,t);return Mf.updateOutput(e,r),this}addUnknownKeyValToGlobal(t){return Mf.checkHasKey(t,this.globalMap.unknownKeyVals,Mf.getEnumLength(If.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,e){const r=Mf.checkForInput(this.inputs,t);return Mf.checkHasKey(e,r.unknownKeyVals,Mf.getEnumLength(If.InputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addUnknownKeyValToOutput(t,e){const r=Mf.checkForOutput(this.outputs,t);return Mf.checkHasKey(e,r.unknownKeyVals,Mf.getEnumLength(If.OutputTypes)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(e),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Mf.addInputAttributes(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const e=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(e))throw new Error("unknownKeyVals must be an Array");return e.forEach((t=>this.addUnknownKeyValToInput(r,t))),Mf.addOutputAttributes(this.outputs,t),this}clearFinalizedInput(t){const e=Mf.checkForInput(this.inputs,t);Mf.inputCheckUncleanFinalized(t,e);for(const t of Object.keys(e))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(t)||delete e[t];return this}combine(...t){const e=Ef.combine([this].concat(t));return Object.assign(this,e),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}},Object.defineProperty(oh,"__esModule",{value:!0});const Tf=sh,Of=kh,Af=_f,Pf=es,kf=_a,Rf=Js,Nf=ha,xf=ns,Bf=os,Lf=Na,Uf={network:rs.bitcoin,maximumFeeRate:5e3};class Cf{constructor(t={},e=new Tf.Psbt(new Hf)){this.data=e,this.opts=Object.assign({},Uf,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},0===this.data.inputs.length&&this.setVersion(2);const r=(t,e,r,n)=>Object.defineProperty(t,e,{enumerable:r,writable:n});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}static fromBase64(t,e={}){const r=Buffer.from(t,"base64");return this.fromBuffer(r,e)}static fromHex(t,e={}){const r=Buffer.from(t,"hex");return this.fromBuffer(r,e)}static fromBuffer(t,e={}){const r=Tf.Psbt.fromBuffer(t,Df),n=new Cf(e,r);return function(t,e){t.ins.forEach((t=>{tc(e,t)}))}(n.__CACHE.__TX,n.__CACHE),n}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map((t=>({hash:kf.cloneBuffer(t.hash),index:t.index,sequence:t.sequence})))}get txOutputs(){return this.__CACHE.__TX.outs.map((t=>{let e;try{e=Pf.fromOutputScript(t.script,this.opts.network)}catch(t){}return{script:kf.cloneBuffer(t.script),value:t.value,address:e}}))}combine(...t){return this.data.combine(...t.map((t=>t.data))),this}clone(){const t=Cf.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Jf(t),this.opts.maximumFeeRate=t}setVersion(t){Jf(t),Zf(this.data.inputs,"setVersion");const e=this.__CACHE;return e.__TX.version=t,e.__EXTRACTED_TX=void 0,this}setLocktime(t){Jf(t),Zf(this.data.inputs,"setLocktime");const e=this.__CACHE;return e.__TX.locktime=t,e.__EXTRACTED_TX=void 0,this}setInputSequence(t,e){Jf(e),Zf(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=e,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach((t=>this.addInput(t))),this}addInput(t){if(arguments.length>1||!t||void 0===t.hash||void 0===t.index)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Zf(this.data.inputs,"addInput"),t.witnessScript&&yc(t.witnessScript);const e=this.__CACHE;this.data.addInput(t);tc(e,e.__TX.ins[e.__TX.ins.length-1]);const r=this.data.inputs.length-1,n=this.data.inputs[r];return n.nonWitnessUtxo&&cc(this.__CACHE,n,r),e.__FEE=void 0,e.__FEE_RATE=void 0,e.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach((t=>this.addOutput(t))),this}addOutput(t){if(arguments.length>1||!t||void 0===t.value||void 0===t.address&&void 0===t.script)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Zf(this.data.inputs,"addOutput");const{address:e}=t;if("string"==typeof e){const{network:r}=this.opts,n=Pf.toOutputScript(e,r);t=Object.assign(t,{script:n})}const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(qf))throw new Error("Not finalized");const e=this.__CACHE;if(t||function(t,e,r){const n=e.__FEE_RATE||t.getFeeRate(),i=e.__EXTRACTED_TX.virtualSize(),o=n*i;if(n>=r.maximumFeeRate)throw new Error(`Warning: You are paying around ${(o/1e8).toFixed(8)} in fees, which is ${n} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}(this,e,this.opts),e.__EXTRACTED_TX)return e.__EXTRACTED_TX;const r=e.__TX.clone();return lc(this.data.inputs,r,e,!0),r}getFeeRate(){return ic("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return ic("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Af.checkForInput(this.data.inputs,0),bc(this.data.inputs.length).forEach((t=>this.finalizeInput(t))),this}finalizeInput(t,e=oc){const r=Af.checkForInput(this.data.inputs,t),{script:n,isP2SH:i,isP2WSH:o,isSegwit:s}=function(t,e,r){const n=r.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!e.redeemScript,i.isP2WSH=!!e.witnessScript,e.witnessScript)i.script=e.witnessScript;else if(e.redeemScript)i.script=e.redeemScript;else if(e.nonWitnessUtxo){const o=pc(r,e,t),s=n.ins[t].index;i.script=o.outs[s].script}else e.witnessUtxo&&(i.script=e.witnessUtxo.script);(e.witnessScript||$f(i.script))&&(i.isSegwit=!0);return i}(t,r,this.__CACHE);if(!n)throw new Error(`No script found for input #${t}`);!function(t){if(!t.sighashType||!t.partialSig)return;const{partialSig:e,sighashType:r}=t;e.forEach((t=>{const{hashType:e}=Bf.signature.decode(t.signature);if(r!==e)throw new Error("Signature sighash does not match input sighash type")}))}(r);const{finalScriptSig:u,finalScriptWitness:a}=e(t,r,n,s,i,o);if(u&&this.data.updateInput(t,{finalScriptSig:u}),a&&this.data.updateInput(t,{finalScriptWitness:a}),!u&&!a)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}getInputType(t){const e=Af.checkForInput(this.data.inputs,t),r=mc(dc(t,e,this.__CACHE),t,"input",e.redeemScript||function(t){if(!t)return;const e=Bf.decompile(t);if(!e)return;const r=e[e.length-1];if(!Buffer.isBuffer(r)||gc(r)||(n=r,Bf.isCanonicalScriptSignature(n)))return;var n;if(!Bf.decompile(r))return;return r}(e.finalScriptSig),e.witnessScript||function(t){if(!t)return;const e=hc(t),r=e[e.length-1];if(gc(r))return;if(!Bf.decompile(r))return;return r}(e.finalScriptWitness));return("raw"===r.type?"":r.type+"-")+wc(r.meaningfulScript)}inputHasPubkey(t,e){return function(t,e,r,n){const i=dc(r,e,n),{meaningfulScript:o}=mc(i,r,"input",e.redeemScript,e.witnessScript);return vc(t,o)}(e,Af.checkForInput(this.data.inputs,t),t,this.__CACHE)}inputHasHDKey(t,e){const r=Af.checkForInput(this.data.inputs,t),n=Yf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}outputHasPubkey(t,e){return function(t,e,r,n){const i=n.__TX.outs[r].script,{meaningfulScript:o}=mc(i,r,"output",e.redeemScript,e.witnessScript);return vc(t,o)}(e,Af.checkForOutput(this.data.outputs,t),t,this.__CACHE)}outputHasHDKey(t,e){const r=Af.checkForOutput(this.data.outputs,t),n=Yf(e);return!!r.bip32Derivation&&r.bip32Derivation.some(n)}validateSignaturesOfAllInputs(){Af.checkForInput(this.data.inputs,0);return bc(this.data.inputs.length).map((t=>this.validateSignaturesOfInput(t))).reduce(((t,e)=>!0===e&&t),!0)}validateSignaturesOfInput(t,e){const r=this.data.inputs[t],n=(r||{}).partialSig;if(!r||!n||n.length<1)throw new Error("No signatures to validate");const i=e?n.filter((t=>t.pubkey.equals(e))):n;if(i.length<1)throw new Error("No signatures for this pubkey");const o=[];let s,u,a;for(const e of i){const n=Bf.signature.decode(e.signature),{hash:i,script:h}=a!==n.hashType?uc(t,Object.assign({},r,{sighashType:n.hashType}),this.__CACHE,!0):{hash:s,script:u};a=n.hashType,s=i,u=h,Qf(e.pubkey,h,"verify");const f=Nf.fromPublicKey(e.pubkey);o.push(f.verify(i,n.signature))}return o.every((t=>!0===t))}signAllInputsHD(t,e=[Lf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const n of bc(this.data.inputs.length))try{this.signInputHD(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,e=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey||!t.fingerprint)return n(new Error("Need HDSigner to sign input"));const i=[],o=[];for(const r of bc(this.data.inputs.length))o.push(this.signInputHDAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInputHD(t,e,r=[Lf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey||!e.fingerprint)throw new Error("Need HDSigner to sign input");return ac(t,this.data.inputs,e).forEach((e=>this.signInput(t,e,r))),this}signInputHDAsync(t,e,r=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((n,i)=>{if(!e||!e.publicKey||!e.fingerprint)return i(new Error("Need HDSigner to sign input"));const o=ac(t,this.data.inputs,e).map((e=>this.signInputAsync(t,e,r)));return Promise.all(o).then((()=>{n()})).catch(i)}))}signAllInputs(t,e=[Lf.Transaction.SIGHASH_ALL]){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const n of bc(this.data.inputs.length))try{this.signInput(n,t,e),r.push(!0)}catch(t){r.push(!1)}if(r.every((t=>!1===t)))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,e=[Lf.Transaction.SIGHASH_ALL]){return new Promise(((r,n)=>{if(!t||!t.publicKey)return n(new Error("Need Signer to sign input"));const i=[],o=[];for(const[r]of this.data.inputs.entries())o.push(this.signInputAsync(r,t,e).then((()=>{i.push(!0)}),(()=>{i.push(!1)})));return Promise.all(o).then((()=>{if(i.every((t=>!1===t)))return n(new Error("No inputs were signed"));r()}))}))}signInput(t,e,r=[Lf.Transaction.SIGHASH_ALL]){if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=sc(this.data.inputs,t,e.publicKey,this.__CACHE,r),o=[{pubkey:e.publicKey,signature:Bf.signature.encode(e.sign(n),i)}];return this.data.updateInput(t,{partialSig:o}),this}signInputAsync(t,e,r=[Lf.Transaction.SIGHASH_ALL]){return Promise.resolve().then((()=>{if(!e||!e.publicKey)throw new Error("Need Signer to sign input");const{hash:n,sighashType:i}=sc(this.data.inputs,t,e.publicKey,this.__CACHE,r);return Promise.resolve(e.sign(n)).then((r=>{const n=[{pubkey:e.publicKey,signature:Bf.signature.encode(r,i)}];this.data.updateInput(t,{partialSig:n})}))}))}toBuffer(){return Ff(this.__CACHE),this.data.toBuffer()}toHex(){return Ff(this.__CACHE),this.data.toHex()}toBase64(){return Ff(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,e){return e.witnessScript&&yc(e.witnessScript),this.data.updateInput(t,e),e.nonWitnessUtxo&&cc(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,e){return this.data.updateOutput(t,e),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,e){return this.data.addUnknownKeyValToInput(t,e),this}addUnknownKeyValToOutput(t,e){return this.data.addUnknownKeyValToOutput(t,e),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}oh.Psbt=Cf;const Df=t=>new Hf(t);class Hf{constructor(t=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=Lf.Transaction.fromBuffer(t),function(t){const e=t.ins.every((t=>t.script&&0===t.script.length&&t.witness&&0===t.witness.length));if(!e)throw new Error("Format Error: Transaction ScriptSigs are not empty")}(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(void 0===t.hash||void 0===t.index||!Buffer.isBuffer(t.hash)&&"string"!=typeof t.hash||"number"!=typeof t.index)throw new Error("Error adding input.");const e="string"==typeof t.hash?kf.reverseBuffer(Buffer.from(t.hash,"hex")):t.hash;this.tx.addInput(e,t.index,t.sequence)}addOutput(t){if(void 0===t.script||void 0===t.value||!Buffer.isBuffer(t.script)||"number"!=typeof t.value)throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function Ff(t){if(!1!==t.__UNSAFE_SIGN_NONSEGWIT)throw new Error("Not BIP174 compliant, can not export")}function jf(t,e,r){if(!e)return!1;let n;if(n=r?r.map((t=>{const r=Nf.fromPublicKey(t,{compressed:!0}).publicKey;return e.find((t=>t.pubkey.equals(r)))})).filter((t=>!!t)):e,n.length>t)throw new Error("Too many signatures");return n.length===t}function qf(t){return!!t.finalScriptSig||!!t.finalScriptWitness}function Gf(t){return e=>{try{return t({output:e}),!0}catch(t){return!1}}}const Kf=Gf(xf.p2ms),Wf=Gf(xf.p2pk),Vf=Gf(xf.p2pkh),$f=Gf(xf.p2wpkh),zf=Gf(xf.p2wsh),Xf=Gf(xf.p2sh);function Yf(t){return e=>!!e.masterFingerprint.equals(t.fingerprint)&&!!t.derivePath(e.path).publicKey.equals(e.pubkey)}function Jf(t){if("number"!=typeof t||t!==Math.floor(t)||t>4294967295||t<0)throw new Error("Invalid 32 bit integer")}function Zf(t,e){t.forEach((t=>{let r=!1,n=[];if(0===(t.partialSig||[]).length){if(!t.finalScriptSig&&!t.finalScriptWitness)return;n=function(t){const e=t.finalScriptSig&&Bf.decompile(t.finalScriptSig)||[],r=t.finalScriptWitness&&Bf.decompile(t.finalScriptWitness)||[];return e.concat(r).filter((t=>Buffer.isBuffer(t)&&Bf.isCanonicalScriptSignature(t))).map((t=>({signature:t})))}(t)}else n=t.partialSig;if(n.forEach((t=>{const{hashType:n}=Bf.signature.decode(t.signature),i=[];n&Lf.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput");switch(31&n){case Lf.Transaction.SIGHASH_ALL:break;case Lf.Transaction.SIGHASH_SINGLE:case Lf.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence")}-1===i.indexOf(e)&&(r=!0)})),r)throw new Error("Can not modify transaction, signatures exist.")}))}function Qf(t,e,r){if(!vc(t,e))throw new Error(`Can not ${r} for this input with the key ${t.toString("hex")}`)}function tc(t,e){const r=kf.reverseBuffer(Buffer.from(e.hash)).toString("hex")+":"+e.index;if(t.__TX_IN_CACHE[r])throw new Error("Duplicate input detected.");t.__TX_IN_CACHE[r]=1}function ec(t,e){return(r,n,i,o)=>{const s=t({redeem:{output:i}}).output;if(!n.equals(s))throw new Error(`${e} for ${o} #${r} doesn't match the scriptPubKey in the prevout`)}}const rc=ec(xf.p2sh,"Redeem script"),nc=ec(xf.p2wsh,"Witness script");function ic(t,e,r,n){if(!r.every(qf))throw new Error(`PSBT must be finalized to calculate ${e}`);if("__FEE_RATE"===t&&n.__FEE_RATE)return n.__FEE_RATE;if("__FEE"===t&&n.__FEE)return n.__FEE;let i,o=!0;return n.__EXTRACTED_TX?(i=n.__EXTRACTED_TX,o=!1):i=n.__TX.clone(),lc(r,i,n,o),"__FEE_RATE"===t?n.__FEE_RATE:"__FEE"===t?n.__FEE:void 0}function oc(t,e,r,n,i,o){const s=wc(r);if(!function(t,e,r){switch(r){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return jf(1,t.partialSig);case"multisig":const r=xf.p2ms({output:e});return jf(r.m,t.partialSig,r.pubkeys);default:return!1}}(e,r,s))throw new Error(`Can not finalize input #${t}`);return function(t,e,r,n,i,o){let s,u;const a=function(t,e,r){let n;switch(e){case"multisig":const e=function(t,e){return xf.p2ms({output:t}).pubkeys.map((t=>(e.filter((e=>e.pubkey.equals(t)))[0]||{}).signature)).filter((t=>!!t))}(t,r);n=xf.p2ms({output:t,signatures:e});break;case"pubkey":n=xf.p2pk({output:t,signature:r[0].signature});break;case"pubkeyhash":n=xf.p2pkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature});break;case"witnesspubkeyhash":n=xf.p2wpkh({output:t,pubkey:r[0].pubkey,signature:r[0].signature})}return n}(t,e,r),h=o?xf.p2wsh({redeem:a}):null,f=i?xf.p2sh({redeem:h||a}):null;n?(u=fc(h?h.witness:a.witness),f&&(s=f.input)):s=f?f.input:a.input;return{finalScriptSig:s,finalScriptWitness:u}}(r,s,e.partialSig,n,i,o)}function sc(t,e,r,n,i){const o=Af.checkForInput(t,e),{hash:s,sighashType:u,script:a}=uc(e,o,n,!1,i);return Qf(r,a,"sign"),{hash:s,sighashType:u}}function uc(t,e,r,n,i){const o=r.__TX,s=e.sighashType||Lf.Transaction.SIGHASH_ALL;if(i&&i.indexOf(s)<0){const t=function(t){let e=t&Lf.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(31&t){case Lf.Transaction.SIGHASH_ALL:e+="SIGHASH_ALL";break;case Lf.Transaction.SIGHASH_SINGLE:e+="SIGHASH_SINGLE";break;case Lf.Transaction.SIGHASH_NONE:e+="SIGHASH_NONE"}return e}(s);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${t}`)}let u,a;if(e.nonWitnessUtxo){const n=pc(r,e,t),i=o.ins[t].hash,s=n.getHash();if(!i.equals(s))throw new Error(`Non-witness UTXO hash for input #${t} doesn't match the hash specified in the prevout`);const u=o.ins[t].index;a=n.outs[u]}else{if(!e.witnessUtxo)throw new Error("Need a Utxo input item for signing");a=e.witnessUtxo}const{meaningfulScript:h,type:f}=mc(a.script,t,"input",e.redeemScript,e.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)u=o.hashForWitnessV0(t,h,a.value,s);else if($f(h)){const e=xf.p2pkh({hash:h.slice(2)}).output;u=o.hashForWitnessV0(t,e,a.value,s)}else{if(void 0===e.nonWitnessUtxo&&!1===r.__UNSAFE_SIGN_NONSEGWIT)throw new Error(`Input #${t} has witnessUtxo but non-segwit script: ${h.toString("hex")}`);n||!1===r.__UNSAFE_SIGN_NONSEGWIT||console.warn("Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as the old TransactionBuilder class when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n*********************"),u=o.hashForSignature(t,h,s)}return{script:h,sighashType:s,hash:u}}function ac(t,e,r){const n=Af.checkForInput(e,t);if(!n.bip32Derivation||0===n.bip32Derivation.length)throw new Error("Need bip32Derivation to sign with HD");const i=n.bip32Derivation.map((t=>t.masterFingerprint.equals(r.fingerprint)?t:void 0)).filter((t=>!!t));if(0===i.length)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");const o=i.map((t=>{const e=r.derivePath(t.path);if(!t.pubkey.equals(e.publicKey))throw new Error("pubkey did not match bip32Derivation");return e}));return o}function hc(t){let e=0;function r(){const r=Of.decode(t,e);return e+=Of.decode.bytes,r}function n(){return function(r){return e+=r,t.slice(e-r,e)}(r())}return function(){const t=r(),e=[];for(let r=0;r{if(n&&t.finalScriptSig&&(e.ins[o].script=t.finalScriptSig),n&&t.finalScriptWitness&&(e.ins[o].witness=hc(t.finalScriptWitness)),t.witnessUtxo)i+=t.witnessUtxo.value;else if(t.nonWitnessUtxo){const n=pc(r,t,o),s=e.ins[o].index,u=n.outs[s];i+=u.value}}));const o=e.outs.reduce(((t,e)=>t+e.value),0),s=i-o;if(s<0)throw new Error("Outputs are spending more than Inputs");const u=e.virtualSize();r.__FEE=s,r.__EXTRACTED_TX=e,r.__FEE_RATE=Math.floor(s/u)}function pc(t,e,r){const n=t.__NON_WITNESS_UTXO_TX_CACHE;return n[r]||cc(t,e,r),n[r]}function dc(t,e,r){if(void 0!==e.witnessUtxo)return e.witnessUtxo.script;if(void 0!==e.nonWitnessUtxo){return pc(r,e,t).outs[r.__TX.ins[t].index].script}throw new Error("Can't find pubkey in input without Utxo data")}function gc(t){return 33===t.length&&Bf.isCanonicalPubKey(t)}function mc(t,e,r,n,i){const o=Xf(t),s=o&&n&&zf(n),u=zf(t);if(o&&void 0===n)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((u||s)&&void 0===i)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return s?(a=i,rc(e,t,n,r),nc(e,n,i,r),yc(a)):u?(a=i,nc(e,t,i,r),yc(a)):o?(a=n,rc(e,t,n,r)):a=t,{meaningfulScript:a,type:s?"p2sh-p2wsh":o?"p2sh":u?"p2wsh":"raw"}}function yc(t){if($f(t)||Xf(t))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function vc(t,e){const r=Rf.hash160(t),n=Bf.decompile(e);if(null===n)throw new Error("Unknown script error");return n.some((e=>"number"!=typeof e&&(e.equals(t)||e.equals(r))))}function wc(t){return $f(t)?"witnesspubkeyhash":Vf(t)?"pubkeyhash":Kf(t)?"multisig":Wf(t)?"pubkey":"nonstandard"}function bc(t){return[...Array(t).keys()]}var _c={},Ec={},Sc={},Ic={};Object.defineProperty(Ic,"__esModule",{value:!0});const Mc=os,Tc=os;function Oc(t){return t===Tc.OPS.OP_0||Mc.isCanonicalScriptSignature(t)}function Ac(t,e){const r=Mc.decompile(t);return!(r.length<2)&&(r[0]===Tc.OPS.OP_0&&(e?r.slice(1).every(Oc):r.slice(1).every(Mc.isCanonicalScriptSignature)))}Ic.check=Ac,Ac.toJSON=()=>"multisig input";var Pc={};Object.defineProperty(Pc,"__esModule",{value:!0});const kc=os,Rc=os,Nc=as,xc=Rc.OPS.OP_RESERVED;function Bc(t,e){const r=kc.decompile(t);if(r.length<4)return!1;if(r[r.length-1]!==Rc.OPS.OP_CHECKMULTISIG)return!1;if(!Nc.Number(r[0]))return!1;if(!Nc.Number(r[r.length-2]))return!1;const n=r[0]-xc,i=r[r.length-2]-xc;if(n<=0)return!1;if(i>16)return!1;if(n>i)return!1;if(i!==r.length-3)return!1;if(e)return!0;return r.slice(1,-2).every(kc.isCanonicalPubKey)}Pc.check=Bc,Bc.toJSON=()=>"multi-sig output",Object.defineProperty(Sc,"__esModule",{value:!0});const Lc=Ic;Sc.input=Lc;const Uc=Pc;Sc.output=Uc;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const Dc=os,Hc=Dc.OPS;function Fc(t){const e=Dc.compile(t);return e.length>1&&e[0]===Hc.OP_RETURN}Cc.check=Fc,Fc.toJSON=()=>"null data output";const jc={check:Fc};Cc.output=jc;var qc={},Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});const Kc=os;function Wc(t){const e=Kc.decompile(t);return 1===e.length&&Kc.isCanonicalScriptSignature(e[0])}Gc.check=Wc,Wc.toJSON=()=>"pubKey input";var Vc={};Object.defineProperty(Vc,"__esModule",{value:!0});const $c=os,zc=os;function Xc(t){const e=$c.decompile(t);return 2===e.length&&$c.isCanonicalPubKey(e[0])&&e[1]===zc.OPS.OP_CHECKSIG}Vc.check=Xc,Xc.toJSON=()=>"pubKey output",Object.defineProperty(qc,"__esModule",{value:!0});const Yc=Gc;qc.input=Yc;const Jc=Vc;qc.output=Jc;var Zc={},Qc={};Object.defineProperty(Qc,"__esModule",{value:!0});const tl=os;function el(t){const e=tl.decompile(t);return 2===e.length&&tl.isCanonicalScriptSignature(e[0])&&tl.isCanonicalPubKey(e[1])}Qc.check=el,el.toJSON=()=>"pubKeyHash input";var rl={};Object.defineProperty(rl,"__esModule",{value:!0});const nl=os,il=os;function ol(t){const e=nl.compile(t);return 25===e.length&&e[0]===il.OPS.OP_DUP&&e[1]===il.OPS.OP_HASH160&&20===e[2]&&e[23]===il.OPS.OP_EQUALVERIFY&&e[24]===il.OPS.OP_CHECKSIG}rl.check=ol,ol.toJSON=()=>"pubKeyHash output",Object.defineProperty(Zc,"__esModule",{value:!0});const sl=Qc;Zc.input=sl;const ul=rl;Zc.output=ul;var al={},hl={},fl={};Object.defineProperty(fl,"__esModule",{value:!0});const cl=os,ll=os;function pl(t){const e=cl.compile(t);return 22===e.length&&e[0]===ll.OPS.OP_0&&20===e[1]}fl.check=pl,pl.toJSON=()=>"Witness pubKeyHash output";var dl={};Object.defineProperty(dl,"__esModule",{value:!0});const gl=os,ml=os;function yl(t){const e=gl.compile(t);return 34===e.length&&e[0]===ml.OPS.OP_0&&32===e[1]}dl.check=yl,yl.toJSON=()=>"Witness scriptHash output",Object.defineProperty(hl,"__esModule",{value:!0});const vl=os,wl=Sc,bl=qc,_l=Zc,El=fl,Sl=dl;function Il(t,e){const r=vl.decompile(t);if(r.length<1)return!1;const n=r[r.length-1];if(!Buffer.isBuffer(n))return!1;const i=vl.decompile(vl.compile(r.slice(0,-1))),o=vl.decompile(n);return!!o&&(!!vl.isPushOnly(i)&&(1===r.length?Sl.check(o)||El.check(o):!(!_l.input.check(i)||!_l.output.check(o))||(!(!wl.input.check(i,e)||!wl.output.check(o))||!(!bl.input.check(i)||!bl.output.check(o)))))}hl.check=Il,Il.toJSON=()=>"scriptHash input";var Ml={};Object.defineProperty(Ml,"__esModule",{value:!0});const Tl=os,Ol=os;function Al(t){const e=Tl.compile(t);return 23===e.length&&e[0]===Ol.OPS.OP_HASH160&&20===e[1]&&e[22]===Ol.OPS.OP_EQUAL}Ml.check=Al,Al.toJSON=()=>"scriptHash output",Object.defineProperty(al,"__esModule",{value:!0});const Pl=hl;al.input=Pl;const kl=Ml;al.output=kl;var Rl={},Nl={};Object.defineProperty(Nl,"__esModule",{value:!0});const xl=os,Bl=os,Ll=as,Ul=xo,Cl=Buffer.from("aa21a9ed","hex");function Dl(t){const e=xl.compile(t);return e.length>37&&e[0]===Bl.OPS.OP_RETURN&&36===e[1]&&e.slice(2,6).equals(Cl)}Nl.check=Dl,Dl.toJSON=()=>"Witness commitment output",Nl.encode=function(t){Ul(Ll.Hash256bit,t);const e=Buffer.allocUnsafe(36);return Cl.copy(e,0),t.copy(e,4),xl.compile([Bl.OPS.OP_RETURN,e])},Nl.decode=function(t){return Ul(Dl,t),xl.decompile(t)[1].slice(4,36)},Object.defineProperty(Rl,"__esModule",{value:!0});const Hl=Nl;Rl.output=Hl;var Fl={},jl={};Object.defineProperty(jl,"__esModule",{value:!0});const ql=os;function Gl(t){const e=ql.decompile(t);return 2===e.length&&ql.isCanonicalScriptSignature(e[0])&&function(t){return ql.isCanonicalPubKey(t)&&33===t.length}(e[1])}jl.check=Gl,Gl.toJSON=()=>"witnessPubKeyHash input",Object.defineProperty(Fl,"__esModule",{value:!0});const Kl=jl;Fl.input=Kl;const Wl=fl;Fl.output=Wl;var Vl={},$l={};Object.defineProperty($l,"__esModule",{value:!0});const zl=os,Xl=xo,Yl=Sc,Jl=qc,Zl=Zc;function Ql(t,e){if(Xl(Xl.Array,t),t.length<1)return!1;const r=t[t.length-1];if(!Buffer.isBuffer(r))return!1;const n=zl.decompile(r);if(!n||0===n.length)return!1;const i=zl.compile(t.slice(0,-1));return!(!Zl.input.check(i)||!Zl.output.check(n))||(!(!Yl.input.check(i,e)||!Yl.output.check(n))||!(!Jl.input.check(i)||!Jl.output.check(n)))}$l.check=Ql,Ql.toJSON=()=>"witnessScriptHash input",Object.defineProperty(Vl,"__esModule",{value:!0});const tp=$l;Vl.input=tp;const ep=dl;Vl.output=ep,Object.defineProperty(Ec,"__esModule",{value:!0});const rp=os,np=Sc,ip=Cc,op=qc,sp=Zc,up=al,ap=Rl,hp=Fl,fp=Vl,cp={P2MS:"multisig",NONSTANDARD:"nonstandard",NULLDATA:"nulldata",P2PK:"pubkey",P2PKH:"pubkeyhash",P2SH:"scripthash",P2WPKH:"witnesspubkeyhash",P2WSH:"witnessscripthash",WITNESS_COMMITMENT:"witnesscommitment"};Ec.types=cp,Ec.output=function(t){if(hp.output.check(t))return cp.P2WPKH;if(fp.output.check(t))return cp.P2WSH;if(sp.output.check(t))return cp.P2PKH;if(up.output.check(t))return cp.P2SH;const e=rp.decompile(t);if(!e)throw new TypeError("Invalid script");return np.output.check(e)?cp.P2MS:op.output.check(e)?cp.P2PK:ap.output.check(e)?cp.WITNESS_COMMITMENT:ip.output.check(e)?cp.NULLDATA:cp.NONSTANDARD},Ec.input=function(t,e){const r=rp.decompile(t);if(!r)throw new TypeError("Invalid script");return sp.input.check(r)?cp.P2PKH:up.input.check(r,e)?cp.P2SH:np.input.check(r,e)?cp.P2MS:op.input.check(r)?cp.P2PK:cp.NONSTANDARD},Ec.witness=function(t,e){const r=rp.decompile(t);if(!r)throw new TypeError("Invalid script");return hp.input.check(r)?cp.P2WPKH:fp.input.check(r,e)?cp.P2WSH:cp.NONSTANDARD},Object.defineProperty(_c,"__esModule",{value:!0});const lp=es,pp=_a,dp=Ec,gp=Js,mp=ha,yp=rs,vp=ns,wp=os,bp=os,_p=Na,Ep=as,Sp=xo,Ip=dp.types,Mp=new Set(["p2pkh","p2pk","p2wpkh","p2ms","p2sh-p2pkh","p2sh-p2pk","p2sh-p2wpkh","p2sh-p2ms","p2wsh-p2pkh","p2wsh-p2pk","p2wsh-p2ms","p2sh-p2wsh-p2pkh","p2sh-p2wsh-p2pk","p2sh-p2wsh-p2ms"]);function Tp(t,e,r){try{Sp(t,e)}catch(t){throw new Error(r)}}class Op{constructor(t=yp.bitcoin,e=2500){this.network=t,this.maximumFeeRate=e,this.__PREV_TX_SET={},this.__INPUTS=[],this.__TX=new _p.Transaction,this.__TX.version=2,this.__USE_LOW_R=!1,console.warn("Deprecation Warning: TransactionBuilder will be removed in the future. (v6.x.x or later) Please use the Psbt class instead. Examples of usage are available in the transactions-psbt.js integration test file on our Github. A high level explanation is available in the psbt.ts and psbt.js files as well.")}static fromTransaction(t,e){const r=new Op(e);return r.setVersion(t.version),r.setLockTime(t.locktime),t.outs.forEach((t=>{r.addOutput(t.script,t.value)})),t.ins.forEach((t=>{r.__addInputUnsafe(t.hash,t.index,{sequence:t.sequence,script:t.script,witness:t.witness})})),r.__INPUTS.forEach(((e,r)=>{!function(t,e,r){if(t.redeemScriptType!==Ip.P2MS||!t.redeemScript)return;if(t.pubkeys.length===t.signatures.length)return;const n=t.signatures.concat();t.signatures=t.pubkeys.map((i=>{const o=mp.fromPublicKey(i);let s;return n.some(((i,u)=>{if(!i)return!1;const a=wp.signature.decode(i),h=e.hashForSignature(r,t.redeemScript,a.hashType);return!!o.verify(h,a.signature)&&(n[u]=void 0,s=i,!0)})),s}))}(e,t,r)})),r}setLowR(t){return Sp(Sp.maybe(Sp.Boolean),t),void 0===t&&(t=!0),this.__USE_LOW_R=t,t}setLockTime(t){if(Sp(Ep.UInt32,t),this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>void 0!==t)))))throw new Error("No, this would invalidate signatures");this.__TX.locktime=t}setVersion(t){Sp(Ep.UInt32,t),this.__TX.version=t}addInput(t,e,r,n){if(!this.__canModifyInputs())throw new Error("No, this would invalidate signatures");let i;if("string"==typeof(o=t)||o instanceof String)t=pp.reverseBuffer(Buffer.from(t,"hex"));else if(function(t){return t instanceof _p.Transaction}(t)){const r=t.outs[e];n=r.script,i=r.value,t=t.getHash(!1)}var o;return this.__addInputUnsafe(t,e,{sequence:r,prevOutScript:n,value:i})}addOutput(t,e){if(!this.__canModifyOutputs())throw new Error("No, this would invalidate signatures");return"string"==typeof t&&(t=lp.toOutputScript(t,this.network)),this.__TX.addOutput(t,e)}build(){return this.__build(!1)}buildIncomplete(){return this.__build(!0)}sign(t,e,r,n,i,o){!function({input:t,ourPubKey:e,keyPair:r,signatureHash:n,hashType:i,useLowR:o}){let s=!1;for(const[u,a]of t.pubkeys.entries()){if(!e.equals(a))continue;if(t.signatures[u])throw new Error("Signature already exists");if(33!==e.length&&t.hasWitness)throw new Error("BIP143 rejects uncompressed public keys in P2WPKH or P2WSH");const h=r.sign(n,o);t.signatures[u]=wp.signature.encode(h,i),s=!0}if(!s)throw new Error("Key pair cannot sign for this input")}(function(t,e,r,n,i,o,s,u,a,h,f){let c;if("number"==typeof i)console.warn("DEPRECATED: TransactionBuilder sign method arguments will change in v6, please use the TxbSignArg interface"),c=i;else{if("object"!=typeof i)throw new TypeError("TransactionBuilder sign first arg must be TxbSignArg or number");!function(t,e){if(!Mp.has(e.prevOutScriptType))throw new TypeError(`Unknown prevOutScriptType "${e.prevOutScriptType}"`);Tp(Sp.Number,e.vin,"sign must include vin parameter as Number (input index)"),Tp(Ep.Signer,e.keyPair,"sign must include keyPair parameter as Signer interface"),Tp(Sp.maybe(Sp.Number),e.hashType,"sign hashType parameter must be a number");const r=(t[e.vin]||[]).prevOutType,n=e.prevOutScriptType;switch(n){case"p2pkh":if(r&&"pubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2pkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2pk":if(r&&"pubkey"!==r)throw new TypeError(`input #${e.vin} is not of type p2pk: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wpkh":if(r&&"witnesspubkeyhash"!==r)throw new TypeError(`input #${e.vin} is not of type p2wpkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2ms":if(r&&"multisig"!==r)throw new TypeError(`input #${e.vin} is not of type p2ms: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2sh-p2wpkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type p2sh-p2wpkh: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2ms":case"p2sh-p2pk":case"p2sh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.value(void 0),e.witnessScript,`${n} requires NO witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires redeemScript`),Tp(Sp.value(void 0),e.witnessValue,`${n} requires NO witnessValue`);break;case"p2wsh-p2ms":case"p2wsh-p2pk":case"p2wsh-p2pkh":if(r&&"witnessscripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.Buffer,e.witnessScript,`${n} requires witnessScript`),Tp(Sp.value(void 0),e.redeemScript,`${n} requires NO redeemScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessValue`);break;case"p2sh-p2wsh-p2ms":case"p2sh-p2wsh-p2pk":case"p2sh-p2wsh-p2pkh":if(r&&"scripthash"!==r)throw new TypeError(`input #${e.vin} is not of type ${n}: ${r}`);Tp(Sp.Buffer,e.witnessScript,`${n} requires witnessScript`),Tp(Sp.Buffer,e.redeemScript,`${n} requires witnessScript`),Tp(Ep.Satoshi,e.witnessValue,`${n} requires witnessScript`)}}(e,i),({vin:c,keyPair:o,redeemScript:s,hashType:u,witnessValue:a,witnessScript:h}=i)}if(void 0===o)throw new Error("sign requires keypair");if(o.network&&o.network!==t)throw new TypeError("Inconsistent network");if(!e[c])throw new Error("No input at index: "+c);if(u=u||_p.Transaction.SIGHASH_ALL,r(u))throw new Error("Transaction needs outputs");const l=e[c];if(void 0!==l.redeemScript&&s&&!l.redeemScript.equals(s))throw new Error("Inconsistent redeemScript");const p=o.publicKey||o.getPublicKey&&o.getPublicKey();if(!Rp(l)){if(void 0!==a){if(void 0!==l.value&&l.value!==a)throw new Error("Input did not match witnessValue");Sp(Ep.Satoshi,a),l.value=a}if(!Rp(l)){const t=function(t,e,r,n){if(r&&n){const i=vp.p2wsh({redeem:{output:n}}),o=vp.p2wsh({output:r}),s=vp.p2sh({redeem:{output:r}}),u=vp.p2sh({redeem:i});if(!i.hash.equals(o.hash))throw new Error("Witness script inconsistent with prevOutScript");if(!s.hash.equals(u.hash))throw new Error("Redeem script inconsistent with prevOutScript");const a=Pp(i.redeem.output,e);if(!a.pubkeys)throw new Error(a.type+" not supported as witnessScript ("+wp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(a.signatures=t.signatures);const h=n;if(a.type===Ip.P2WPKH)throw new Error("P2SH(P2WSH(P2WPKH)) is a consensus failure");return{redeemScript:r,redeemScriptType:Ip.P2WSH,witnessScript:n,witnessScriptType:a.type,prevOutType:Ip.P2SH,prevOutScript:s.output,hasWitness:!0,signScript:h,signType:a.type,pubkeys:a.pubkeys,signatures:a.signatures,maxSignatures:a.maxSignatures}}if(r){const n=vp.p2sh({redeem:{output:r}});if(t.prevOutScript){let e;try{e=vp.p2sh({output:t.prevOutScript})}catch(t){throw new Error("PrevOutScript must be P2SH")}if(!n.hash.equals(e.hash))throw new Error("Redeem script inconsistent with prevOutScript")}const i=Pp(n.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as redeemScript ("+wp.toASM(r)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);let o=r;return i.type===Ip.P2WPKH&&(o=vp.p2pkh({pubkey:i.pubkeys[0]}).output),{redeemScript:r,redeemScriptType:i.type,prevOutType:Ip.P2SH,prevOutScript:n.output,hasWitness:i.type===Ip.P2WPKH,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(n){const r=vp.p2wsh({redeem:{output:n}});if(t.prevOutScript){const e=vp.p2wsh({output:t.prevOutScript});if(!r.hash.equals(e.hash))throw new Error("Witness script inconsistent with prevOutScript")}const i=Pp(r.redeem.output,e);if(!i.pubkeys)throw new Error(i.type+" not supported as witnessScript ("+wp.toASM(n)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(i.signatures=t.signatures);const o=n;if(i.type===Ip.P2WPKH)throw new Error("P2WSH(P2WPKH) is a consensus failure");return{witnessScript:n,witnessScriptType:i.type,prevOutType:Ip.P2WSH,prevOutScript:r.output,hasWitness:!0,signScript:o,signType:i.type,pubkeys:i.pubkeys,signatures:i.signatures,maxSignatures:i.maxSignatures}}if(t.prevOutType&&t.prevOutScript){if(t.prevOutType===Ip.P2SH)throw new Error("PrevOutScript is "+t.prevOutType+", requires redeemScript");if(t.prevOutType===Ip.P2WSH)throw new Error("PrevOutScript is "+t.prevOutType+", requires witnessScript");if(!t.prevOutScript)throw new Error("PrevOutScript is missing");const r=Pp(t.prevOutScript,e);if(!r.pubkeys)throw new Error(r.type+" not supported ("+wp.toASM(t.prevOutScript)+")");t.signatures&&t.signatures.some((t=>void 0!==t))&&(r.signatures=t.signatures);let n=t.prevOutScript;return r.type===Ip.P2WPKH&&(n=vp.p2pkh({pubkey:r.pubkeys[0]}).output),{prevOutType:r.type,prevOutScript:t.prevOutScript,hasWitness:r.type===Ip.P2WPKH,signScript:n,signType:r.type,pubkeys:r.pubkeys,signatures:r.signatures,maxSignatures:r.maxSignatures}}const i=vp.p2pkh({pubkey:e}).output;return{prevOutType:Ip.P2PKH,prevOutScript:i,hasWitness:!1,signScript:i,signType:Ip.P2PKH,pubkeys:[e],signatures:[void 0]}}(l,p,s,h);Object.assign(l,t)}if(!Rp(l))throw Error(l.prevOutType+" not supported")}let d;d=l.hasWitness?n.hashForWitnessV0(c,l.signScript,l.value,u):n.hashForSignature(c,l.signScript,u);return{input:l,ourPubKey:p,keyPair:o,signatureHash:d,hashType:u,useLowR:!!f}}(this.network,this.__INPUTS,this.__needsOutputs.bind(this),this.__TX,t,e,r,n,i,o,this.__USE_LOW_R))}__addInputUnsafe(t,e,r){if(_p.Transaction.isCoinbaseHash(t))throw new Error("coinbase inputs not supported");const n=t.toString("hex")+":"+e;if(void 0!==this.__PREV_TX_SET[n])throw new Error("Duplicate TxOut: "+n);let i={};if(void 0!==r.script&&(i=Ap(r.script,r.witness||[])),void 0!==r.value&&(i.value=r.value),!i.prevOutScript&&r.prevOutScript){let t;if(!i.pubkeys&&!i.signatures){const e=Pp(r.prevOutScript);e.pubkeys&&(i.pubkeys=e.pubkeys,i.signatures=e.signatures),t=e.type}i.prevOutScript=r.prevOutScript,i.prevOutType=t||dp.output(r.prevOutScript)}const o=this.__TX.addInput(t,e,r.sequence,r.scriptSig);return this.__INPUTS[o]=i,this.__PREV_TX_SET[n]=!0,o}__build(t){if(!t){if(!this.__TX.ins.length)throw new Error("Transaction has no inputs");if(!this.__TX.outs.length)throw new Error("Transaction has no outputs")}const e=this.__TX.clone();if(this.__INPUTS.forEach(((r,n)=>{if(!r.prevOutType&&!t)throw new Error("Transaction is not complete");const i=kp(r.prevOutType,r,t);if(i)e.setInputScript(n,i.input),e.setWitness(n,i.witness);else{if(!t&&r.prevOutType===Ip.NONSTANDARD)throw new Error("Unknown input type");if(!t)throw new Error("Not enough information")}})),!t&&this.__overMaximumFees(e.virtualSize()))throw new Error("Transaction has absurd fees");return e}__canModifyInputs(){return this.__INPUTS.every((t=>!t.signatures||t.signatures.every((t=>{if(!t)return!0;return 0!=(Np(t)&_p.Transaction.SIGHASH_ANYONECANPAY)}))))}__needsOutputs(t){return t===_p.Transaction.SIGHASH_ALL?0===this.__TX.outs.length:0===this.__TX.outs.length&&this.__INPUTS.some((t=>!!t.signatures&&t.signatures.some((t=>{if(!t)return!1;return!(Np(t)&_p.Transaction.SIGHASH_NONE)}))))}__canModifyOutputs(){const t=this.__TX.ins.length,e=this.__TX.outs.length;return this.__INPUTS.every((r=>void 0===r.signatures||r.signatures.every((r=>{if(!r)return!0;const n=31&Np(r);return n===_p.Transaction.SIGHASH_NONE||n===_p.Transaction.SIGHASH_SINGLE&&t<=e}))))}__overMaximumFees(t){const e=this.__INPUTS.reduce(((t,e)=>t+(e.value>>>0)),0),r=this.__TX.outs.reduce(((t,e)=>t+e.value),0);return(e-r)/t>this.maximumFeeRate}}function Ap(t,e,r,n){if(0===t.length&&0===e.length)return{};if(!r){let n=dp.input(t,!0),i=dp.witness(e,!0);n===Ip.NONSTANDARD&&(n=void 0),i===Ip.NONSTANDARD&&(i=void 0),r=n||i}switch(r){case Ip.P2WPKH:{const{output:t,pubkey:r,signature:n}=vp.p2wpkh({witness:e});return{prevOutScript:t,prevOutType:Ip.P2WPKH,pubkeys:[r],signatures:[n]}}case Ip.P2PKH:{const{output:e,pubkey:r,signature:n}=vp.p2pkh({input:t});return{prevOutScript:e,prevOutType:Ip.P2PKH,pubkeys:[r],signatures:[n]}}case Ip.P2PK:{const{signature:e}=vp.p2pk({input:t});return{prevOutType:Ip.P2PK,pubkeys:[void 0],signatures:[e]}}case Ip.P2MS:{const{m:e,pubkeys:r,signatures:i}=vp.p2ms({input:t,output:n},{allowIncomplete:!0});return{prevOutType:Ip.P2MS,pubkeys:r,signatures:i,maxSignatures:e}}}if(r===Ip.P2SH){const{output:r,redeem:n}=vp.p2sh({input:t,witness:e}),i=dp.output(n.output),o=Ap(n.input,n.witness,i,n.output);return o.prevOutType?{prevOutScript:r,prevOutType:Ip.P2SH,redeemScript:n.output,redeemScriptType:o.prevOutType,witnessScript:o.witnessScript,witnessScriptType:o.witnessScriptType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}if(r===Ip.P2WSH){const{output:r,redeem:n}=vp.p2wsh({input:t,witness:e}),i=dp.output(n.output);let o;return o=i===Ip.P2WPKH?Ap(n.input,n.witness,i):Ap(wp.compile(n.witness),[],i,n.output),o.prevOutType?{prevOutScript:r,prevOutType:Ip.P2WSH,witnessScript:n.output,witnessScriptType:o.prevOutType,pubkeys:o.pubkeys,signatures:o.signatures}:{}}return{prevOutType:Ip.NONSTANDARD,prevOutScript:t}}function Pp(t,e){Sp(Ep.Buffer,t);const r=dp.output(t);switch(r){case Ip.P2PKH:{if(!e)return{type:r};const n=vp.p2pkh({output:t}).hash,i=gp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case Ip.P2WPKH:{if(!e)return{type:r};const n=vp.p2wpkh({output:t}).hash,i=gp.hash160(e);return n.equals(i)?{type:r,pubkeys:[e],signatures:[void 0]}:{type:r}}case Ip.P2PK:return{type:r,pubkeys:[vp.p2pk({output:t}).pubkey],signatures:[void 0]};case Ip.P2MS:{const e=vp.p2ms({output:t});return{type:r,pubkeys:e.pubkeys,signatures:e.pubkeys.map((()=>{})),maxSignatures:e.m}}}return{type:r}}function kp(t,e,r){const n=e.pubkeys||[];let i=e.signatures||[];switch(t){case Ip.P2PKH:if(0===n.length)break;if(0===i.length)break;return vp.p2pkh({pubkey:n[0],signature:i[0]});case Ip.P2WPKH:if(0===n.length)break;if(0===i.length)break;return vp.p2wpkh({pubkey:n[0],signature:i[0]});case Ip.P2PK:if(0===n.length)break;if(0===i.length)break;return vp.p2pk({signature:i[0]});case Ip.P2MS:{const t=e.maxSignatures;i=r?i.map((t=>t||bp.OPS.OP_0)):i.filter((t=>t));const o=!r||t===i.length;return vp.p2ms({m:t,pubkeys:n,signatures:i},{allowIncomplete:r,validate:o})}case Ip.P2SH:{const t=kp(e.redeemScriptType,e,r);if(!t)return;return vp.p2sh({redeem:{output:t.output||e.redeemScript,input:t.input,witness:t.witness}})}case Ip.P2WSH:{const t=kp(e.witnessScriptType,e,r);if(!t)return;return vp.p2wsh({redeem:{output:e.witnessScript,input:t.input,witness:t.witness}})}}}function Rp(t){return void 0!==t.signScript&&void 0!==t.signType&&void 0!==t.pubkeys&&void 0!==t.signatures&&t.signatures.length===t.pubkeys.length&&t.pubkeys.length>0&&(!1===t.hasWitness||void 0!==t.value)}function Np(t){return t.readUInt8(t.length-1)}_c.TransactionBuilder=Op,Object.defineProperty(Mt,"__esModule",{value:!0});const xp=Tt;Mt.bip32=xp;const Bp=es;Mt.address=Bp;const Lp=Js;var Up=Mt.crypto=Lp;const Cp=ha;Mt.ECPair=Cp;const Dp=rs;Mt.networks=Dp;const Hp=ns;Mt.payments=Hp;const Fp=os;Mt.script=Fp;var jp=ba;Mt.Block=jp.Block;var qp=oh;Mt.Psbt=qp.Psbt;var Gp=os;Mt.opcodes=Gp.OPS;var Kp=Na;Mt.Transaction=Kp.Transaction;var Wp=_c;Mt.TransactionBuilder=Wp.TransactionBuilder;var Vp={exports:{}};var $p={SEMVER_SPEC_VERSION:"2.0.0",MAX_LENGTH:256,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||9007199254740991,MAX_SAFE_COMPONENT_LENGTH:16};var zp="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};!function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r}=$p,n=zp,i=(e=t.exports={}).re=[],o=e.src=[],s=e.t={};let u=0;const a=(t,e,r)=>{const a=u++;n(a,e),s[t]=a,o[a]=e,i[a]=new RegExp(e,r?"g":void 0)};a("NUMERICIDENTIFIER","0|[1-9]\\d*"),a("NUMERICIDENTIFIERLOOSE","[0-9]+"),a("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*"),a("MAINVERSION",`(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})\\.(${o[s.NUMERICIDENTIFIER]})`),a("MAINVERSIONLOOSE",`(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})\\.(${o[s.NUMERICIDENTIFIERLOOSE]})`),a("PRERELEASEIDENTIFIER",`(?:${o[s.NUMERICIDENTIFIER]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASEIDENTIFIERLOOSE",`(?:${o[s.NUMERICIDENTIFIERLOOSE]}|${o[s.NONNUMERICIDENTIFIER]})`),a("PRERELEASE",`(?:-(${o[s.PRERELEASEIDENTIFIER]}(?:\\.${o[s.PRERELEASEIDENTIFIER]})*))`),a("PRERELEASELOOSE",`(?:-?(${o[s.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${o[s.PRERELEASEIDENTIFIERLOOSE]})*))`),a("BUILDIDENTIFIER","[0-9A-Za-z-]+"),a("BUILD",`(?:\\+(${o[s.BUILDIDENTIFIER]}(?:\\.${o[s.BUILDIDENTIFIER]})*))`),a("FULLPLAIN",`v?${o[s.MAINVERSION]}${o[s.PRERELEASE]}?${o[s.BUILD]}?`),a("FULL",`^${o[s.FULLPLAIN]}$`),a("LOOSEPLAIN",`[v=\\s]*${o[s.MAINVERSIONLOOSE]}${o[s.PRERELEASELOOSE]}?${o[s.BUILD]}?`),a("LOOSE",`^${o[s.LOOSEPLAIN]}$`),a("GTLT","((?:<|>)?=?)"),a("XRANGEIDENTIFIERLOOSE",`${o[s.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),a("XRANGEIDENTIFIER",`${o[s.NUMERICIDENTIFIER]}|x|X|\\*`),a("XRANGEPLAIN",`[v=\\s]*(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:\\.(${o[s.XRANGEIDENTIFIER]})(?:${o[s.PRERELEASE]})?${o[s.BUILD]}?)?)?`),a("XRANGEPLAINLOOSE",`[v=\\s]*(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:\\.(${o[s.XRANGEIDENTIFIERLOOSE]})(?:${o[s.PRERELEASELOOSE]})?${o[s.BUILD]}?)?)?`),a("XRANGE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAIN]}$`),a("XRANGELOOSE",`^${o[s.GTLT]}\\s*${o[s.XRANGEPLAINLOOSE]}$`),a("COERCE",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?(?:$|[^\\d])`),a("COERCERTL",o[s.COERCE],!0),a("LONETILDE","(?:~>?)"),a("TILDETRIM",`(\\s*)${o[s.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",a("TILDE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAIN]}$`),a("TILDELOOSE",`^${o[s.LONETILDE]}${o[s.XRANGEPLAINLOOSE]}$`),a("LONECARET","(?:\\^)"),a("CARETTRIM",`(\\s*)${o[s.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",a("CARET",`^${o[s.LONECARET]}${o[s.XRANGEPLAIN]}$`),a("CARETLOOSE",`^${o[s.LONECARET]}${o[s.XRANGEPLAINLOOSE]}$`),a("COMPARATORLOOSE",`^${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]})$|^$`),a("COMPARATOR",`^${o[s.GTLT]}\\s*(${o[s.FULLPLAIN]})$|^$`),a("COMPARATORTRIM",`(\\s*)${o[s.GTLT]}\\s*(${o[s.LOOSEPLAIN]}|${o[s.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",a("HYPHENRANGE",`^\\s*(${o[s.XRANGEPLAIN]})\\s+-\\s+(${o[s.XRANGEPLAIN]})\\s*$`),a("HYPHENRANGELOOSE",`^\\s*(${o[s.XRANGEPLAINLOOSE]})\\s+-\\s+(${o[s.XRANGEPLAINLOOSE]})\\s*$`),a("STAR","(<|>)?=?\\s*\\*"),a("GTE0","^\\s*>=\\s*0.0.0\\s*$"),a("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")}(Vp,Vp.exports);const Xp=["includePrerelease","loose","rtl"];var Yp=t=>t?"object"!=typeof t?{loose:!0}:Xp.filter((e=>t[e])).reduce(((t,e)=>(t[e]=!0,t)),{}):{};const Jp=/^[0-9]+$/,Zp=(t,e)=>{const r=Jp.test(t),n=Jp.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:tZp(e,t)};const td=zp,{MAX_LENGTH:ed,MAX_SAFE_INTEGER:rd}=$p,{re:nd,t:id}=Vp.exports,od=Yp,{compareIdentifiers:sd}=Qp;class ud{constructor(t,e){if(e=od(e),t instanceof ud){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if("string"!=typeof t)throw new TypeError(`Invalid Version: ${t}`);if(t.length>ed)throw new TypeError(`version is longer than ${ed} characters`);td("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;const r=t.trim().match(e.loose?nd[id.LOOSE]:nd[id.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>rd||this.major<0)throw new TypeError("Invalid major version");if(this.minor>rd||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>rd||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((t=>{if(/^[0-9]+$/.test(t)){const e=+t;if(e>=0&&e=0;)"number"==typeof this.prerelease[t]&&(this.prerelease[t]++,t=-2);-1===t&&this.prerelease.push(0)}e&&(this.prerelease[0]===e?isNaN(this.prerelease[1])&&(this.prerelease=[e,0]):this.prerelease=[e,0]);break;default:throw new Error(`invalid increment argument: ${t}`)}return this.format(),this.raw=this.version,this}}var ad=ud;const{MAX_LENGTH:hd}=$p,{re:fd,t:cd}=Vp.exports,ld=ad,pd=Yp;var dd=(t,e)=>{if(e=pd(e),t instanceof ld)return t;if("string"!=typeof t)return null;if(t.length>hd)return null;if(!(e.loose?fd[cd.LOOSE]:fd[cd.FULL]).test(t))return null;try{return new ld(t,e)}catch(t){return null}};const gd=dd;var md=(t,e)=>{const r=gd(t,e);return r?r.version:null};const yd=dd;var vd=(t,e)=>{const r=yd(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null};const wd=ad;var bd=(t,e,r,n)=>{"string"==typeof r&&(n=r,r=void 0);try{return new wd(t,r).inc(e,n).version}catch(t){return null}};const _d=ad;var Ed=(t,e,r)=>new _d(t,r).compare(new _d(e,r));const Sd=Ed;var Id=(t,e,r)=>0===Sd(t,e,r);const Md=dd,Td=Id;var Od=(t,e)=>{if(Td(t,e))return null;{const r=Md(t),n=Md(e),i=r.prerelease.length||n.prerelease.length,o=i?"pre":"",s=i?"prerelease":"";for(const t in r)if(("major"===t||"minor"===t||"patch"===t)&&r[t]!==n[t])return o+t;return s}};const Ad=ad;var Pd=(t,e)=>new Ad(t,e).major;const kd=ad;var Rd=(t,e)=>new kd(t,e).minor;const Nd=ad;var xd=(t,e)=>new Nd(t,e).patch;const Bd=dd;var Ld=(t,e)=>{const r=Bd(t,e);return r&&r.prerelease.length?r.prerelease:null};const Ud=Ed;var Cd=(t,e,r)=>Ud(e,t,r);const Dd=Ed;var Hd=(t,e)=>Dd(t,e,!0);const Fd=ad;var jd=(t,e,r)=>{const n=new Fd(t,r),i=new Fd(e,r);return n.compare(i)||n.compareBuild(i)};const qd=jd;var Gd=(t,e)=>t.sort(((t,r)=>qd(t,r,e)));const Kd=jd;var Wd=(t,e)=>t.sort(((t,r)=>Kd(r,t,e)));const Vd=Ed;var $d=(t,e,r)=>Vd(t,e,r)>0;const zd=Ed;var Xd=(t,e,r)=>zd(t,e,r)<0;const Yd=Ed;var Jd=(t,e,r)=>0!==Yd(t,e,r);const Zd=Ed;var Qd=(t,e,r)=>Zd(t,e,r)>=0;const tg=Ed;var eg=(t,e,r)=>tg(t,e,r)<=0;const rg=Id,ng=Jd,ig=$d,og=Qd,sg=Xd,ug=eg;var ag=(t,e,r,n)=>{switch(e){case"===":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t===r;case"!==":return"object"==typeof t&&(t=t.version),"object"==typeof r&&(r=r.version),t!==r;case"":case"=":case"==":return rg(t,r,n);case"!=":return ng(t,r,n);case">":return ig(t,r,n);case">=":return og(t,r,n);case"<":return sg(t,r,n);case"<=":return ug(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}};const hg=ad,fg=dd,{re:cg,t:lg}=Vp.exports;var pg=(t,e)=>{if(t instanceof hg)return t;if("number"==typeof t&&(t=String(t)),"string"!=typeof t)return null;let r=null;if((e=e||{}).rtl){let e;for(;(e=cg[lg.COERCERTL].exec(t))&&(!r||r.index+r[0].length!==t.length);)r&&e.index+e[0].length===r.index+r[0].length||(r=e),cg[lg.COERCERTL].lastIndex=e.index+e[1].length+e[2].length;cg[lg.COERCERTL].lastIndex=-1}else r=t.match(cg[lg.COERCE]);return null===r?null:fg(`${r[2]}.${r[3]||"0"}.${r[4]||"0"}`,e)},dg=gg;function gg(t){var e=this;if(e instanceof gg||(e=new gg),e.tail=null,e.head=null,e.length=0,t&&"function"==typeof t.forEach)t.forEach((function(t){e.push(t)}));else if(arguments.length>0)for(var r=0,n=arguments.length;r1)r=e;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");n=this.head.next,r=this.head.value}for(var i=0;null!==n;i++)r=t(r,n.value,i),n=n.next;return r},gg.prototype.reduceReverse=function(t,e){var r,n=this.tail;if(arguments.length>1)r=e;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");n=this.tail.prev,r=this.tail.value}for(var i=this.length-1;null!==n;i--)r=t(r,n.value,i),n=n.prev;return r},gg.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;null!==r;e++)t[e]=r.value,r=r.next;return t},gg.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;null!==r;e++)t[e]=r.value,r=r.prev;return t},gg.prototype.slice=function(t,e){(e=e||this.length)<0&&(e+=this.length),(t=t||0)<0&&(t+=this.length);var r=new gg;if(ethis.length&&(e=this.length);for(var n=0,i=this.head;null!==i&&nthis.length&&(e=this.length);for(var n=this.length,i=this.tail;null!==i&&n>e;n--)i=i.prev;for(;null!==i&&n>t;n--,i=i.prev)r.push(i.value);return r},gg.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var n=0,i=this.head;null!==i&&n1;const Ng=(t,e,r)=>{const n=t[Pg].get(e);if(n){const e=n.value;if(xg(t,e)){if(Lg(t,n),!t[Ig])return}else r&&(t[kg]&&(n.value.now=Date.now()),t[Ag].unshiftNode(n));return e.value}},xg=(t,e)=>{if(!e||!e.maxAge&&!t[Mg])return!1;const r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[Mg]&&r>t[Mg]},Bg=t=>{if(t[Eg]>t[_g])for(let e=t[Ag].tail;t[Eg]>t[_g]&&null!==e;){const r=e.prev;Lg(t,e),e=r}},Lg=(t,e)=>{if(e){const r=e.value;t[Tg]&&t[Tg](r.key,r.value),t[Eg]-=r.length,t[Pg].delete(r.key),t[Ag].removeNode(e)}};class Ug{constructor(t,e,r,n,i){this.key=t,this.value=e,this.length=r,this.now=n,this.maxAge=i||0}}const Cg=(t,e,r,n)=>{let i=r.value;xg(t,i)&&(Lg(t,r),t[Ig]||(i=void 0)),i&&e.call(n,i.value,i.key,t)};var Dg=class{constructor(t){if("number"==typeof t&&(t={max:t}),t||(t={}),t.max&&("number"!=typeof t.max||t.max<0))throw new TypeError("max must be a non-negative number");this[_g]=t.max||1/0;const e=t.length||Rg;if(this[Sg]="function"!=typeof e?Rg:e,this[Ig]=t.stale||!1,t.maxAge&&"number"!=typeof t.maxAge)throw new TypeError("maxAge must be a number");this[Mg]=t.maxAge||0,this[Tg]=t.dispose,this[Og]=t.noDisposeOnSet||!1,this[kg]=t.updateAgeOnGet||!1,this.reset()}set max(t){if("number"!=typeof t||t<0)throw new TypeError("max must be a non-negative number");this[_g]=t||1/0,Bg(this)}get max(){return this[_g]}set allowStale(t){this[Ig]=!!t}get allowStale(){return this[Ig]}set maxAge(t){if("number"!=typeof t)throw new TypeError("maxAge must be a non-negative number");this[Mg]=t,Bg(this)}get maxAge(){return this[Mg]}set lengthCalculator(t){"function"!=typeof t&&(t=Rg),t!==this[Sg]&&(this[Sg]=t,this[Eg]=0,this[Ag].forEach((t=>{t.length=this[Sg](t.value,t.key),this[Eg]+=t.length}))),Bg(this)}get lengthCalculator(){return this[Sg]}get length(){return this[Eg]}get itemCount(){return this[Ag].length}rforEach(t,e){e=e||this;for(let r=this[Ag].tail;null!==r;){const n=r.prev;Cg(this,t,r,e),r=n}}forEach(t,e){e=e||this;for(let r=this[Ag].head;null!==r;){const n=r.next;Cg(this,t,r,e),r=n}}keys(){return this[Ag].toArray().map((t=>t.key))}values(){return this[Ag].toArray().map((t=>t.value))}reset(){this[Tg]&&this[Ag]&&this[Ag].length&&this[Ag].forEach((t=>this[Tg](t.key,t.value))),this[Pg]=new Map,this[Ag]=new bg,this[Eg]=0}dump(){return this[Ag].map((t=>!xg(this,t)&&{k:t.key,v:t.value,e:t.now+(t.maxAge||0)})).toArray().filter((t=>t))}dumpLru(){return this[Ag]}set(t,e,r){if((r=r||this[Mg])&&"number"!=typeof r)throw new TypeError("maxAge must be a number");const n=r?Date.now():0,i=this[Sg](e,t);if(this[Pg].has(t)){if(i>this[_g])return Lg(this,this[Pg].get(t)),!1;const o=this[Pg].get(t).value;return this[Tg]&&(this[Og]||this[Tg](t,o.value)),o.now=n,o.maxAge=r,o.value=e,this[Eg]+=i-o.length,o.length=i,this.get(t),Bg(this),!0}const o=new Ug(t,e,i,n,r);return o.length>this[_g]?(this[Tg]&&this[Tg](t,e),!1):(this[Eg]+=o.length,this[Ag].unshift(o),this[Pg].set(t,this[Ag].head),Bg(this),!0)}has(t){if(!this[Pg].has(t))return!1;const e=this[Pg].get(t).value;return!xg(this,e)}get(t){return Ng(this,t,!0)}peek(t){return Ng(this,t,!1)}pop(){const t=this[Ag].tail;return t?(Lg(this,t),t.value):null}del(t){Lg(this,this[Pg].get(t))}load(t){this.reset();const e=Date.now();for(let r=t.length-1;r>=0;r--){const n=t[r],i=n.e||0;if(0===i)this.set(n.k,n.v);else{const t=i-e;t>0&&this.set(n.k,n.v,t)}}}prune(){this[Pg].forEach(((t,e)=>Ng(this,e,!1)))}};class Hg{constructor(t,e){if(e=qg(e),t instanceof Hg)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new Hg(t.raw,e);if(t instanceof Gg)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((t=>this.parseRange(t.trim()))).filter((t=>t.length)),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${t}`);if(this.set.length>1){const t=this.set[0];if(this.set=this.set.filter((t=>!Jg(t[0]))),0===this.set.length)this.set=[t];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&Zg(t[0])){this.set=[t];break}}this.format()}format(){return this.range=this.set.map((t=>t.join(" ").trim())).join("||").trim(),this.range}toString(){return this.range}parseRange(t){t=t.trim();const e=`parseRange:${Object.keys(this.options).join(",")}:${t}`,r=jg.get(e);if(r)return r;const n=this.options.loose,i=n?Vg[$g.HYPHENRANGELOOSE]:Vg[$g.HYPHENRANGE];t=t.replace(i,fm(this.options.includePrerelease)),Kg("hyphen replace",t),t=t.replace(Vg[$g.COMPARATORTRIM],zg),Kg("comparator trim",t,Vg[$g.COMPARATORTRIM]),t=(t=(t=t.replace(Vg[$g.TILDETRIM],Xg)).replace(Vg[$g.CARETTRIM],Yg)).split(/\s+/).join(" ");const o=n?Vg[$g.COMPARATORLOOSE]:Vg[$g.COMPARATOR],s=t.split(" ").map((t=>tm(t,this.options))).join(" ").split(/\s+/).map((t=>hm(t,this.options))).filter(this.options.loose?t=>!!t.match(o):()=>!0).map((t=>new Gg(t,this.options)));s.length;const u=new Map;for(const t of s){if(Jg(t))return[t];u.set(t.value,t)}u.size>1&&u.has("")&&u.delete("");const a=[...u.values()];return jg.set(e,a),a}intersects(t,e){if(!(t instanceof Hg))throw new TypeError("a Range is required");return this.set.some((r=>Qg(r,e)&&t.set.some((t=>Qg(t,e)&&r.every((r=>t.every((t=>r.intersects(t,e)))))))))}test(t){if(!t)return!1;if("string"==typeof t)try{t=new Wg(t,this.options)}catch(t){return!1}for(let e=0;e"<0.0.0-0"===t.value,Zg=t=>""===t.value,Qg=(t,e)=>{let r=!0;const n=t.slice();let i=n.pop();for(;r&&n.length;)r=n.every((t=>i.intersects(t,e))),i=n.pop();return r},tm=(t,e)=>(Kg("comp",t,e),t=im(t,e),Kg("caret",t),t=rm(t,e),Kg("tildes",t),t=sm(t,e),Kg("xrange",t),t=am(t,e),Kg("stars",t),t),em=t=>!t||"x"===t.toLowerCase()||"*"===t,rm=(t,e)=>t.trim().split(/\s+/).map((t=>nm(t,e))).join(" "),nm=(t,e)=>{const r=e.loose?Vg[$g.TILDELOOSE]:Vg[$g.TILDE];return t.replace(r,((e,r,n,i,o)=>{let s;return Kg("tilde",t,e,r,n,i,o),em(r)?s="":em(n)?s=`>=${r}.0.0 <${+r+1}.0.0-0`:em(i)?s=`>=${r}.${n}.0 <${r}.${+n+1}.0-0`:o?(Kg("replaceTilde pr",o),s=`>=${r}.${n}.${i}-${o} <${r}.${+n+1}.0-0`):s=`>=${r}.${n}.${i} <${r}.${+n+1}.0-0`,Kg("tilde return",s),s}))},im=(t,e)=>t.trim().split(/\s+/).map((t=>om(t,e))).join(" "),om=(t,e)=>{Kg("caret",t,e);const r=e.loose?Vg[$g.CARETLOOSE]:Vg[$g.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,((e,r,i,o,s)=>{let u;return Kg("caret",t,e,r,i,o,s),em(r)?u="":em(i)?u=`>=${r}.0.0${n} <${+r+1}.0.0-0`:em(o)?u="0"===r?`>=${r}.${i}.0${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.0${n} <${+r+1}.0.0-0`:s?(Kg("replaceCaret pr",s),u="0"===r?"0"===i?`>=${r}.${i}.${o}-${s} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}-${s} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o}-${s} <${+r+1}.0.0-0`):(Kg("no pr"),u="0"===r?"0"===i?`>=${r}.${i}.${o}${n} <${r}.${i}.${+o+1}-0`:`>=${r}.${i}.${o}${n} <${r}.${+i+1}.0-0`:`>=${r}.${i}.${o} <${+r+1}.0.0-0`),Kg("caret return",u),u}))},sm=(t,e)=>(Kg("replaceXRanges",t,e),t.split(/\s+/).map((t=>um(t,e))).join(" ")),um=(t,e)=>{t=t.trim();const r=e.loose?Vg[$g.XRANGELOOSE]:Vg[$g.XRANGE];return t.replace(r,((r,n,i,o,s,u)=>{Kg("xRange",t,r,n,i,o,s,u);const a=em(i),h=a||em(o),f=h||em(s),c=f;return"="===n&&c&&(n=""),u=e.includePrerelease?"-0":"",a?r=">"===n||"<"===n?"<0.0.0-0":"*":n&&c?(h&&(o=0),s=0,">"===n?(n=">=",h?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",h?i=+i+1:o=+o+1),"<"===n&&(u="-0"),r=`${n+i}.${o}.${s}${u}`):h?r=`>=${i}.0.0${u} <${+i+1}.0.0-0`:f&&(r=`>=${i}.${o}.0${u} <${i}.${+o+1}.0-0`),Kg("xRange return",r),r}))},am=(t,e)=>(Kg("replaceStars",t,e),t.trim().replace(Vg[$g.STAR],"")),hm=(t,e)=>(Kg("replaceGTE0",t,e),t.trim().replace(Vg[e.includePrerelease?$g.GTE0PRE:$g.GTE0],"")),fm=t=>(e,r,n,i,o,s,u,a,h,f,c,l,p)=>`${r=em(n)?"":em(i)?`>=${n}.0.0${t?"-0":""}`:em(o)?`>=${n}.${i}.0${t?"-0":""}`:s?`>=${r}`:`>=${r}${t?"-0":""}`} ${a=em(h)?"":em(f)?`<${+h+1}.0.0-0`:em(c)?`<${h}.${+f+1}.0-0`:l?`<=${h}.${f}.${c}-${l}`:t?`<${h}.${f}.${+c+1}-0`:`<=${a}`}`.trim(),cm=(t,e,r)=>{for(let r=0;r0){const n=t[r].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0},lm=Symbol("SemVer ANY");class pm{static get ANY(){return lm}constructor(t,e){if(e=gm(e),t instanceof pm){if(t.loose===!!e.loose)return t;t=t.value}wm("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===lm?this.value="":this.value=this.operator+this.semver.version,wm("comp",this)}parse(t){const e=this.options.loose?mm[ym.COMPARATORLOOSE]:mm[ym.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==r[1]?r[1]:"","="===this.operator&&(this.operator=""),r[2]?this.semver=new bm(r[2],this.options.loose):this.semver=lm}toString(){return this.value}test(t){if(wm("Comparator.test",t,this.options.loose),this.semver===lm||t===lm)return!0;if("string"==typeof t)try{t=new bm(t,this.options)}catch(t){return!1}return vm(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof pm))throw new TypeError("a Comparator is required");if(e&&"object"==typeof e||(e={loose:!!e,includePrerelease:!1}),""===this.operator)return""===this.value||new _m(t.value,e).test(this.value);if(""===t.operator)return""===t.value||new _m(this.value,e).test(t.semver);const r=!(">="!==this.operator&&">"!==this.operator||">="!==t.operator&&">"!==t.operator),n=!("<="!==this.operator&&"<"!==this.operator||"<="!==t.operator&&"<"!==t.operator),i=this.semver.version===t.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==t.operator&&"<="!==t.operator),s=vm(this.semver,"<",t.semver,e)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),u=vm(this.semver,">",t.semver,e)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return r||n||i&&o||s||u}}var dm=pm;const gm=Yp,{re:mm,t:ym}=Vp.exports,vm=ag,wm=zp,bm=ad,_m=Fg,Em=Fg;var Sm=(t,e,r)=>{try{e=new Em(e,r)}catch(t){return!1}return e.test(t)};const Im=Fg;var Mm=(t,e)=>new Im(t,e).set.map((t=>t.map((t=>t.value)).join(" ").trim().split(" ")));const Tm=ad,Om=Fg;var Am=(t,e,r)=>{let n=null,i=null,o=null;try{o=new Om(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&-1!==i.compare(t)||(n=t,i=new Tm(n,r)))})),n};const Pm=ad,km=Fg;var Rm=(t,e,r)=>{let n=null,i=null,o=null;try{o=new km(e,r)}catch(t){return null}return t.forEach((t=>{o.test(t)&&(n&&1!==i.compare(t)||(n=t,i=new Pm(n,r)))})),n};const Nm=ad,xm=Fg,Bm=$d;var Lm=(t,e)=>{t=new xm(t,e);let r=new Nm("0.0.0");if(t.test(r))return r;if(r=new Nm("0.0.0-0"),t.test(r))return r;r=null;for(let e=0;e{const e=new Nm(t.semver.version);switch(t.operator){case">":0===e.prerelease.length?e.patch++:e.prerelease.push(0),e.raw=e.format();case"":case">=":i&&!Bm(e,i)||(i=e);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}})),!i||r&&!Bm(r,i)||(r=i)}return r&&t.test(r)?r:null};const Um=Fg;var Cm=(t,e)=>{try{return new Um(t,e).range||"*"}catch(t){return null}};const Dm=ad,Hm=dm,{ANY:Fm}=Hm,jm=Fg,qm=Sm,Gm=$d,Km=Xd,Wm=eg,Vm=Qd;var $m=(t,e,r,n)=>{let i,o,s,u,a;switch(t=new Dm(t,n),e=new jm(e,n),r){case">":i=Gm,o=Wm,s=Km,u=">",a=">=";break;case"<":i=Km,o=Vm,s=Gm,u="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(qm(t,e,n))return!1;for(let r=0;r{t.semver===Fm&&(t=new Hm(">=0.0.0")),f=f||t,c=c||t,i(t.semver,f.semver,n)?f=t:s(t.semver,c.semver,n)&&(c=t)})),f.operator===u||f.operator===a)return!1;if((!c.operator||c.operator===u)&&o(t,c.semver))return!1;if(c.operator===a&&s(t,c.semver))return!1}return!0};const zm=$m;var Xm=(t,e,r)=>zm(t,e,">",r);const Ym=$m;var Jm=(t,e,r)=>Ym(t,e,"<",r);const Zm=Fg;var Qm=(t,e,r)=>(t=new Zm(t,r),e=new Zm(e,r),t.intersects(e));const ty=Sm,ey=Ed;const ry=Fg,ny=dm,{ANY:iy}=ny,oy=Sm,sy=Ed,uy=(t,e,r)=>{if(t===e)return!0;if(1===t.length&&t[0].semver===iy){if(1===e.length&&e[0].semver===iy)return!0;t=r.includePrerelease?[new ny(">=0.0.0-0")]:[new ny(">=0.0.0")]}if(1===e.length&&e[0].semver===iy){if(r.includePrerelease)return!0;e=[new ny(">=0.0.0")]}const n=new Set;let i,o,s,u,a,h,f;for(const e of t)">"===e.operator||">="===e.operator?i=ay(i,e,r):"<"===e.operator||"<="===e.operator?o=hy(o,e,r):n.add(e.semver);if(n.size>1)return null;if(i&&o){if(s=sy(i.semver,o.semver,r),s>0)return null;if(0===s&&(">="!==i.operator||"<="!==o.operator))return null}for(const t of n){if(i&&!oy(t,String(i),r))return null;if(o&&!oy(t,String(o),r))return null;for(const n of e)if(!oy(t,String(n),r))return!1;return!0}let c=!(!o||r.includePrerelease||!o.semver.prerelease.length)&&o.semver,l=!(!i||r.includePrerelease||!i.semver.prerelease.length)&&i.semver;c&&1===c.prerelease.length&&"<"===o.operator&&0===c.prerelease[0]&&(c=!1);for(const t of e){if(f=f||">"===t.operator||">="===t.operator,h=h||"<"===t.operator||"<="===t.operator,i)if(l&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===l.major&&t.semver.minor===l.minor&&t.semver.patch===l.patch&&(l=!1),">"===t.operator||">="===t.operator){if(u=ay(i,t,r),u===t&&u!==i)return!1}else if(">="===i.operator&&!oy(i.semver,String(t),r))return!1;if(o)if(c&&t.semver.prerelease&&t.semver.prerelease.length&&t.semver.major===c.major&&t.semver.minor===c.minor&&t.semver.patch===c.patch&&(c=!1),"<"===t.operator||"<="===t.operator){if(a=hy(o,t,r),a===t&&a!==o)return!1}else if("<="===o.operator&&!oy(o.semver,String(t),r))return!1;if(!t.operator&&(o||i)&&0!==s)return!1}return!(i&&h&&!o&&0!==s)&&(!(o&&f&&!i&&0!==s)&&(!l&&!c))},ay=(t,e,r)=>{if(!t)return e;const n=sy(t.semver,e.semver,r);return n>0?t:n<0||">"===e.operator&&">="===t.operator?e:t},hy=(t,e,r)=>{if(!t)return e;const n=sy(t.semver,e.semver,r);return n<0?t:n>0||"<"===e.operator&&"<="===t.operator?e:t};var fy=(t,e,r={})=>{if(t===e)return!0;t=new ry(t,r),e=new ry(e,r);let n=!1;t:for(const i of t.set){for(const t of e.set){const e=uy(i,t,r);if(n=n||null!==e,e)continue t}if(n)return!1}return!0};const cy=Vp.exports;var ly={re:cy.re,src:cy.src,tokens:cy.t,SEMVER_SPEC_VERSION:$p.SEMVER_SPEC_VERSION,SemVer:ad,compareIdentifiers:Qp.compareIdentifiers,rcompareIdentifiers:Qp.rcompareIdentifiers,parse:dd,valid:md,clean:vd,inc:bd,diff:Od,major:Pd,minor:Rd,patch:xd,prerelease:Ld,compare:Ed,rcompare:Cd,compareLoose:Hd,compareBuild:jd,sort:Gd,rsort:Wd,gt:$d,lt:Xd,eq:Id,neq:Jd,gte:Qd,lte:eg,cmp:ag,coerce:pg,Comparator:dm,Range:Fg,satisfies:Sm,toComparators:Mm,maxSatisfying:Am,minSatisfying:Rm,minVersion:Lm,validRange:Cm,outside:$m,gtr:Xm,ltr:Jm,intersects:Qm,simplifyRange:(t,e,r)=>{const n=[];let i=null,o=null;const s=t.sort(((t,e)=>ey(t,e,r)));for(const t of s){ty(t,e,r)?(o=t,i||(i=t)):(o&&n.push([i,o]),o=null,i=null)}i&&n.push([i,null]);const u=[];for(const[t,e]of n)t===e?u.push(t):e||t!==s[0]?e?t===s[0]?u.push(`<=${e}`):u.push(`${t} - ${e}`):u.push(`>=${t}`):u.push("*");const a=u.join(" || "),h="string"==typeof e.raw?e.raw:String(e);return a.length0&&s.length>i){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,u=a,"function"==typeof console.warn?console.warn(u):console.log(u)}}else s=o[e]=r,++t._eventsCount;return t}function Oy(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function Ay(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Py(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}vy.prototype=Object.create(null),wy.EventEmitter=wy,wy.usingDomains=!1,wy.prototype.domain=void 0,wy.prototype._events=void 0,wy.prototype._maxListeners=void 0,wy.defaultMaxListeners=10,wy.init=function(){this.domain=null,wy.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new vy,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},wy.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},wy.prototype.getMaxListeners=function(){return by(this)},wy.prototype.emit=function(t){var e,r,n,i,o,s,u,a="error"===t;if(s=this._events)a=a&&null==s.error;else if(!a)return!1;if(u=this.domain,a){if(e=arguments[1],!u){if(e instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=s[t]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:_y(r,f,this);break;case 2:Ey(r,f,this,arguments[1]);break;case 3:Sy(r,f,this,arguments[1],arguments[2]);break;case 4:Iy(r,f,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===e||r[o].listener&&r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new vy,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var ky=Object.freeze({__proto__:null,default:wy,EventEmitter:wy});function Ry(){throw new Error("setTimeout has not been defined")}function Ny(){throw new Error("clearTimeout has not been defined")}var xy=Ry,By=Ny;function Ly(t){if(xy===setTimeout)return setTimeout(t,0);if((xy===Ry||!xy)&&setTimeout)return xy=setTimeout,setTimeout(t,0);try{return xy(t,0)}catch(e){try{return xy.call(null,t,0)}catch(e){return xy.call(this,t,0)}}}"function"==typeof global.setTimeout&&(xy=setTimeout),"function"==typeof global.clearTimeout&&(By=clearTimeout);var Uy,Cy=[],Dy=!1,Hy=-1;function Fy(){Dy&&Uy&&(Dy=!1,Uy.length?Cy=Uy.concat(Cy):Hy=-1,Cy.length&&jy())}function jy(){if(!Dy){var t=Ly(Fy);Dy=!0;for(var e=Cy.length;e;){for(Uy=Cy,Cy=[];++Hy1)for(var r=1;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),s=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),ov(e)?r.showHidden=e:e&&Iv(r,e),cv(r.showHidden)&&(r.showHidden=!1),cv(r.depth)&&(r.depth=2),cv(r.colors)&&(r.colors=!1),cv(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Qy),ev(r,t,r.depth)}function Qy(t,e){var r=Zy.styles[e];return r?"["+Zy.colors[r][0]+"m"+t+"["+Zy.colors[r][1]+"m":t}function tv(t,e){return t}function ev(t,e,r){if(t.customInspect&&e&&mv(e.inspect)&&e.inspect!==Zy&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return hv(n)||(n=ev(t,n,r)),n}var i=function(t,e){if(cv(e))return t.stylize("undefined","undefined");if(hv(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(av(e))return t.stylize(""+e,"number");if(ov(e))return t.stylize(""+e,"boolean");if(sv(e))return t.stylize("null","null")}(t,e);if(i)return i;var o=Object.keys(e),s=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(e)),gv(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return rv(e);if(0===o.length){if(mv(e)){var u=e.name?": "+e.name:"";return t.stylize("[Function"+u+"]","special")}if(lv(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(dv(e))return t.stylize(Date.prototype.toString.call(e),"date");if(gv(e))return rv(e)}var a,h="",f=!1,c=["{","}"];(iv(e)&&(f=!0,c=["[","]"]),mv(e))&&(h=" [Function"+(e.name?": "+e.name:"")+"]");return lv(e)&&(h=" "+RegExp.prototype.toString.call(e)),dv(e)&&(h=" "+Date.prototype.toUTCString.call(e)),gv(e)&&(h=" "+rv(e)),0!==o.length||f&&0!=e.length?r<0?lv(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),a=f?function(t,e,r,n,i){for(var o=[],s=0,u=e.length;s60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(a,h,c)):c[0]+h+c[1]}function rv(t){return"["+Error.prototype.toString.call(t)+"]"}function nv(t,e,r,n,i,o){var s,u,a;if((a=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?u=a.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):a.set&&(u=t.stylize("[Setter]","special")),Mv(n,i)||(s="["+i+"]"),u||(t.seen.indexOf(a.value)<0?(u=sv(r)?ev(t,a.value,null):ev(t,a.value,r-1)).indexOf("\n")>-1&&(u=o?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n")):u=t.stylize("[Circular]","special")),cv(s)){if(o&&i.match(/^\d+$/))return u;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+u}function iv(t){return Array.isArray(t)}function ov(t){return"boolean"==typeof t}function sv(t){return null===t}function uv(t){return null==t}function av(t){return"number"==typeof t}function hv(t){return"string"==typeof t}function fv(t){return"symbol"==typeof t}function cv(t){return void 0===t}function lv(t){return pv(t)&&"[object RegExp]"===wv(t)}function pv(t){return"object"==typeof t&&null!==t}function dv(t){return pv(t)&&"[object Date]"===wv(t)}function gv(t){return pv(t)&&("[object Error]"===wv(t)||t instanceof Error)}function mv(t){return"function"==typeof t}function yv(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function vv(t){return Buffer.isBuffer(t)}function wv(t){return Object.prototype.toString.call(t)}function bv(t){return t<10?"0"+t.toString(10):t.toString(10)}Zy.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]},Zy.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var _v=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ev(){var t=new Date,e=[bv(t.getHours()),bv(t.getMinutes()),bv(t.getSeconds())].join(":");return[t.getDate(),_v[t.getMonth()],e].join(" ")}function Sv(){console.log("%s - %s",Ev(),$y.apply(null,arguments))}function Iv(t,e){if(!e||!pv(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}function Mv(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Tv={inherits:Wy,_extend:Iv,log:Sv,isBuffer:vv,isPrimitive:yv,isFunction:mv,isError:gv,isDate:dv,isObject:pv,isRegExp:lv,isUndefined:cv,isSymbol:fv,isString:hv,isNumber:av,isNullOrUndefined:uv,isNull:sv,isBoolean:ov,isArray:iv,inspect:Zy,deprecate:zy,format:$y,debuglog:Jy},Ov=Object.freeze({__proto__:null,format:$y,deprecate:zy,debuglog:Jy,inspect:Zy,isArray:iv,isBoolean:ov,isNull:sv,isNullOrUndefined:uv,isNumber:av,isString:hv,isSymbol:fv,isUndefined:cv,isRegExp:lv,isObject:pv,isDate:dv,isError:gv,isFunction:mv,isPrimitive:yv,isBuffer:vv,log:Sv,inherits:Wy,_extend:Iv,default:Tv});function Av(){this.head=null,this.tail=null,this.length=0}Av.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Av.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Av.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Av.prototype.clear=function(){this.head=this.tail=null,this.length=0},Av.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Av.prototype.concat=function(t){if(0===this.length)return M.alloc(0);if(1===this.length)return this.head.data;for(var e=M.allocUnsafe(t>>>0),r=this.head,n=0;r;)r.data.copy(e,n),n+=r.data.length,r=r.next;return e};var Pv=M.isEncoding||function(t){switch(t&&t.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!0;default:return!1}};function kv(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Pv(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Nv;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=xv;break;default:return void(this.write=Rv)}this.charBuffer=new M(6),this.charReceived=0,this.charLength=0}function Rv(t){return t.toString(this.encoding)}function Nv(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function xv(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}kv.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived);var i;n=(e+=t.toString(this.encoding,0,n)).length-1;if((i=e.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},kv.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},kv.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;e+=n.slice(0,r).toString(i)}return e};var Bv=Object.freeze({__proto__:null,StringDecoder:kv});Cv.ReadableState=Uv;var Lv=Jy("stream");function Uv(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof cw&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Av,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new kv(t.encoding),this.encoding=t.encoding)}function Cv(t){if(!(this instanceof Cv))return new Cv(t);this._readableState=new Uv(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),wy.call(this)}function Dv(t,e,r,n,i){var o=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(o)t.emit("error",o);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,jv(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!i){var s=new Error("stream.push() after EOF");t.emit("error",s)}else if(e.endEmitted&&i){var u=new Error("stream.unshift() after end event");t.emit("error",u)}else{var a;!e.decoder||i||n||(r=e.decoder.write(r),a=!e.objectMode&&0===r.length),i||(e.reading=!1),a||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&jv(t))),function(t,e){e.readingMore||(e.readingMore=!0,qy(Gv,t,e))}(t,e)}else i||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=Hv?t=Hv:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function jv(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Lv("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?qy(qv,t):qv(t))}function qv(t){Lv("emit readable"),t.emit("readable"),Vv(t)}function Gv(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;to.length?o.length:t;if(s===o.length?i+=o:i+=o.slice(0,t),0===(t-=s)){s===o.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(s));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var o=n.data,s=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,s),0===(t-=s)){s===o.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=o.slice(s));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function zv(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,qy(Xv,e,t))}function Xv(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Yv(t,e){for(var r=0,n=t.length;r=e.highWaterMark||e.ended))return Lv("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?zv(this):jv(this),null;if(0===(t=Fv(t,e))&&e.ended)return 0===e.length&&zv(this),null;var n,i=e.needReadable;return Lv("need readable",i),(0===e.length||e.length-t0?$v(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&zv(this)),null!==n&&this.emit("data",n),n},Cv.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Cv.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,Lv("pipe count=%d opts=%j",n.pipesCount,e);var i=!e||!1!==e.end?s:h;function o(t){Lv("onunpipe"),t===r&&h()}function s(){Lv("onend"),t.end()}n.endEmitted?qy(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;Lv("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Vv(t))}}(r);t.on("drain",u);var a=!1;function h(){Lv("cleanup"),t.removeListener("close",p),t.removeListener("finish",d),t.removeListener("drain",u),t.removeListener("error",l),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",h),r.removeListener("data",c),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var f=!1;function c(e){Lv("ondata"),f=!1,!1!==t.write(e)||f||((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==Yv(n.pipes,t))&&!a&&(Lv("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,f=!0),r.pause())}function l(e){var r;Lv("onerror",e),g(),t.removeListener("error",l),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function p(){t.removeListener("finish",d),g()}function d(){Lv("onfinish"),t.removeListener("close",p),g()}function g(){Lv("unpipe"),r.unpipe(t)}return r.on("data",c),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",l),t.once("close",p),t.once("finish",d),t.emit("pipe",r),n.flowing||(Lv("pipe resume"),r.resume()),t},Cv.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},tw.prototype._write=function(t,e,r){r(new Error("not implemented"))},tw.prototype._writev=null,tw.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,sw(t,e),r&&(e.finished?qy(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)},Wy(cw,Cv);for(var aw=Object.keys(tw.prototype),hw=0;hw0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r}},{key:"concat",value:function(t){if(0===this.length)return Tw.alloc(0);for(var e=Tw.allocUnsafe(t>>>0),r=this.head,n=0;r;)Pw(r.data,e,n),n+=r.data.length,r=r.next;return e}},{key:"consume",value:function(t,e){var r;return ti.length?i.length:t;if(o===i.length?n+=i:n+=i.slice(0,t),0==(t-=o)){o===i.length?(++r,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(t){var e=Tw.allocUnsafe(t),r=this.head,n=1;for(r.data.copy(e),t-=r.data.length;r=r.next;){var i=r.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,e}},{key:Aw,value:function(t,e){return Ow(this,function(t){for(var e=1;eString(t))),r>2?`one of ${e} ${t.slice(0,r-1).join(", ")}, or `+t[r-1]:2===r?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}return`of ${e} ${String(t)}`}Cw("ERR_INVALID_OPT_VALUE",(function(t,e){return'The value "'+e+'" is invalid for option "'+t+'"'}),TypeError),Cw("ERR_INVALID_ARG_TYPE",(function(t,e,r){let n;var i,o;let s;if("string"==typeof e&&(i="not ",e.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",e=e.replace(/^not /,"")):n="must be",function(t,e,r){return(void 0===r||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}(t," argument"))s=`The ${t} ${n} ${Dw(e,"type")}`;else{const r=function(t,e,r){return"number"!=typeof r&&(r=0),!(r+e.length>t.length)&&-1!==t.indexOf(e,r)}(t,".")?"property":"argument";s=`The "${t}" ${r} ${n} ${Dw(e,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),Cw("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Cw("ERR_METHOD_NOT_IMPLEMENTED",(function(t){return"The "+t+" method is not implemented"})),Cw("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Cw("ERR_STREAM_DESTROYED",(function(t){return"Cannot call "+t+" after a stream was destroyed"})),Cw("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Cw("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Cw("ERR_STREAM_WRITE_AFTER_END","write after end"),Cw("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Cw("ERR_UNKNOWN_ENCODING",(function(t){return"Unknown encoding: "+t}),TypeError),Cw("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Lw.codes=Uw;var Hw=Lw.codes.ERR_INVALID_OPT_VALUE;var Fw,jw={getHighWaterMark:function(t,e,r,n){var i=function(t,e,r){return null!=t.highWaterMark?t.highWaterMark:e?t[r]:null}(e,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Hw(n?r:"highWaterMark",i);return Math.floor(i)}return t.objectMode?16:16384}},qw=Ew.deprecate,Gw=fb;function Kw(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,r){var n=t.entry;t.entry=null;for(;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree.next=t}(e,t)}}fb.WritableState=hb;var Ww={deprecate:qw},Vw=_w,$w=ft.Buffer,zw=r.Uint8Array||function(){};var Xw,Yw=Bw,Jw=jw.getHighWaterMark,Zw=Lw.codes,Qw=Zw.ERR_INVALID_ARG_TYPE,tb=Zw.ERR_METHOD_NOT_IMPLEMENTED,eb=Zw.ERR_MULTIPLE_CALLBACK,rb=Zw.ERR_STREAM_CANNOT_PIPE,nb=Zw.ERR_STREAM_DESTROYED,ib=Zw.ERR_STREAM_NULL_VALUES,ob=Zw.ERR_STREAM_WRITE_AFTER_END,sb=Zw.ERR_UNKNOWN_ENCODING,ub=Yw.errorOrDestroy;function ab(){}function hb(t,e,r){Fw=Fw||vb,t=t||{},"boolean"!=typeof r&&(r=e instanceof Fw),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=Jw(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===t.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new eb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?(process.nextTick(i,n),process.nextTick(mb,t,e),t._writableState.errorEmitted=!0,ub(t,n)):(i(n),t._writableState.errorEmitted=!0,ub(t,n),mb(t,e))}(t,r,n,e,i);else{var o=db(r)||t.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||pb(t,r),n?process.nextTick(lb,t,r,o,i):lb(t,r,o,i)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new Kw(this)}function fb(t){var e=this instanceof(Fw=Fw||vb);if(!e&&!Xw.call(fb,this))return new fb(t);this._writableState=new hb(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),Vw.call(this)}function cb(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new nb("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function lb(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),mb(t,e)}function pb(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),o=e.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,cb(t,e,!0,e.length,i,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new Kw(e),e.bufferedRequestCount=0}else{for(;r;){var a=r.chunk,h=r.encoding,f=r.callback;if(cb(t,e,!1,e.objectMode?1:a.length,a,h,f),r=r.next,e.bufferedRequestCount--,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}function db(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function gb(t,e){t._final((function(r){e.pendingcb--,r&&ub(t,r),e.prefinished=!0,t.emit("prefinish"),mb(t,e)}))}function mb(t,e){var r=db(e);if(r&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,process.nextTick(gb,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var n=t._readableState;(!n||n.autoDestroy&&n.endEmitted)&&t.destroy()}return r}te.exports(fb,Vw),hb.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(hb.prototype,"buffer",{get:Ww.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(Xw=Function.prototype[Symbol.hasInstance],Object.defineProperty(fb,Symbol.hasInstance,{value:function(t){return!!Xw.call(this,t)||this===fb&&(t&&t._writableState instanceof hb)}})):Xw=function(t){return t instanceof this},fb.prototype.pipe=function(){ub(this,new rb)},fb.prototype.write=function(t,e,r){var n,i=this._writableState,o=!1,s=!i.objectMode&&(n=t,$w.isBuffer(n)||n instanceof zw);return s&&!$w.isBuffer(t)&&(t=function(t){return $w.from(t)}(t)),"function"==typeof e&&(r=e,e=null),s?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=ab),i.ending?function(t,e){var r=new ob;ub(t,r),process.nextTick(e,r)}(this,r):(s||function(t,e,r,n){var i;return null===r?i=new ib:"string"==typeof r||e.objectMode||(i=new Qw("chunk",["string","Buffer"],r)),!i||(ub(t,i),process.nextTick(n,i),!1)}(this,i,t,r))&&(i.pendingcb++,o=function(t,e,r,n,i,o){if(!r){var s=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=$w.from(e,r));return e}(e,n,i);n!==s&&(r=!0,i="buffer",n=s)}var u=e.objectMode?1:n.length;e.length+=u;var a=e.length-1))throw new sb(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(fb.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(fb.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),fb.prototype._write=function(t,e,r){r(new tb("_write()"))},fb.prototype._writev=null,fb.prototype.end=function(t,e,r){var n=this._writableState;return"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||function(t,e,r){e.ending=!0,mb(t,e),r&&(e.finished?process.nextTick(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r),this},Object.defineProperty(fb.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(fb.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),fb.prototype.destroy=Yw.destroy,fb.prototype._undestroy=Yw.undestroy,fb.prototype._destroy=function(t,e){e(t)};var yb=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e},vb=Ib,wb=c_,bb=Gw;te.exports(Ib,wb);for(var _b=yb(bb.prototype),Eb=0;Eb<_b.length;Eb++){var Sb=_b[Eb];Ib.prototype[Sb]||(Ib.prototype[Sb]=bb.prototype[Sb])}function Ib(t){if(!(this instanceof Ib))return new Ib(t);wb.call(this,t),bb.call(this,t),this.allowHalfOpen=!0,t&&(!1===t.readable&&(this.readable=!1),!1===t.writable&&(this.writable=!1),!1===t.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",Mb)))}function Mb(){this._writableState.ended||process.nextTick(Tb,this)}function Tb(t){t.end()}Object.defineProperty(Ib.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Ib.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Ib.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Ib.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}});var Ob={},Ab=f.exports.Buffer,Pb=Ab.isEncoding||function(t){switch((t=""+t)&&t.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!0;default:return!1}};function kb(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){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 t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(Ab.isEncoding===Pb||!Pb(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=xb,this.end=Bb,e=4;break;case"utf8":this.fillLast=Nb,e=4;break;case"base64":this.text=Lb,this.end=Ub,e=3;break;default:return this.write=Cb,void(this.end=Db)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Ab.allocUnsafe(e)}function Rb(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function Nb(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function xb(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function Bb(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function Lb(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function Ub(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function Cb(t){return t.toString(this.encoding)}function Db(t){return t&&t.length?this.write(t):""}Ob.StringDecoder=kb,kb.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(t.lastNeed=i-1),i;if(--n=0)return i>0&&(t.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},kb.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};var Hb=Lw.codes.ERR_STREAM_PREMATURE_CLOSE;function Fb(){}var jb,qb=function t(e,r,n){if("function"==typeof r)return t(e,null,r);r||(r={}),n=function(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===d_.prototype||(e=function(t){return d_.from(t)}(e)),n)s.endEmitted?P_(t,new A_):B_(t,s,e,!0);else if(s.ended)P_(t,new T_);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!r?(e=s.decoder.write(e),s.objectMode||0!==e.length?B_(t,s,e,!1):H_(t,s)):B_(t,s,e,!1)}else n||(s.reading=!1,H_(t,s));return!s.ended&&(s.lengthe.highWaterMark&&(e.highWaterMark=function(t){return t>=L_?t=L_:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function C_(t){var e=t._readableState;m_("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(m_("emitReadable",e.flowing),e.emittedReadable=!0,process.nextTick(D_,t))}function D_(t){var e=t._readableState;m_("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,K_(t)}function H_(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(F_,t,e))}function F_(t,e){for(;!e.reading&&!e.ended&&(e.length0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function q_(t){m_("readable nexttick read 0"),t.read(0)}function G_(t,e){m_("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),K_(t),e.flowing&&!e.reading&&t.read(0)}function K_(t){var e=t._readableState;for(m_("flow",e.flowing);e.flowing&&null!==t.read(););}function W_(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r);var r}function V_(t){var e=t._readableState;m_("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick($_,e,t))}function $_(t,e){if(m_("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}function z_(t,e){for(var r=0,n=t.length;r=e.highWaterMark:e.length>0)||e.ended))return m_("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?V_(this):C_(this),null;if(0===(t=U_(t,e))&&e.ended)return 0===e.length&&V_(this),null;var n,i=e.needReadable;return m_("need readable",i),(0===e.length||e.length-t0?W_(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&V_(this)),null!==n&&this.emit("data",n),n},N_.prototype._read=function(t){P_(this,new O_("_read()"))},N_.prototype.pipe=function(t,e){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=t;break;case 1:n.pipes=[n.pipes,t];break;default:n.pipes.push(t)}n.pipesCount+=1,m_("pipe count=%d opts=%j",n.pipesCount,e);var i=(!e||!1!==e.end)&&t!==process.stdout&&t!==process.stderr?s:p;function o(e,i){m_("onunpipe"),e===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,m_("cleanup"),t.removeListener("close",c),t.removeListener("finish",l),t.removeListener("drain",u),t.removeListener("error",f),t.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",h),a=!0,!n.awaitDrain||t._writableState&&!t._writableState.needDrain||u())}function s(){m_("onend"),t.end()}n.endEmitted?process.nextTick(i):r.once("end",i),t.on("unpipe",o);var u=function(t){return function(){var e=t._readableState;m_("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&l_(t,"data")&&(e.flowing=!0,K_(t))}}(r);t.on("drain",u);var a=!1;function h(e){m_("ondata");var i=t.write(e);m_("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===t||n.pipesCount>1&&-1!==z_(n.pipes,t))&&!a&&(m_("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function f(e){m_("onerror",e),p(),t.removeListener("error",f),0===l_(t,"error")&&P_(t,e)}function c(){t.removeListener("finish",l),p()}function l(){m_("onfinish"),t.removeListener("close",c),p()}function p(){m_("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",c),t.once("finish",l),t.emit("pipe",r),n.flowing||(m_("pipe resume"),r.resume()),t},N_.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r)),this;if(!t){var n=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===t&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,m_("on readable",n.length,n.reading),n.length?C_(this):n.reading||process.nextTick(q_,this))),r},N_.prototype.addListener=N_.prototype.on,N_.prototype.removeListener=function(t,e){var r=p_.prototype.removeListener.call(this,t,e);return"readable"===t&&process.nextTick(j_,this),r},N_.prototype.removeAllListeners=function(t){var e=p_.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||process.nextTick(j_,this),e},N_.prototype.resume=function(){var t=this._readableState;return t.flowing||(m_("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(G_,t,e))}(this,t)),t.paused=!1,this},N_.prototype.pause=function(){return m_("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(m_("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},N_.prototype.wrap=function(t){var e=this,r=this._readableState,n=!1;for(var i in t.on("end",(function(){if(m_("wrapped end"),r.decoder&&!r.ended){var t=r.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(m_("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(e.push(i)||(n=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o0,(function(t){n||(n=t),t&&o.forEach(gE),s||(o.forEach(gE),i(n))}))}));return e.reduce(mE)};!function(t,e){var r=ww;"disable"===process.env.READABLE_STREAM&&r?(t.exports=r.Readable,Object.assign(t.exports,r),t.exports.Stream=r):((e=t.exports=c_).Stream=r||e,e.Readable=e,e.Writable=Gw,e.Duplex=vb,e.Transform=X_,e.PassThrough=uE,e.finished=qb,e.pipeline=vE)}(yy,yy.exports);var wE=f.exports.Buffer,bE=yy.exports.Transform;function _E(t){bE.call(this),this._block=wE.allocUnsafe(t),this._blockSize=t,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,te.exports)(_E,bE),_E.prototype._transform=function(t,e,r){var n=null;try{this.update(t,e)}catch(t){n=t}r(n)},_E.prototype._flush=function(t){var e=null;try{this.push(this.digest())}catch(t){e=t}t(e)},_E.prototype.update=function(t,e){if(function(t,e){if(!wE.isBuffer(t)&&"string"!=typeof t)throw new TypeError(e+" must be a string or a buffer")}(t,"Data"),this._finalized)throw new Error("Digest already called");wE.isBuffer(t)||(t=wE.from(t,e));for(var r=this._block,n=0;this._blockOffset+t.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=s,(s=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*s);return this},_E.prototype._update=function(){throw new Error("_update is not implemented")},_E.prototype.digest=function(t){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var e=this._digest();void 0!==t&&(e=e.toString(t)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return e},_E.prototype._digest=function(){throw new Error("_digest is not implemented")};var EE=_E,SE=ft.Buffer,IE=te.exports,ME=EE,TE=new Array(16),OE=[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],AE=[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],PE=[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],kE=[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],RE=[0,1518500249,1859775393,2400959708,2840853838],NE=[1352829926,1548603684,1836072691,2053994217,0];function xE(){ME.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function BE(t,e){return t<>>32-e}function LE(t,e,r,n,i,o,s,u){return BE(t+(e^r^n)+o+s|0,u)+i|0}function UE(t,e,r,n,i,o,s,u){return BE(t+(e&r|~e&n)+o+s|0,u)+i|0}function CE(t,e,r,n,i,o,s,u){return BE(t+((e|~r)^n)+o+s|0,u)+i|0}function DE(t,e,r,n,i,o,s,u){return BE(t+(e&n|r&~n)+o+s|0,u)+i|0}function HE(t,e,r,n,i,o,s,u){return BE(t+(e^(r|~n))+o+s|0,u)+i|0}IE(xE,ME),xE.prototype._update=function(){for(var t=TE,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._a,a=0|this._b,h=0|this._c,f=0|this._d,c=0|this._e,l=0;l<80;l+=1){var p,d;l<16?(p=LE(r,n,i,o,s,t[OE[l]],RE[0],PE[l]),d=HE(u,a,h,f,c,t[AE[l]],NE[0],kE[l])):l<32?(p=UE(r,n,i,o,s,t[OE[l]],RE[1],PE[l]),d=DE(u,a,h,f,c,t[AE[l]],NE[1],kE[l])):l<48?(p=CE(r,n,i,o,s,t[OE[l]],RE[2],PE[l]),d=CE(u,a,h,f,c,t[AE[l]],NE[2],kE[l])):l<64?(p=DE(r,n,i,o,s,t[OE[l]],RE[3],PE[l]),d=UE(u,a,h,f,c,t[AE[l]],NE[3],kE[l])):(p=HE(r,n,i,o,s,t[OE[l]],RE[4],PE[l]),d=LE(u,a,h,f,c,t[AE[l]],NE[4],kE[l])),r=s,s=o,o=BE(i,10),i=n,n=p,u=c,c=f,f=BE(h,10),h=a,a=d}var g=this._b+i+f|0;this._b=this._c+o+c|0,this._c=this._d+s+u|0,this._d=this._e+r+a|0,this._e=this._a+n+h|0,this._a=g},xE.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=SE.alloc?SE.alloc(20):new SE(20);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t.writeInt32LE(this._e,16),t};var FE=xE,jE={exports:{}},qE=f.exports.Buffer;function GE(t,e){this._block=qE.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}GE.prototype.update=function(t,e){"string"==typeof t&&(e=e||"utf8",t=qE.from(t,e));for(var r=this._block,n=this._blockSize,i=t.length,o=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return t?o.toString(t):o},GE.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var KE=GE,WE=te.exports,VE=KE,$E=f.exports.Buffer,zE=[1518500249,1859775393,-1894007588,-899497514],XE=new Array(80);function YE(){this.init(),this._w=XE,VE.call(this,64,56)}function JE(t){return t<<30|t>>>2}function ZE(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}WE(YE,VE),YE.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},YE.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=r[a-3]^r[a-8]^r[a-14]^r[a-16];for(var h=0;h<80;++h){var f=~~(h/20),c=0|((e=n)<<5|e>>>27)+ZE(f,i,o,s)+u+r[h]+zE[f];u=s,s=o,o=JE(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},YE.prototype._hash=function(){var t=$E.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var QE=YE,tS=te.exports,eS=KE,rS=f.exports.Buffer,nS=[1518500249,1859775393,-1894007588,-899497514],iS=new Array(80);function oS(){this.init(),this._w=iS,eS.call(this,64,56)}function sS(t){return t<<5|t>>>27}function uS(t){return t<<30|t>>>2}function aS(t,e,r,n){return 0===t?e&r|~e&n:2===t?e&r|e&n|r&n:e^r^n}tS(oS,eS),oS.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},oS.prototype._update=function(t){for(var e,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,a=0;a<16;++a)r[a]=t.readInt32BE(4*a);for(;a<80;++a)r[a]=(e=r[a-3]^r[a-8]^r[a-14]^r[a-16])<<1|e>>>31;for(var h=0;h<80;++h){var f=~~(h/20),c=sS(n)+aS(f,i,o,s)+u+r[h]+nS[f]|0;u=s,s=o,o=uS(i),i=n,n=c}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},oS.prototype._hash=function(){var t=rS.allocUnsafe(20);return t.writeInt32BE(0|this._a,0),t.writeInt32BE(0|this._b,4),t.writeInt32BE(0|this._c,8),t.writeInt32BE(0|this._d,12),t.writeInt32BE(0|this._e,16),t};var hS=oS,fS=te.exports,cS=KE,lS=f.exports.Buffer,pS=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],dS=new Array(64);function gS(){this.init(),this._w=dS,cS.call(this,64,56)}function mS(t,e,r){return r^t&(e^r)}function yS(t,e,r){return t&e|r&(t|e)}function vS(t){return(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10)}function wS(t){return(t>>>6|t<<26)^(t>>>11|t<<21)^(t>>>25|t<<7)}function bS(t){return(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3}function _S(t){return(t>>>17|t<<15)^(t>>>19|t<<13)^t>>>10}fS(gS,cS),gS.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},gS.prototype._update=function(t){for(var e=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,a=0|this._g,h=0|this._h,f=0;f<16;++f)e[f]=t.readInt32BE(4*f);for(;f<64;++f)e[f]=_S(e[f-2])+e[f-7]+bS(e[f-15])+e[f-16]|0;for(var c=0;c<64;++c){var l=h+wS(s)+mS(s,u,a)+pS[c]+e[c]|0,p=vS(r)+yS(r,n,i)|0;h=a,a=u,u=s,s=o+l|0,o=i,i=n,n=r,r=l+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=a+this._g|0,this._h=h+this._h|0},gS.prototype._hash=function(){var t=lS.allocUnsafe(32);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t.writeInt32BE(this._h,28),t};var ES=gS,SS=te.exports,IS=ES,MS=KE,TS=f.exports.Buffer,OS=new Array(64);function AS(){this.init(),this._w=OS,MS.call(this,64,56)}SS(AS,IS),AS.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},AS.prototype._hash=function(){var t=TS.allocUnsafe(28);return t.writeInt32BE(this._a,0),t.writeInt32BE(this._b,4),t.writeInt32BE(this._c,8),t.writeInt32BE(this._d,12),t.writeInt32BE(this._e,16),t.writeInt32BE(this._f,20),t.writeInt32BE(this._g,24),t};var PS=AS,kS=te.exports,RS=KE,NS=f.exports.Buffer,xS=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],BS=new Array(160);function LS(){this.init(),this._w=BS,RS.call(this,128,112)}function US(t,e,r){return r^t&(e^r)}function CS(t,e,r){return t&e|r&(t|e)}function DS(t,e){return(t>>>28|e<<4)^(e>>>2|t<<30)^(e>>>7|t<<25)}function HS(t,e){return(t>>>14|e<<18)^(t>>>18|e<<14)^(e>>>9|t<<23)}function FS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^t>>>7}function jS(t,e){return(t>>>1|e<<31)^(t>>>8|e<<24)^(t>>>7|e<<25)}function qS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^t>>>6}function GS(t,e){return(t>>>19|e<<13)^(e>>>29|t<<3)^(t>>>6|e<<26)}function KS(t,e){return t>>>0>>0?1:0}kS(LS,RS),LS.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},LS.prototype._update=function(t){for(var e=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,a=0|this._gh,h=0|this._hh,f=0|this._al,c=0|this._bl,l=0|this._cl,p=0|this._dl,d=0|this._el,g=0|this._fl,m=0|this._gl,y=0|this._hl,v=0;v<32;v+=2)e[v]=t.readInt32BE(4*v),e[v+1]=t.readInt32BE(4*v+4);for(;v<160;v+=2){var w=e[v-30],b=e[v-30+1],_=FS(w,b),E=jS(b,w),S=qS(w=e[v-4],b=e[v-4+1]),I=GS(b,w),M=e[v-14],T=e[v-14+1],O=e[v-32],A=e[v-32+1],P=E+T|0,k=_+M+KS(P,E)|0;k=(k=k+S+KS(P=P+I|0,I)|0)+O+KS(P=P+A|0,A)|0,e[v]=k,e[v+1]=P}for(var R=0;R<160;R+=2){k=e[R],P=e[R+1];var N=CS(r,n,i),x=CS(f,c,l),B=DS(r,f),L=DS(f,r),U=HS(s,d),C=HS(d,s),D=xS[R],H=xS[R+1],F=US(s,u,a),j=US(d,g,m),q=y+C|0,G=h+U+KS(q,y)|0;G=(G=(G=G+F+KS(q=q+j|0,j)|0)+D+KS(q=q+H|0,H)|0)+k+KS(q=q+P|0,P)|0;var K=L+x|0,W=B+N+KS(K,L)|0;h=a,y=m,a=u,m=g,u=s,g=d,s=o+G+KS(d=p+q|0,p)|0,o=i,p=l,i=n,l=c,n=r,c=f,r=G+W+KS(f=q+K|0,q)|0}this._al=this._al+f|0,this._bl=this._bl+c|0,this._cl=this._cl+l|0,this._dl=this._dl+p|0,this._el=this._el+d|0,this._fl=this._fl+g|0,this._gl=this._gl+m|0,this._hl=this._hl+y|0,this._ah=this._ah+r+KS(this._al,f)|0,this._bh=this._bh+n+KS(this._bl,c)|0,this._ch=this._ch+i+KS(this._cl,l)|0,this._dh=this._dh+o+KS(this._dl,p)|0,this._eh=this._eh+s+KS(this._el,d)|0,this._fh=this._fh+u+KS(this._fl,g)|0,this._gh=this._gh+a+KS(this._gl,m)|0,this._hh=this._hh+h+KS(this._hl,y)|0},LS.prototype._hash=function(){var t=NS.allocUnsafe(64);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),e(this._gh,this._gl,48),e(this._hh,this._hl,56),t};var WS=LS,VS=te.exports,$S=WS,zS=KE,XS=f.exports.Buffer,YS=new Array(160);function JS(){this.init(),this._w=YS,zS.call(this,128,112)}VS(JS,$S),JS.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},JS.prototype._hash=function(){var t=XS.allocUnsafe(48);function e(e,r,n){t.writeInt32BE(e,n),t.writeInt32BE(r,n+4)}return e(this._ah,this._al,0),e(this._bh,this._bl,8),e(this._ch,this._cl,16),e(this._dh,this._dl,24),e(this._eh,this._el,32),e(this._fh,this._fl,40),t};var ZS=JS,QS=jE.exports=function(t){t=t.toLowerCase();var e=QS[t];if(!e)throw new Error(t+" is not supported (we accept pull requests)");return new e};QS.sha=QE,QS.sha1=hS,QS.sha224=PS,QS.sha256=ES,QS.sha384=ZS,QS.sha512=WS;var tI=jE.exports;function eI(t){return(new FE).update(tI("sha256").update(t).digest()).digest()}var rI,nI=(rI=function(t,e){return rI=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},rI(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}rI(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),iI=function(t,e){this.psbt=t,this.masterFp=e},oI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.spendingCondition=function(t){if(1!=t.length)throw new Error("Expected single key, got "+t.length);return this.singleKeyCondition(t[0])},e.prototype.setInput=function(t,e,r,n,i){if(1!=n.length)throw new Error("Expected single key, got "+n.length);if(1!=i.length)throw new Error("Expected single path, got "+i.length);this.setSingleKeyInput(t,e,r,n[0],i[0])},e.prototype.setOwnOutput=function(t,e,r,n){if(1!=r.length)throw new Error("Expected single key, got "+r.length);if(1!=n.length)throw new Error("Expected single path, got "+n.length);this.setSingleKeyOutput(t,e,r[0],n[0])},e}(iI),sI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=eI(t);return e.writeSlice(Buffer.from([118,169,20])),e.writeSlice(r),e.writeSlice(Buffer.from([136,172])),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"pkh(@0)"},e}(oI),uI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=t.slice(1),r=new py,n=this.getTaprootOutputKey(e);return r.writeSlice(Buffer.from([81,32])),r.writeSlice(n),{scriptPubKey:r.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){var o=n.slice(1);this.psbt.setInputTapBip32Derivation(t,o,[],this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){var i=r.slice(1);this.psbt.setOutputTapBip32Derivation(t,i,[],this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"tr(@0)"},e.prototype.hashTapTweak=function(t){var e=Up.sha256(Buffer.from("TapTweak","utf-8"));return Up.sha256(Buffer.concat([e,e,t]))},e.prototype.getTaprootOutputKey=function(t){if(32!=t.length)throw new Error("Expected 32 byte pubkey. Got "+t.length);var e=Buffer.concat([Buffer.from([2]),t]),r=this.hashTapTweak(t);return Buffer.from(Nt.exports.pointAddScalar(e,r)).slice(1)},e}(oI),aI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=this.createRedeemScript(t),n=eI(r);return e.writeSlice(Buffer.from([169,20])),e.writeSlice(n),e.writeUInt8(135),{scriptPubKey:e.buffer(),redeemScript:r}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i);var o=r.cond.redeemScript,s=this.createRedeemScript(n);if(o&&!s.equals(o))throw new Error("User-supplied redeemScript "+o.toString("hex")+" doesn't\n match expected "+s.toString("hex")+" for input "+t);this.psbt.setInputRedeemScript(t,s),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputRedeemScript(t,e.redeemScript),this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"sh(wpkh(@0))"},e.prototype.createRedeemScript=function(t){var e=eI(t);return Buffer.concat([Buffer.from("0014","hex"),e])},e}(oI),hI=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nI(e,t),e.prototype.singleKeyCondition=function(t){var e=new py,r=eI(t);return e.writeSlice(Buffer.from([0,20])),e.writeSlice(r),{scriptPubKey:e.buffer()}},e.prototype.setSingleKeyInput=function(t,e,r,n,i){if(!e)throw new Error("Full input base transaction required");this.psbt.setInputNonWitnessUtxo(t,e),this.psbt.setInputBip32Derivation(t,n,this.masterFp,i),this.psbt.setInputWitnessUtxo(t,r.amount,r.cond.scriptPubKey)},e.prototype.setSingleKeyOutput=function(t,e,r,n){this.psbt.setOutputBip32Derivation(t,r,this.masterFp,n)},e.prototype.getDescriptorTemplate=function(){return"wpkh(@0)"},e}(oI),fI=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},cI=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=this.leaves.length)throw Error("Index out of bounds");return gI(this.leafNodes[t])},t.prototype.calculateRoot=function(t){var e=t.length;if(0==e)return{root:new dI(void 0,void 0,Buffer.alloc(32,0)),leaves:[]};if(1==e){var r=new dI(void 0,void 0,t[0]);return{root:r,leaves:[r]}}var n=function(t){if(t<2)throw Error("Expected n >= 2");if(function(t){return 0==(t&t-1)}(t))return t/2;return 1<>8&255,r}var n=Buffer.alloc(5);return n[0]=254,n[1]=255&t,n[2]=t>>8&255,n[3]=t>>16&255,n[4]=t>>24&255,n}function FI(t){var e=t.outputs,r=Buffer.alloc(0);return void 0!==e&&(r=Buffer.concat([r,HI(e.length)]),e.forEach((function(t){r=Buffer.concat([r,t.amount,HI(t.script.length),t.script])}))),r}function jI(t,e,r,n){void 0===n&&(n=[]);var i=n.includes("decred"),o=n.includes("bech32"),s=Buffer.alloc(0),u=void 0!==t.witness&&!e;t.inputs.forEach((function(t){s=i||o?Buffer.concat([s,t.prevout,Buffer.from([0]),t.sequence]):Buffer.concat([s,t.prevout,HI(t.script.length),t.script,t.sequence])}));var a=FI(t);return void 0!==t.outputs&&void 0!==t.locktime&&(a=Buffer.concat([a,u&&t.witness||Buffer.alloc(0),t.locktime,t.nExpiryHeight||Buffer.alloc(0),t.extraData||Buffer.alloc(0)])),Buffer.concat([t.version,r||Buffer.alloc(0),t.nVersionGroupId||Buffer.alloc(0),u?Buffer.from("0001","hex"):Buffer.alloc(0),HI(t.inputs.length),s,a])}var qI=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},GI=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=0;e--)if(t[e]>=2147483648)return t.slice(0,e+1);return[]}(t),n.length+2!=t.length?[2,""]:[4,this.client.getExtendedPubkey(!1,n)];case 1:return i=a.sent(),[4,this.client.getMasterFingerprint()];case 2:return o=a.sent(),s=new mI(e,yI(o,n,i)),u=t.slice(-2,t.length),[2,this.client.getWalletAddress(s,Buffer.alloc(32,0),u[0],u[1],r)]}}))}))},t.prototype.createPaymentTransactionNew=function(t){return qI(this,void 0,void 0,(function(){var e,r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I;return GI(this,(function(M){switch(M.label){case 0:if(0==(e=t.inputs.length))throw Error("No inputs");return r=new MI,[4,this.client.getMasterFingerprint()];case 1:n=M.sent(),i=function(t,e,r){return t.additionals.includes("bech32m")?new uI(e,r):t.additionals.includes("bech32")?new hI(e,r):t.segwit?new aI(e,r):new sI(e,r)}(t,r,n),t.lockTime&&r.setGlobalFallbackLocktime(t.lockTime),r.setGlobalInputCount(e),r.setGlobalPsbtVersion(2),r.setGlobalTxVersion(2),o=0,s=function(){t.onDeviceStreaming&&t.onDeviceStreaming({total:2*e,index:o,progress:++o/(2*e)})},u="",a=[],g=0,M.label=2;case 2:return g0){if(n.length>1)throw Error("Expected exactly one signature, got "+n.length);if(i)throw Error("Both taproot and non-taproot signatures present.");var o=!!t.getInputWitnessUtxo(r),s=t.getInputRedeemScript(r),u=!!s;if(!(f=t.getInputPartialSig(r,n[0])))throw new Error("Expected partial signature for input "+r);if(o){if((c=new py).writeVarInt(2),c.writeVarInt(f.length),c.writeSlice(f),c.writeVarInt(n[0].length),c.writeSlice(n[0]),t.setInputFinalScriptwitness(r,c.buffer()),u){if(!s||0==s.length)throw new Error("Expected non-empty redeemscript. Can't finalize intput "+r);var a=new py;a.writeUInt8(s.length),a.writeSlice(s),t.setInputFinalScriptsig(r,a.buffer())}}else{var h=new py;CI(h,f),CI(h,n[0]),t.setInputFinalScriptsig(r,h.buffer())}}else{var f,c;if(!(f=t.getInputTapKeySig(r)))throw Error("No taproot signature found");if(64!=f.length&&65!=f.length)throw Error("Unexpected length of schnorr signature.");(c=new py).writeVarInt(1),c.writeVarSlice(f),t.setInputFinalScriptwitness(r,c.buffer())}UI(t,r)}}(r),I=function(t){var e,r,n=new py;n.writeUInt32(t.getGlobalTxVersion());var i=!!t.getInputWitnessUtxo(0);i&&n.writeSlice(Buffer.from([0,1]));var o=t.getGlobalInputCount();n.writeVarInt(o);for(var s=new py,u=0;u0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function aM(t,e,r){return oM(this,void 0,void 0,(function(){var n,i,o,s;return sM(this,(function(u){switch(u.label){case 0:return i=!1,"number"==typeof r?(i=!0,(o=Buffer.alloc(4)).writeUInt32BE(r,0),n=Buffer.concat([o,e],e.length+4)):n=e,[4,t.send(224,66,i?0:128,0,n)];case 1:return s=u.sent(),[2,s.slice(0,s.length-2).toString("hex")]}}))}))}function hM(t,e,r,n){return void 0===n&&(n=[]),oM(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N=this;return sM(this,(function(x){switch(x.label){case 0:if(i=r.version,o=r.inputs,s=r.outputs,u=r.locktime,a=r.nExpiryHeight,h=r.extraData,!s||!u)throw new Error("getTrustedInput: locktime & outputs is expected");return f=n.includes("decred"),c=n.includes("stealthcoin"),l=function(e,r){return oM(N,void 0,void 0,(function(){var n,i,o,s,u,a,h,f,c,l,p;return sM(this,(function(d){switch(d.label){case 0:for(n=r||Buffer.alloc(0),i=[],o=0;o!==e.length;)s=e.length-o>gy?gy:e.length-o,o+s!==e.length?i.push(e.slice(o,o+s)):i.push(Buffer.concat([e.slice(o,o+s),n])),o+=s;0===e.length&&i.push(n),d.label=1;case 1:d.trys.push([1,6,7,8]),a=uM(i),h=a.next(),d.label=2;case 2:return h.done?[3,5]:(f=h.value,[4,aM(t,f)]);case 3:u=d.sent(),d.label=4;case 4:return h=a.next(),[3,2];case 5:return[3,8];case 6:return c=d.sent(),l={error:c},[3,8];case 7:try{h&&!h.done&&(p=a.return)&&p.call(a)}finally{if(l)throw l.error}return[7];case 8:return[2,u]}}))}))},p=function(e){return aM(t,e)},[4,aM(t,Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),HI(o.length)]),e)];case 1:x.sent(),x.label=2;case 2:x.trys.push([2,8,9,10]),d=uM(o),g=d.next(),x.label=3;case 3:return g.done?[3,7]:(m=g.value,y=c&&0===Buffer.compare(i,Buffer.from([2,0,0,0])),v=f?m.tree||Buffer.from([0]):Buffer.alloc(0),T=Buffer.concat([m.prevout,v,y?Buffer.from([0]):HI(m.script.length)]),[4,aM(t,T)]);case 4:return x.sent(),[4,f?p(Buffer.concat([m.script,m.sequence])):y?p(m.sequence):l(m.script,m.sequence)];case 5:x.sent(),x.label=6;case 6:return g=d.next(),[3,3];case 7:return[3,10];case 8:return w=x.sent(),A={error:w},[3,10];case 9:try{g&&!g.done&&(P=d.return)&&P.call(d)}finally{if(A)throw A.error}return[7];case 10:return[4,aM(t,HI(s.length))];case 11:x.sent(),x.label=12;case 12:x.trys.push([12,17,18,19]),b=uM(s),_=b.next(),x.label=13;case 13:return _.done?[3,16]:(E=_.value,T=Buffer.concat([E.amount,f?Buffer.from([0,0]):Buffer.alloc(0),HI(E.script.length),E.script]),[4,aM(t,T)]);case 14:x.sent(),x.label=15;case 15:return _=b.next(),[3,13];case 16:return[3,19];case 17:return S=x.sent(),k={error:S},[3,19];case 18:try{_&&!_.done&&(R=b.return)&&R.call(b)}finally{if(k)throw k.error}return[7];case 19:return I=[],a&&a.length>0&&I.push(a),h&&h.length>0&&I.push(h),I.length&&(T=Buffer.concat(I),M=f?T:Buffer.concat([HI(T.length),T])),[4,l(Buffer.concat([u,M||Buffer.alloc(0)]))];case 20:return O=x.sent(),iM(O,"missing result in processScriptBlocks"),[2,O]}}))}))}var fM=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},cM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function pM(t,e,r,n,i,o,s){void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]);var u=s.includes("cashaddr")?3:i?s.includes("sapling")?5:o?4:2:0;return t.send(224,68,r?0:128,e?u:128,n)}function dM(t,e,r,n,i,o,s,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===s&&(s=[]),void 0===u&&(u=!1),fM(this,void 0,void 0,(function(){var a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O;return cM(this,(function(A){switch(A.label){case 0:return a=Buffer.concat([r.version,r.timestamp||Buffer.alloc(0),r.nVersionGroupId||Buffer.alloc(0),HI(r.inputs.length)]),[4,pM(t,e,!0,a,i,o,s)];case 1:A.sent(),h=0,f=s.includes("decred"),A.label=2;case 2:A.trys.push([2,15,16,17]),c=lM(r.inputs),l=c.next(),A.label=3;case 3:return l.done?[3,14]:(p=l.value,d=void 0,g=n[h].value,d=i?u&&n[h].trustedInput?Buffer.from([1,g.length]):Buffer.from([2]):n[h].trustedInput?Buffer.from([1,n[h].value.length]):Buffer.from([0]),a=Buffer.concat([d,g,f?Buffer.from([0]):Buffer.alloc(0),HI(p.script.length)]),[4,pM(t,e,!1,a,i,o,s)]);case 4:if(A.sent(),m=[],y=0,0===p.script.length)m.push(p.sequence);else for(;y!==p.script.length;)v=p.script.length-y>gy?gy:p.script.length-y,y+v!==p.script.length?m.push(p.script.slice(y,y+v)):m.push(Buffer.concat([p.script.slice(y,y+v),p.sequence])),y+=v;A.label=5;case 5:A.trys.push([5,10,11,12]),T=void 0,w=lM(m),b=w.next(),A.label=6;case 6:return b.done?[3,9]:(_=b.value,[4,pM(t,e,!1,_,i,o,s)]);case 7:A.sent(),A.label=8;case 8:return b=w.next(),[3,6];case 9:return[3,12];case 10:return E=A.sent(),T={error:E},[3,12];case 11:try{b&&!b.done&&(O=w.return)&&O.call(w)}finally{if(T)throw T.error}return[7];case 12:h++,A.label=13;case 13:return l=c.next(),[3,3];case 14:return[3,17];case 15:return S=A.sent(),I={error:S},[3,17];case 16:try{l&&!l.done&&(M=c.return)&&M.call(c)}finally{if(I)throw I.error}return[7];case 17:return[2]}}))}))}function gM(t,e,r,n){if(void 0===n&&(n=[]),!r)throw new Error("getTrustedInputBIP143: missing tx");if(n.includes("decred"))throw new Error("Decred does not implement BIP143");var i=tI("sha256").update(tI("sha256").update(jI(r,!0)).digest()).digest(),o=Buffer.alloc(4);o.writeUInt32LE(e,0);var s=r.outputs,u=r.locktime;if(!s||!u)throw new Error("getTrustedInputBIP143: locktime & outputs is expected");if(!s[e])throw new Error("getTrustedInputBIP143: wrong index");return(i=Buffer.concat([i,o,s[e].amount])).toString("hex")}function mM(t,e,r,n,i,o){void 0===o&&(o=[]);var s=o.includes("decred"),u=bt(e),a=Buffer.alloc(4);a.writeUInt32BE(r,0);var h=s?Buffer.concat([u,a,i||Buffer.from([0,0,0,0]),Buffer.from([n])]):Buffer.concat([u,Buffer.from([0]),a,Buffer.from([n])]);return i&&!s&&(h=Buffer.concat([h,i])),t.send(224,72,0,0,h).then((function(t){return t.length>0?(t[0]=48,t.slice(0,t.length-2)):t}))}var yM=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=e.length?e.length-n:gy,s=n+o===e.length?128:0,u=e.slice(n,n+o),[4,t.send(224,74,s,0,u)]):[3,3];case 2:return a.sent(),n+=o,[3,1];case 3:return[2]}}))}))}var _M=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},EM=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},AM={lockTime:0,sigHashType:1,segwit:!1,additionals:[],onDeviceStreaming:function(t){},onDeviceSignatureGranted:function(){},onDeviceSignatureRequested:function(){}};function PM(t,e){return MM(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N,x,B,L,U,C,D,H,F,j,q,G,K,W,V,$,z,X,Y,J,Z,Q,tt,et,rt,nt,it,ot,st,ut,at;return TM(this,(function(ht){switch(ht.label){case 0:if(r=IM(IM({},AM),e),n=r.inputs,i=r.associatedKeysets,o=r.changePath,s=r.outputScriptHex,u=r.lockTime,a=r.sigHashType,h=r.segwit,f=r.initialTimestamp,c=r.additionals,l=r.expiryHeight,p=r.onDeviceStreaming,d=r.onDeviceSignatureGranted,g=r.onDeviceSignatureRequested,void 0!==(m=r.useTrustedInputForSegwit))return[3,4];ht.label=1;case 1:return ht.trys.push([1,3,,4]),[4,SM(t)];case 2:return y=ht.sent(),m=function(t){var e=t.version,r=t.name;return"Decred"!==r&&("Exchange"===r||ly.gte(e,"1.4.0"))}(y),[3,4];case 3:if(27904!==(v=ht.sent()).statusCode)throw v;return m=!1,[3,4];case 4:w=function(t,e){var r=n.length;if(!(r<3)){var i=r*t+e,o=2*r;p({progress:i/o,total:o,index:i})}},b=c.includes("decred"),_=c.includes("stealthcoin"),E=Date.now(),S=c.includes("sapling"),I=h&&c.includes("bech32"),M=h||!!c&&(c.includes("abc")||c.includes("gold")||c.includes("bip143"))||!!l&&!b,T=Buffer.alloc(0),O=Buffer.alloc(0),A=Buffer.alloc(4),l&&!b?A.writeUInt32LE(S?2147483652:2147483651,0):_?A.writeUInt32LE(2,0):A.writeUInt32LE(1,0),P=[],k=[],R=[],N=[],x=!0,B=!1,L={inputs:[],version:A,timestamp:Buffer.alloc(0)},U=M&&!m?gM:hM,C=Buffer.from(s,"hex"),w(0,0),ht.label=5;case 5:ht.trys.push([5,11,12,13]),D=OM(n),H=D.next(),ht.label=6;case 6:return H.done?[3,10]:($=H.value,B?[3,8]:[4,U(t,$[1],$[0],c)]);case 7:F=ht.sent(),XI("hw","got trustedInput="+F),(j=Buffer.alloc(4)).writeUInt32LE($.length>=4&&"number"==typeof $[3]?$[3]:my,0),P.push({trustedInput:!0,value:Buffer.from(F,"hex"),sequence:j}),ht.label=8;case 8:q=$[0].outputs,G=$[1],q&&G<=q.length-1&&k.push(q[G]),l&&!b?(L.nVersionGroupId=Buffer.from(S?[133,32,47,137]:[112,130,196,3]),L.nExpiryHeight=l,L.extraData=Buffer.from(S?[0,0,0,0,0,0,0,0,0,0,0]:[0])):b&&(L.nExpiryHeight=l),ht.label=9;case 9:return H=D.next(),[3,6];case 10:return[3,13];case 11:return K=ht.sent(),ut={error:K},[3,13];case 12:try{H&&!H.done&&(at=D.return)&&at.call(D)}finally{if(ut)throw ut.error}return[7];case 13:if(L.inputs=n.map((function(t){var e=Buffer.alloc(4);return e.writeUInt32LE(t.length>=4&&"number"==typeof t[3]?t[3]:my,0),{script:T,prevout:O,sequence:e}})),B)return[3,18];W=[],it=0,ht.label=14;case 14:return it=3&&"string"==typeof $[2]?Buffer.from($[2],"hex"):h?Buffer.concat([Buffer.from([118,169,20]),eI(N[it]),Buffer.from([136,172])]):k[it].script,X=Object.assign({},L),Y=M?[P[it]]:P,M?X.inputs=[IM(IM({},X.inputs[it]),{script:z})]:X.inputs[it].script=z,[4,dM(t,!M&&x,X,Y,M,!!l&&!b,c,m)]):[3,34];case 27:return ht.sent(),M?[3,31]:B||!o?[3,29]:[4,wM(t,o)];case 28:ht.sent(),ht.label=29;case 29:return[4,bM(t,C,c)];case 30:ht.sent(),ht.label=31;case 31:return x&&(d(),w(1,0)),[4,mM(t,i[it],u,a,l,c)];case 32:J=ht.sent(),w(1,it+1),R.push(J),L.inputs[it].script=T,x&&(x=!1),ht.label=33;case 33:return it++,[3,26];case 34:for(it=0;it0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},UM={lockTime:0,sigHashType:1,segwit:!1,transactionVersion:1};function CM(t,e){return xM(this,void 0,void 0,(function(){var r,n,i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S,I,M,T,O,A,P,k,R,N,x,B,L;return BM(this,(function(U){switch(U.label){case 0:r=NM(NM({},UM),e),n=r.inputs,i=r.associatedKeysets,o=r.outputScriptHex,s=r.lockTime,u=r.sigHashType,a=r.segwit,h=r.transactionVersion,f=Buffer.alloc(0),c=Buffer.alloc(0),(l=Buffer.alloc(4)).writeUInt32LE(h,0),p=[],d=[],g=[],m=!0,y=!1,v={inputs:[],version:l},w=a?gM:hM,b=Buffer.from(o,"hex"),U.label=1;case 1:U.trys.push([1,7,8,9]),_=LM(n),E=_.next(),U.label=2;case 2:return E.done?[3,6]:(P=E.value,y?[3,4]:[4,w(t,P[1],P[0])]);case 3:S=U.sent(),(O=Buffer.alloc(4)).writeUInt32LE(P.length>=4&&"number"==typeof P[3]?P[3]:my,0),p.push({trustedInput:!1,value:a?Buffer.from(S,"hex"):Buffer.from(S,"hex").slice(4,40),sequence:O}),U.label=4;case 4:I=P[0].outputs,M=P[1],I&&M<=I.length-1&&d.push(I[M]),U.label=5;case 5:return E=_.next(),[3,2];case 6:return[3,9];case 7:return T=U.sent(),B={error:T},[3,9];case 8:try{E&&!E.done&&(L=_.return)&&L.call(_)}finally{if(B)throw B.error}return[7];case 9:for(A=0;A=4&&"number"==typeof n[A][3]?n[A][3]:my,0),v.inputs.push({script:f,prevout:c,sequence:O});return a?[4,dM(t,!0,v,p,!0)]:[3,12];case 10:return U.sent(),[4,bM(t,b)];case 11:U.sent(),U.label=12;case 12:A=0,U.label=13;case 13:return A=3&&"string"==typeof P[2]?Buffer.from(P[2],"hex"):d[A].script,R=Object.assign({},v),N=a?[p[A]]:p,a?R.inputs=[NM(NM({},R.inputs[A]),{script:k})]:R.inputs[A].script=k,[4,dM(t,!a&&m,R,N,a)]):[3,19];case 14:return U.sent(),a?[3,16]:[4,bM(t,b)];case 15:U.sent(),U.label=16;case 16:return[4,mM(t,i[A],s,u)];case 17:x=U.sent(),g.push(a?x.toString("hex"):x.slice(0,x.length-1).toString("hex")),v.inputs[A].script=f,m&&(m=!1),U.label=18;case 18:return A++,[3,13];case 19:return[2,g]}}))}))}var DM=function(){return DM=Object.assign||function(t){for(var e,r=1,n=arguments.length;r0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]i.length?i.length-o:r,s=Buffer.alloc(0===o?1+4*e.length+2+n:n),0===o?(s[0]=e.length,e.forEach((function(t,e){s.writeUInt32BE(t,1+4*e)})),s.writeUInt16BE(i.length,1+4*e.length),i.copy(s,1+4*e.length+2,o,o+n)):i.copy(s,0,o,o+n),[4,t.send(224,78,0,0===o?1:128,s)];case 1:return u.sent(),o+=n,[2]}}))},l.label=1;case 1:return o===i.length?[3,3]:[5,s()];case 2:return l.sent(),[3,1];case 3:return[4,t.send(224,78,128,0,Buffer.from([0]))];case 4:return a=l.sent(),h=a[0]-48,0===(f=a.slice(4,4+a[3]))[0]&&(f=f.slice(1)),f=f.toString("hex"),o=4+a[3]+2,0===(c=a.slice(o,o+a[o-1]))[0]&&(c=c.slice(1)),c=c.toString("hex"),[2,{v:h,r:f,s:c}]}}))}))}(this.transport,{path:t,messageHex:e})},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),PM(this.transport,t)},t.prototype.signP2SHTransaction=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."),CM(this.transport,t)},t}();function qM(t){var e=Buffer.allocUnsafe(4);return e.writeUInt32BE(t,0),e}var GM=function(t){return Buffer.concat([Buffer.from([2+(1&t[64])]),t.slice(1,33)])};function KM(t){return tI("sha256").update(t).digest()}var WM,VM=function(){function t(t,e){if(t.length!=e.length)throw new Error("keys and values should have the same length");for(var r=0;r=t[r+1].toString("hex"))throw new Error("keys must be in strictly increasing order");this.keys=t,this.keysTree=new lI(t.map((function(t){return pI(t)}))),this.values=e,this.valuesTree=new lI(e.map((function(t){return pI(t)})))}return t.prototype.commitment=function(){return Buffer.concat([HI(this.keys.length),this.keysTree.getRoot(),this.valuesTree.getRoot()])},t}(),$M=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),zM=function(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},XM=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},QM=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.YIELD=16]="YIELD",t[t.GET_PREIMAGE=64]="GET_PREIMAGE",t[t.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",t[t.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",t[t.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS"}(WM||(WM={}));var eT,rT,nT=function(){},iT=function(t){function e(e,r){var n=t.call(this)||this;return n.progressCallback=r,n.code=WM.YIELD,n.results=e,n}return JM(e,t),e.prototype.execute=function(t){return this.results.push(Buffer.from(t.subarray(1))),this.progressCallback(),Buffer.from("")},e}(nT),oT=function(t){function e(e,r){var n=t.call(this)||this;return n.code=WM.GET_PREIMAGE,n.known_preimages=e,n.queue=r,n}return JM(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(33!=e.length)throw new Error("Invalid request, unexpected trailing data");if(0!=e[0])throw new Error("Unsupported request, the first byte should be 0");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e[1+n];var i=r.toString("hex"),o=this.known_preimages.get(i);if(null!=o){var s=HI(o.length),u=255-s.length-1,a=Math.min(u,o.length);if(a=n||u.size()!=n)throw Error("Invalid index or tree size.");if(0!=this.queue.length)throw Error("This command should not execute when the queue is not empty.");var a=u.getProof(i),h=Math.min(Math.floor(221/32),a.length),f=a.length-h;return f>0&&(e=this.queue).push.apply(e,QM([],ZM(a.slice(-f)),!1)),Buffer.concat(QM([u.getLeafHash(i),Buffer.from([a.length]),Buffer.from([h])],ZM(a.slice(0,h)),!1))},e}(nT),uT=function(t){function e(e){var r=t.call(this)||this;return r.code=WM.GET_MERKLE_LEAF_INDEX,r.known_trees=e,r}return JM(e,t),e.prototype.execute=function(t){var e=t.subarray(1);if(64!=e.length)throw new Error("Invalid request, unexpected trailing data");for(var r=Buffer.alloc(32),n=0;n<32;n++)r[n]=e.readUInt8(n);var i=r.toString("hex"),o=Buffer.alloc(32);for(n=0;n<32;n++)o[n]=e.readUInt8(32+n);var s=o.toString("hex"),u=this.known_trees.get(i);if(!u)throw Error("Requested Merkle leaf index for unknown root: "+i);var a=0,h=0;for(n=0;n0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};!function(t){t[t.GET_PUBKEY=0]="GET_PUBKEY",t[t.REGISTER_WALLET=2]="REGISTER_WALLET",t[t.GET_WALLET_ADDRESS=3]="GET_WALLET_ADDRESS",t[t.SIGN_PSBT=4]="SIGN_PSBT",t[t.GET_MASTER_FINGERPRINT=5]="GET_MASTER_FINGERPRINT"}(eT||(eT={})),function(t){t[t.CONTINUE_INTERRUPTED=1]="CONTINUE_INTERRUPTED"}(rT||(rT={}));var pT=function(){function t(t){this.transport=t}return t.prototype.makeRequest=function(t,e,r){return fT(this,void 0,void 0,(function(){var n,i,o;return cT(this,(function(s){switch(s.label){case 0:return[4,this.transport.send(225,t,0,0,e,[36864,57344])];case 1:n=s.sent(),s.label=2;case 2:if(57344!==n.readUInt16BE(n.length-2))return[3,4];if(!r)throw new Error("Unexpected SW_INTERRUPTED_EXECUTION");return i=n.slice(0,-2),o=r.execute(i),[4,this.transport.send(248,rT.CONTINUE_INTERRUPTED,0,0,o,[36864,57344])];case 3:return n=s.sent(),[3,2];case 4:return[2,n.slice(0,-2)]}}))}))},t.prototype.getExtendedPubkey=function(t,e){return fT(this,void 0,void 0,(function(){return cT(this,(function(r){switch(r.label){case 0:if(e.length>6)throw new Error("Path too long. At most 6 levels allowed.");return[4,this.makeRequest(eT.GET_PUBKEY,Buffer.concat([Buffer.from(t?[1]:[0]),wt(e)]))];case 1:return[2,r.sent().toString("ascii")]}}))}))},t.prototype.getWalletAddress=function(t,e,r,n,i){return fT(this,void 0,void 0,(function(){var o,s;return cT(this,(function(u){switch(u.label){case 0:if(0!==r&&1!==r)throw new Error("Change can only be 0 or 1");if(n<0||!Number.isInteger(n))throw new Error("Invalid address index");if(null!=e&&32!=e.length)throw new Error("Invalid HMAC length");return(o=new hT((function(){}))).addKnownList(t.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(t.serialize()),(s=Buffer.alloc(4)).writeUInt32BE(n,0),[4,this.makeRequest(eT.GET_WALLET_ADDRESS,Buffer.concat([Buffer.from(i?[1]:[0]),t.getWalletId(),e||Buffer.alloc(32,0),Buffer.from([r]),s]),o)];case 1:return[2,u.sent().toString("ascii")]}}))}))},t.prototype.signPsbt=function(t,e,r,n){return fT(this,void 0,void 0,(function(){var i,o,s,u,a,h,f,c,l,p,d,g,m,y,v,w,b,_,E,S;return cT(this,(function(I){switch(I.label){case 0:if(i=new YM(t),null!=r&&32!=r.length)throw new Error("Invalid HMAC length");(o=new hT(n)).addKnownList(e.keys.map((function(t){return Buffer.from(t,"ascii")}))),o.addKnownPreimage(e.serialize()),o.addKnownMapping(i.globalMerkleMap);try{for(s=lT(i.inputMerkleMaps),u=s.next();!u.done;u=s.next())f=u.value,o.addKnownMapping(f)}catch(t){v={error:t}}finally{try{u&&!u.done&&(w=s.return)&&w.call(s)}finally{if(v)throw v.error}}try{for(a=lT(i.outputMerkleMaps),h=a.next();!h.done;h=a.next())f=h.value,o.addKnownMapping(f)}catch(t){b={error:t}}finally{try{h&&!h.done&&(_=a.return)&&_.call(a)}finally{if(b)throw b.error}}return o.addKnownList(i.inputMapCommitments),c=new lI(i.inputMapCommitments.map((function(t){return pI(t)}))).getRoot(),o.addKnownList(i.outputMapCommitments),l=new lI(i.outputMapCommitments.map((function(t){return pI(t)}))).getRoot(),[4,this.makeRequest(eT.SIGN_PSBT,Buffer.concat([i.getGlobalKeysValuesRoot(),HI(i.getGlobalInputCount()),c,HI(i.getGlobalOutputCount()),l,e.getWalletId(),r||Buffer.alloc(32,0)]),o)];case 1:I.sent(),p=o.getYielded(),d=new Map;try{for(g=lT(p),m=g.next();!m.done;m=g.next())y=m.value,d.set(y[0],y.slice(1))}catch(t){E={error:t}}finally{try{m&&!m.done&&(S=g.return)&&S.call(g)}finally{if(E)throw E.error}}return[2,d]}}))}))},t.prototype.getMasterFingerprint=function(){return fT(this,void 0,void 0,(function(){return cT(this,(function(t){return[2,this.makeRequest(eT.GET_MASTER_FINGERPRINT,Buffer.from([]))]}))}))},t}();var dT=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},gT=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]2||"boolean"==typeof e?(console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"),r={verify:!!e,format:arguments[2]?"p2sh":"legacy"}):r=e||{},this.getCorrectImpl().then((function(e){return!(e instanceof WI&&"bech32m"!=r.format)||r.verify&&0!=r.verify||yT(t)?e.getWalletPublicKey(t,r):(console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."),n.old().getWalletPublicKey(t,r))}))},t.prototype.signMessageNew=function(t,e){return this.old().signMessageNew(t,e)},t.prototype.createPaymentTransactionNew=function(t){return arguments.length>1&&console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."),this.getCorrectImpl().then((function(e){return e.createPaymentTransactionNew(t)}))},t.prototype.signP2SHTransaction=function(t){return this.old().signP2SHTransaction(t)},t.prototype.splitTransaction=function(t,e,r,n,i){return void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]),function(t,e,r,n,i){void 0===e&&(e=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===i&&(i=[]);var o=[],s=[],u=!1,a=0,h=Buffer.alloc(0),f=Buffer.alloc(0),c=Buffer.alloc(0),l=Buffer.alloc(0),p=i.includes("decred"),d=i.includes("peercoin"),g=Buffer.from(t,"hex"),m=g.slice(a,a+4),y=m.equals(Buffer.from([3,0,0,128]))||m.equals(Buffer.from([4,0,0,128])),v=m.equals(Buffer.from([1,0,0,0]))||m.equals(Buffer.from([2,0,0,0]));a+=4,!r&&e&&0===g[a]&&0!==g[a+1]&&(a+=2,u=!0),r&&(!d||d&&v)&&(h=g.slice(a,4+a),a+=4),y&&(c=g.slice(a,4+a),a+=4);var w=DI(g,a),b=w[0];a+=w[1];for(var _=0;_=2}(t),e?[2,this.new()]:[2,this.old()]}}))}))},t.prototype.old=function(){return new jM(this.transport)},t.prototype.new=function(){return new WI(new pT(this.transport))},t}();function yT(t){var e=2147483648,r=Et(t),n=function(t){return t>=e},i=function(t){return!t||t=3&&r.length<=5&&[44+e,49+e,84+e,86+e].some((function(t){return t==r[0]}))&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&o(r[3])&&i(r[4]))||!!(r.length>=4&&r.length<=6&&48+e==r[0]&&[0+e,1+e].some((function(t){return t==r[1]}))&&n(r[2])&&n(r[3])&&o(r[4])&&i(r[5]))}var vT=Object.freeze({__proto__:null,default:mT}),wT=function(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},bT={},_T={},ET=function(t,e){_T[t]=e},ST=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,bT[t]=e,e},IT=function(t){if("object"==typeof t&&t){try{var e=JSON.parse(t.message);e.message&&e.name&&(t=e)}catch(t){}var r=void 0;if("string"==typeof t.name){var n=t.name,i=_T[n];if(i)r=i(t);else{var o="Error"===n?Error:bT[n];o||(console.warn("deserializing an unknown class '"+n+"'"),o=ST(n)),r=Object.create(o.prototype);try{for(var s in t)t.hasOwnProperty(s)&&(r[s]=t[s])}catch(t){}}}else r=new Error(t.message);return!r.stack&&Error.captureStackTrace&&Error.captureStackTrace(r,IT),r}return new Error(String(t))};function MT(t,e){var r,n,i={};e.push(t);try{for(var o=wT(Object.keys(t)),s=o.next();!s.done;s=o.next()){var u=s.value,a=t[u];"function"!=typeof a&&(a&&"object"==typeof a?-1!==e.indexOf(t[u])?i[u]="[Circular]":i[u]=MT(t[u],e.slice(0)):i[u]=a)}}catch(t){r={error:t}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return"string"==typeof t.name&&(i.name=t.name),"string"==typeof t.message&&(i.message=t.message),"string"==typeof t.stack&&(i.stack=t.stack),i}var TT=ST("AccountNameRequired"),OT=ST("AccountNotSupported"),AT=ST("AmountRequired"),PT=ST("BluetoothRequired"),kT=ST("BtcUnmatchedApp"),RT=ST("CantOpenDevice"),NT=ST("CashAddrNotSupported"),xT=ST("CurrencyNotSupported"),BT=ST("DeviceAppVerifyNotSupported"),LT=ST("DeviceGenuineSocketEarlyClose"),UT=ST("DeviceNotGenuine"),CT=ST("DeviceOnDashboardExpected"),DT=ST("DeviceOnDashboardUnexpected"),HT=ST("DeviceInOSUExpected"),FT=ST("DeviceHalted"),jT=ST("DeviceNameInvalid"),qT=ST("DeviceSocketFail"),GT=ST("DeviceSocketNoBulkStatus"),KT=ST("DisconnectedDevice"),WT=ST("DisconnectedDeviceDuringOperation"),VT=ST("EnpointConfig"),$T=ST("EthAppPleaseEnableContractData"),zT=ST("FeeEstimationFailed"),XT=ST("FirmwareNotRecognized"),YT=ST("HardResetFail"),JT=ST("InvalidXRPTag"),ZT=ST("InvalidAddress"),QT=ST("InvalidAddressBecauseDestinationIsAlsoSource"),tO=ST("LatestMCUInstalledError"),eO=ST("UnknownMCU"),rO=ST("LedgerAPIError"),nO=ST("LedgerAPIErrorWithMessage"),iO=ST("LedgerAPINotAvailable"),oO=ST("ManagerAppAlreadyInstalled"),sO=ST("ManagerAppRelyOnBTC"),uO=ST("ManagerAppDepInstallRequired"),aO=ST("ManagerAppDepUninstallRequired"),hO=ST("ManagerDeviceLocked"),fO=ST("ManagerFirmwareNotEnoughSpace"),cO=ST("ManagerNotEnoughSpace"),lO=ST("ManagerUninstallBTCDep"),pO=ST("NetworkDown"),dO=ST("NoAddressesFound"),gO=ST("NotEnoughBalance"),mO=ST("NotEnoughBalanceToDelegate"),yO=ST("NotEnoughBalanceInParentAccount"),vO=ST("NotEnoughSpendableBalance"),wO=ST("NotEnoughBalanceBecauseDestinationNotCreated"),bO=ST("NoAccessToCamera"),_O=ST("NotEnoughGas"),EO=ST("NotSupportedLegacyAddress"),SO=ST("GasLessThanEstimate"),IO=ST("PasswordsDontMatch"),MO=ST("PasswordIncorrect"),TO=ST("RecommendSubAccountsToEmpty"),OO=ST("RecommendUndelegation"),AO=ST("TimeoutTagged"),PO=ST("UnexpectedBootloader"),kO=ST("MCUNotGenuineToDashboard"),RO=ST("RecipientRequired"),NO=ST("UnavailableTezosOriginatedAccountReceive"),xO=ST("UnavailableTezosOriginatedAccountSend"),BO=ST("UpdateFetchFileFail"),LO=ST("UpdateIncorrectHash"),UO=ST("UpdateIncorrectSig"),CO=ST("UpdateYourApp"),DO=ST("UserRefusedDeviceNameChange"),HO=ST("UserRefusedAddress"),FO=ST("UserRefusedFirmwareUpdate"),jO=ST("UserRefusedAllowManager"),qO=ST("UserRefusedOnDevice"),GO=ST("TransportOpenUserCancelled"),KO=ST("TransportInterfaceNotAvailable"),WO=ST("TransportRaceCondition"),VO=ST("TransportWebUSBGestureRequired"),$O=ST("DeviceShouldStayInApp"),zO=ST("WebsocketConnectionError"),XO=ST("WebsocketConnectionFailed"),YO=ST("WrongDeviceForAccount"),JO=ST("WrongAppForCurrency"),ZO=ST("ETHAddressNonEIP"),QO=ST("CantScanQRCode"),tA=ST("FeeNotLoaded"),eA=ST("FeeRequired"),rA=ST("FeeTooHigh"),nA=ST("SyncError"),iA=ST("PairingFailed"),oA=ST("GenuineCheckFailed"),sA=ST("LedgerAPI4xx"),uA=ST("LedgerAPI5xx"),aA=ST("FirmwareOrAppUpdateRequired"),hA=ST("NoDBPathGiven"),fA=ST("DBWrongPassword"),cA=ST("DBNotReset");function lA(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}lA.prototype=new Error,ET("TransportError",(function(t){return new lA(t.message,t.id)}));var pA={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,MISSING_CRITICAL_PARAMETER:26624,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function dA(t){switch(t){case 26368:return"Incorrect length";case 26624:return"Missing critical parameter";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}function gA(t){this.name="TransportStatusError";var e=Object.keys(pA).find((function(e){return pA[e]===t}))||"UNKNOWN_ERROR",r=dA(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}gA.prototype=new Error,ET("TransportStatusError",(function(t){return new gA(t.statusCode)}));var mA=Object.freeze({__proto__:null,serializeError:function(t){return t?"object"==typeof t?MT(t,[]):"function"==typeof t?"[Function: "+(t.name||"anonymous")+"]":t:t},deserializeError:IT,createCustomErrorClass:ST,addCustomErrorDeserializer:ET,AccountNameRequiredError:TT,AccountNotSupported:OT,AmountRequired:AT,BluetoothRequired:PT,BtcUnmatchedApp:kT,CantOpenDevice:RT,CashAddrNotSupported:NT,CurrencyNotSupported:xT,DeviceAppVerifyNotSupported:BT,DeviceGenuineSocketEarlyClose:LT,DeviceNotGenuineError:UT,DeviceOnDashboardExpected:CT,DeviceOnDashboardUnexpected:DT,DeviceInOSUExpected:HT,DeviceHalted:FT,DeviceNameInvalid:jT,DeviceSocketFail:qT,DeviceSocketNoBulkStatus:GT,DisconnectedDevice:KT,DisconnectedDeviceDuringOperation:WT,EnpointConfigError:VT,EthAppPleaseEnableContractData:$T,FeeEstimationFailed:zT,FirmwareNotRecognized:XT,HardResetFail:YT,InvalidXRPTag:JT,InvalidAddress:ZT,InvalidAddressBecauseDestinationIsAlsoSource:QT,LatestMCUInstalledError:tO,UnknownMCU:eO,LedgerAPIError:rO,LedgerAPIErrorWithMessage:nO,LedgerAPINotAvailable:iO,ManagerAppAlreadyInstalledError:oO,ManagerAppRelyOnBTCError:sO,ManagerAppDepInstallRequired:uO,ManagerAppDepUninstallRequired:aO,ManagerDeviceLockedError:hO,ManagerFirmwareNotEnoughSpaceError:fO,ManagerNotEnoughSpaceError:cO,ManagerUninstallBTCDep:lO,NetworkDown:pO,NoAddressesFound:dO,NotEnoughBalance:gO,NotEnoughBalanceToDelegate:mO,NotEnoughBalanceInParentAccount:yO,NotEnoughSpendableBalance:vO,NotEnoughBalanceBecauseDestinationNotCreated:wO,NoAccessToCamera:bO,NotEnoughGas:_O,NotSupportedLegacyAddress:EO,GasLessThanEstimate:SO,PasswordsDontMatchError:IO,PasswordIncorrectError:MO,RecommendSubAccountsToEmpty:TO,RecommendUndelegation:OO,TimeoutTagged:AO,UnexpectedBootloader:PO,MCUNotGenuineToDashboard:kO,RecipientRequired:RO,UnavailableTezosOriginatedAccountReceive:NO,UnavailableTezosOriginatedAccountSend:xO,UpdateFetchFileFail:BO,UpdateIncorrectHash:LO,UpdateIncorrectSig:UO,UpdateYourApp:CO,UserRefusedDeviceNameChange:DO,UserRefusedAddress:HO,UserRefusedFirmwareUpdate:FO,UserRefusedAllowManager:jO,UserRefusedOnDevice:qO,TransportOpenUserCancelled:GO,TransportInterfaceNotAvailable:KO,TransportRaceCondition:WO,TransportWebUSBGestureRequired:VO,DeviceShouldStayInApp:$O,WebsocketConnectionError:zO,WebsocketConnectionFailed:XO,WrongDeviceForAccount:YO,WrongAppForCurrency:JO,ETHAddressNonEIP:ZO,CantScanQRCode:QO,FeeNotLoaded:tA,FeeRequired:eA,FeeTooHigh:rA,SyncError:nA,PairingFailed:iA,GenuineCheckFailed:oA,LedgerAPI4xx:sA,LedgerAPI5xx:uA,FirmwareOrAppUpdateRequired:aA,NoDBPathGiven:hA,DBWrongPassword:fA,DBNotReset:cA,TransportError:lA,StatusCodes:pA,getAltStatusMessage:dA,TransportStatusError:gA}),yA=function(t,e,r,n){return new(r||(r=Promise))((function(i,o){function s(t){try{a(n.next(t))}catch(t){o(t)}}function u(t){try{a(n.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):function(t){return t instanceof r?t:new r((function(e){e(t)}))}(t.value).then(s,u)}a((n=n.apply(t,e||[])).next())}))},vA=function(t,e){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0)&&!(n=o.next()).done;)s.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},bA=function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},EA=function(){function t(){var t=this;this.exchangeTimeout=3e4,this.unresponsiveTimeout=15e3,this.deviceModel=null,this._events=new wy,this.send=function(e,r,n,i,o,s){return void 0===o&&(o=Buffer.alloc(0)),void 0===s&&(s=[pA.OK]),yA(t,void 0,void 0,(function(){var t,u;return vA(this,(function(a){switch(a.label){case 0:if(o.length>=256)throw new lA("data.length exceed 256 bytes limit. Got: "+o.length,"DataLengthTooBig");return[4,this.exchange(Buffer.concat([Buffer.from([e,r,n,i]),Buffer.from([o.length]),o]))];case 1:if(t=a.sent(),u=t.readUInt16BE(t.length-2),!s.some((function(t){return t===u})))throw new gA(u);return[2,t]}}))}))},this.exchangeAtomicImpl=function(e){return yA(t,void 0,void 0,(function(){var t,r,n,i,o,s=this;return vA(this,(function(u){switch(u.label){case 0:if(this.exchangeBusyPromise)throw new WO("An action was already pending on the Ledger device. Please deny or reconnect.");r=new Promise((function(e){t=e})),this.exchangeBusyPromise=r,n=!1,i=setTimeout((function(){n=!0,s.emit("unresponsive")}),this.unresponsiveTimeout),u.label=1;case 1:return u.trys.push([1,,3,4]),[4,e()];case 2:return o=u.sent(),n&&this.emit("responsive"),[2,o];case 3:return clearTimeout(i),t&&t(),this.exchangeBusyPromise=null,[7];case 4:return[2]}}))}))},this._appAPIlock=null}return t.prototype.exchange=function(t){throw new Error("exchange not implemented")},t.prototype.setScrambleKey=function(t){},t.prototype.close=function(){return Promise.resolve()},t.prototype.on=function(t,e){this._events.on(t,e)},t.prototype.off=function(t,e){this._events.removeListener(t,e)},t.prototype.emit=function(t){for(var e,r=[],n=1;nu&&(s=s.slice(0,u)),{data:s,dataLength:u,sequence:a}},getReducedResult:function(t){if(t&&t.dataLength===t.data.length)return t.data}}}}(SA);var MA,TA,OA=n(SA),AA=function(){return AA=Object.assign||function(t){for(var e,r=1,n=arguments.length;r>8;return kA.find((function(t){return t.productIdMM===r}))},NA=[],xA={};for(var BA in PA){var LA=PA[BA],UA=LA.bluetoothSpec;if(UA)for(var CA=0;CA0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1] "+t.toString("hex")),i=OA(r,n),o=i.makeBlocks(t),s=0,c.label=1;case 1:return s0?[2,t[0]]:[2,qA()]}}))}))}().then((function(r){if(!e){var n=RA(r.productId);t.next({type:"add",descriptor:r,deviceModel:n}),t.complete()}}),(function(e){window.DOMException&&e instanceof window.DOMException&&18===e.code?t.error(new VO(e.message)):t.error(new GO(e.message))})),{unsubscribe:function(){e=!0}}},e}(EA);function XA(t){return VA(this,void 0,void 0,(function(){var e;return $A(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,t.reset()];case 1:return r.sent(),[3,3];case 2:return e=r.sent(),console.warn(e),[3,3];case 3:return[2]}}))}))}var YA=Object.freeze({__proto__:null,default:zA}),JA=JA||{},ZA=JA;JA.EXTENSION_ID="kmendfapggjehodndflmmgagdbamhnfd",JA.MessageTypes={U2F_REGISTER_REQUEST:"u2f_register_request",U2F_SIGN_REQUEST:"u2f_sign_request",U2F_REGISTER_RESPONSE:"u2f_register_response",U2F_SIGN_RESPONSE:"u2f_sign_response"},JA.ErrorCodes={OK:0,OTHER_ERROR:1,BAD_REQUEST:2,CONFIGURATION_UNSUPPORTED:3,DEVICE_INELIGIBLE:4,TIMEOUT:5},JA.Request,JA.Response,JA.Error,JA.SignRequest,JA.SignResponse,JA.RegisterRequest,JA.RegisterResponse,JA.disconnect=function(){JA.port_&&JA.port_.port_&&(JA.port_.port_.disconnect(),JA.port_=null)},JA.getMessagePort=function(t){if("undefined"!=typeof chrome&&chrome.runtime){var e={type:JA.MessageTypes.U2F_SIGN_REQUEST,signRequests:[]};chrome.runtime.sendMessage(JA.EXTENSION_ID,e,(function(){chrome.runtime.lastError?JA.getIframePort_(t):JA.getChromeRuntimePort_(t)}))}else JA.getIframePort_(t)},JA.getChromeRuntimePort_=function(t){var e=chrome.runtime.connect(JA.EXTENSION_ID,{includeTlsChannelId:!0});setTimeout((function(){t(null,new JA.WrappedChromeRuntimePort_(e))}),0)},JA.WrappedChromeRuntimePort_=function(t){this.port_=t},JA.WrappedChromeRuntimePort_.prototype.postMessage=function(t){this.port_.postMessage(t)},JA.WrappedChromeRuntimePort_.prototype.addEventListener=function(t,e){var r=t.toLowerCase();"message"==r||"onmessage"==r?this.port_.onMessage.addListener((function(t){e({data:t})})):console.error("WrappedChromeRuntimePort only supports onMessage")},JA.getIframePort_=function(t){var e="chrome-extension://"+JA.EXTENSION_ID,r=document.createElement("iframe");r.src=e+"/u2f-comms.html",r.setAttribute("style","display:none"),document.body.appendChild(r);var n=!1,i=new MessageChannel,o=function(e){"ready"==e.data?(i.port1.removeEventListener("message",o),n||(n=!0,t(null,i.port1))):console.error('First event on iframe port was not "ready"')};i.port1.addEventListener("message",o),i.port1.start(),r.addEventListener("load",(function(){r.contentWindow.postMessage("init",e,[i.port2])})),setTimeout((function(){n||(n=!0,t(new Error("IFrame extension not supported")))}),200)},JA.EXTENSION_TIMEOUT_SEC=30,JA.port_=null,JA.waitingForPort_=[],JA.reqCounter_=0,JA.callbackMap_={},JA.getPortSingleton_=function(t){JA.port_?t(null,JA.port_):(0==JA.waitingForPort_.length&&JA.getMessagePort((function(t,e){for(t||(JA.port_=e,JA.port_.addEventListener("message",JA.responseHandler_));JA.waitingForPort_.length;)JA.waitingForPort_.shift()(t,e)})),JA.waitingForPort_.push(t))},JA.responseHandler_=function(t){var e=t.data,r=e.requestId;if(r&&JA.callbackMap_[r]){var n=JA.callbackMap_[r];delete JA.callbackMap_[r],n(null,e.responseData)}else console.error("Unknown or missing requestId in response.")},JA.isSupported=function(t){JA.getPortSingleton_((function(e,r){t(!e)}))},JA.sign=function(t,e,r){JA.getPortSingleton_((function(n,i){if(n)return e(n);var o=++JA.reqCounter_;JA.callbackMap_[o]=e;var s={type:JA.MessageTypes.U2F_SIGN_REQUEST,signRequests:t,timeoutSeconds:void 0!==r?r:JA.EXTENSION_TIMEOUT_SEC,requestId:o};i.postMessage(s)}))},JA.register=function(t,e,r,n){JA.getPortSingleton_((function(i,o){if(i)return r(i);var s=++JA.reqCounter_;JA.callbackMap_[s]=r;var u={type:JA.MessageTypes.U2F_REGISTER_REQUEST,signRequests:e,registerRequests:t,timeoutSeconds:void 0!==n?n:JA.EXTENSION_TIMEOUT_SEC,requestId:s};o.postMessage(u)}))};var QA=sP,tP=ZA,eP="undefined"!=typeof navigator&&!!navigator.userAgent,rP=eP&&navigator.userAgent.match(/Safari\//)&&!navigator.userAgent.match(/Chrome\//),nP=eP&&navigator.userAgent.match(/Edge\/1[2345]/),iP=null;function oP(t){return iP||(iP=new t((function(t,e){function r(){t({u2f:null,native:!0})}return eP?rP?r():(void 0!==window.u2f&&"function"==typeof window.u2f.sign&&t({u2f:window.u2f,native:!0}),nP||"http:"===location.protocol||"undefined"==typeof MessageChannel?r():void tP.isSupported((function(e){e?t({u2f:tP,native:!1}):r()}))):r()}))),iP}function sP(t){return{isSupported:hP.bind(t),ensureSupport:cP.bind(t),register:lP.bind(t),sign:pP.bind(t),ErrorCodes:sP.ErrorCodes,ErrorNames:sP.ErrorNames}}function uP(t,e){var r=null!=e?e.errorCode:1,n=sP.ErrorNames[""+r],i=new Error(t);return i.metaData={type:n,code:r},i}function aP(t,e){var r={};return r.promise=new t((function(t,n){r.resolve=t,r.reject=n,e.then(t,n)})),r.promise.cancel=function(e,n){oP(t).then((function(t){n&&!t.native&&t.u2f.disconnect(),r.reject(uP(e,{errorCode:-1}))}))},r}function hP(){return oP(this).then((function(t){return!!t.u2f}))}function fP(t){if(!t.u2f){if("http:"===location.protocol)throw new Error("U2F isn't supported over http, only https");throw new Error("U2F not supported")}}function cP(){return oP(this).then(fP)}function lP(t,e,r){var n=this;return Array.isArray(t)||(t=[t]),"number"==typeof e&&void 0===r&&(r=e,e=null),e||(e=[]),aP(n,oP(n).then((function(i){fP(i);var o=i.native,s=i.u2f;return new n((function(n,i){if(o){var u=t[0].appId;s.register(u,t,e,(function(t){t.errorCode?i(uP("Registration failed",t)):(delete t.errorCode,n(t))}),r)}else s.register(t,e,(function(t,e){t?i(t):e.errorCode?i(uP("Registration failed",e)):n(e)}),r)}))}))).promise}function pP(t,e){var r=this;return Array.isArray(t)||(t=[t]),aP(r,oP(r).then((function(n){fP(n);var i=n.native,o=n.u2f;return new r((function(r,n){if(i){var s=t[0].appId,u=t[0].challenge;o.sign(s,u,t,(function(t){t.errorCode?n(uP("Sign failed",t)):(delete t.errorCode,r(t))}),e)}else o.sign(t,(function(t,e){t?n(t):e.errorCode?n(uP("Sign failed",e)):r(e)}),e)}))}))).promise}function dP(t){sP[t]=function(){if(!r.Promise)throw new Error("The platform doesn't natively support promises");var e=[].slice.call(arguments);return sP(r.Promise)[t].apply(null,e)}}sP.ErrorCodes={CANCELLED:-1,OK:0,OTHER_ERROR:1,BAD_REQUEST:2,CONFIGURATION_UNSUPPORTED:3,DEVICE_INELIGIBLE:4,TIMEOUT:5},sP.ErrorNames={"-1":"CANCELLED",0:"OK",1:"OTHER_ERROR",2:"BAD_REQUEST",3:"CONFIGURATION_UNSUPPORTED",4:"DEVICE_INELIGIBLE",5:"TIMEOUT"},dP("isSupported"),dP("ensureSupport"),dP("register"),dP("sign");var gP=QA,mP={},yP={},vP=function(t,e){yP[t]=e},wP=function(t){var e=function(e,r){Object.assign(this,r),this.name=t,this.message=e||t,this.stack=(new Error).stack};return e.prototype=new Error,mP[t]=e,e};wP("AccountNameRequired"),wP("AccountNotSupported"),wP("AmountRequired"),wP("BluetoothRequired"),wP("BtcUnmatchedApp"),wP("CantOpenDevice"),wP("CashAddrNotSupported"),wP("CurrencyNotSupported"),wP("DeviceAppVerifyNotSupported"),wP("DeviceGenuineSocketEarlyClose"),wP("DeviceNotGenuine"),wP("DeviceOnDashboardExpected"),wP("DeviceOnDashboardUnexpected"),wP("DeviceInOSUExpected"),wP("DeviceHalted"),wP("DeviceNameInvalid"),wP("DeviceSocketFail"),wP("DeviceSocketNoBulkStatus"),wP("DisconnectedDevice"),wP("DisconnectedDeviceDuringOperation"),wP("EnpointConfig"),wP("EthAppPleaseEnableContractData"),wP("FeeEstimationFailed"),wP("FirmwareNotRecognized"),wP("HardResetFail"),wP("InvalidXRPTag"),wP("InvalidAddress"),wP("InvalidAddressBecauseDestinationIsAlsoSource"),wP("LatestMCUInstalledError"),wP("UnknownMCU"),wP("LedgerAPIError"),wP("LedgerAPIErrorWithMessage"),wP("LedgerAPINotAvailable"),wP("ManagerAppAlreadyInstalled"),wP("ManagerAppRelyOnBTC"),wP("ManagerAppDepInstallRequired"),wP("ManagerAppDepUninstallRequired"),wP("ManagerDeviceLocked"),wP("ManagerFirmwareNotEnoughSpace"),wP("ManagerNotEnoughSpace"),wP("ManagerUninstallBTCDep"),wP("NetworkDown"),wP("NoAddressesFound"),wP("NotEnoughBalance"),wP("NotEnoughBalanceToDelegate"),wP("NotEnoughBalanceInParentAccount"),wP("NotEnoughSpendableBalance"),wP("NotEnoughBalanceBecauseDestinationNotCreated"),wP("NoAccessToCamera"),wP("NotEnoughGas"),wP("NotSupportedLegacyAddress"),wP("GasLessThanEstimate"),wP("PasswordsDontMatch"),wP("PasswordIncorrect"),wP("RecommendSubAccountsToEmpty"),wP("RecommendUndelegation"),wP("TimeoutTagged"),wP("UnexpectedBootloader"),wP("MCUNotGenuineToDashboard"),wP("RecipientRequired"),wP("UnavailableTezosOriginatedAccountReceive"),wP("UnavailableTezosOriginatedAccountSend"),wP("UpdateFetchFileFail"),wP("UpdateIncorrectHash"),wP("UpdateIncorrectSig"),wP("UpdateYourApp"),wP("UserRefusedDeviceNameChange"),wP("UserRefusedAddress"),wP("UserRefusedFirmwareUpdate"),wP("UserRefusedAllowManager"),wP("UserRefusedOnDevice"),wP("TransportOpenUserCancelled"),wP("TransportInterfaceNotAvailable");var bP=wP("TransportRaceCondition");function _P(t,e){this.name="TransportError",this.message=t,this.stack=(new Error).stack,this.id=e}wP("TransportWebUSBGestureRequired"),wP("DeviceShouldStayInApp"),wP("WebsocketConnectionError"),wP("WebsocketConnectionFailed"),wP("WrongDeviceForAccount"),wP("WrongAppForCurrency"),wP("ETHAddressNonEIP"),wP("CantScanQRCode"),wP("FeeNotLoaded"),wP("FeeRequired"),wP("FeeTooHigh"),wP("SyncError"),wP("PairingFailed"),wP("GenuineCheckFailed"),wP("LedgerAPI4xx"),wP("LedgerAPI5xx"),wP("FirmwareOrAppUpdateRequired"),wP("NoDBPathGiven"),wP("DBWrongPassword"),wP("DBNotReset"),_P.prototype=new Error,vP("TransportError",(function(t){return new _P(t.message,t.id)}));var EP={PIN_REMAINING_ATTEMPTS:25536,INCORRECT_LENGTH:26368,MISSING_CRITICAL_PARAMETER:26624,COMMAND_INCOMPATIBLE_FILE_STRUCTURE:27009,SECURITY_STATUS_NOT_SATISFIED:27010,CONDITIONS_OF_USE_NOT_SATISFIED:27013,INCORRECT_DATA:27264,NOT_ENOUGH_MEMORY_SPACE:27268,REFERENCED_DATA_NOT_FOUND:27272,FILE_ALREADY_EXISTS:27273,INCORRECT_P1_P2:27392,INS_NOT_SUPPORTED:27904,CLA_NOT_SUPPORTED:28160,TECHNICAL_PROBLEM:28416,OK:36864,MEMORY_PROBLEM:37440,NO_EF_SELECTED:37888,INVALID_OFFSET:37890,FILE_NOT_FOUND:37892,INCONSISTENT_FILE:37896,ALGORITHM_NOT_SUPPORTED:38020,INVALID_KCV:38021,CODE_NOT_INITIALIZED:38914,ACCESS_CONDITION_NOT_FULFILLED:38916,CONTRADICTION_SECRET_CODE_STATUS:38920,CONTRADICTION_INVALIDATION:38928,CODE_BLOCKED:38976,MAX_VALUE_REACHED:38992,GP_AUTH_FAILED:25344,LICENSING:28482,HALTED:28586};function SP(t){this.name="TransportStatusError";var e=Object.keys(EP).find((function(e){return EP[e]===t}))||"UNKNOWN_ERROR",r=function(t){switch(t){case 26368:return"Incorrect length";case 26624:return"Missing critical parameter";case 27010:return"Security not satisfied (dongle locked or have invalid access rights)";case 27013:return"Condition of use not satisfied (denied by the user?)";case 27264:return"Invalid data received";case 27392:return"Invalid parameter received"}if(28416<=t&&t<=28671)return"Internal error, please report"}(t)||e,n=t.toString(16);this.message="Ledger device: "+r+" (0x"+n+")",this.stack=(new Error).stack,this.statusCode=t,this.statusText=e}SP.prototype=new Error,vP("TransportStatusError",(function(t){return new SP(t.statusCode)}));class IP{constructor(){this.exchangeTimeout=3e4,this.unresponsiveTimeout=15e3,this.deviceModel=null,this._events=new wy,this.send=async(t,e,r,n,i=Buffer.alloc(0),o=[EP.OK])=>{if(i.length>=256)throw new _P("data.length exceed 256 bytes limit. Got: "+i.length,"DataLengthTooBig");const s=await this.exchange(Buffer.concat([Buffer.from([t,e,r,n]),Buffer.from([i.length]),i])),u=s.readUInt16BE(s.length-2);if(!o.some((t=>t===u)))throw new SP(u);return s},this.exchangeBusyPromise=void 0,this.exchangeAtomicImpl=async t=>{if(this.exchangeBusyPromise)throw new bP("An action was already pending on the Ledger device. Please deny or reconnect.");let e;const r=new Promise((t=>{e=t}));this.exchangeBusyPromise=r;let n=!1;const i=setTimeout((()=>{n=!0,this.emit("unresponsive")}),this.unresponsiveTimeout);try{const r=await t();return n&&this.emit("responsive"),r}finally{clearTimeout(i),e&&e(),this.exchangeBusyPromise=null}},this._appAPIlock=null}exchange(t){throw new Error("exchange not implemented")}setScrambleKey(t){}close(){return Promise.resolve()}on(t,e){this._events.on(t,e)}off(t,e){this._events.removeListener(t,e)}emit(t,...e){this._events.emit(t,...e)}setDebugMode(){console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore.")}setExchangeTimeout(t){this.exchangeTimeout=t}setExchangeUnresponsiveTimeout(t){this.unresponsiveTimeout=t}static create(t=3e3,e){return new Promise(((r,n)=>{let i=!1;const o=this.listen({next:e=>{i=!0,o&&o.unsubscribe(),s&&clearTimeout(s),this.open(e.descriptor,t).then(r,n)},error:t=>{s&&clearTimeout(s),n(t)},complete:()=>{s&&clearTimeout(s),i||n(new _P(this.ErrorMessage_NoDeviceFound,"NoDeviceFound"))}}),s=e?setTimeout((()=>{o.unsubscribe(),n(new _P(this.ErrorMessage_ListenTimeout,"ListenTimeout"))}),e):null}))}decorateAppAPIMethods(t,e,r){for(let n of e)t[n]=this.decorateAppAPIMethod(n,t[n],t,r)}decorateAppAPIMethod(t,e,r,n){return async(...i)=>{const{_appAPIlock:o}=this;if(o)return Promise.reject(new _P("Ledger Device is busy (lock "+o+")","TransportLocked"));try{return this._appAPIlock=t,this.setScrambleKey(n),await e.apply(r,i)}finally{this._appAPIlock=null}}}}IP.isSupported=void 0,IP.list=void 0,IP.listen=void 0,IP.open=void 0,IP.ErrorMessage_ListenTimeout="No Ledger device found (timeout)",IP.ErrorMessage_NoDeviceFound="No Ledger device found";let MP=0;const TP=[],OP=(t,e,r)=>{const n={type:t,id:String(++MP),date:new Date};e&&(n.message=e),r&&(n.data=r),function(t){for(let e=0;e(TP.push(t),()=>{const e=TP.indexOf(t);-1!==e&&(TP[e]=TP[TP.length-1],TP.pop())});"undefined"!=typeof window&&(window.__ledgerLogsListen=AP);const PP=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");function kP(t,e,r,n){const i=function(t,e){const r=Buffer.alloc(t.length);for(let n=0;n "+t.toString("hex")),gP.sign(s,e/1e3).then((t=>{const{signatureData:e}=t;if("string"==typeof e){const t=Buffer.from((r=e).replace(/-/g,"+").replace(/_/g,"/")+"==".substring(0,3*r.length%4),"base64");let i;return i=n?t.slice(5):t,OP("apdu","<= "+i.toString("hex")),i}throw t;var r}))}let RP=[];class NP extends IP{static async open(t,e=5e3){return new NP}constructor(){super(),this.scrambleKey=void 0,this.unwrap=!0,RP.push(this)}async exchange(t){try{return await kP(t,this.exchangeTimeout,this.scrambleKey,this.unwrap)}catch(t){throw"object"==typeof t.metaData?(5===t.metaData.code&&(RP.forEach((t=>t.emit("disconnect"))),RP=[]),function(t,e,r){const n=new _P(e,r);return n.originalError=t,n}(t,"Failed to sign with Ledger device: U2F "+t.metaData.type,"U2F_"+t.metaData.code)):t}}setScrambleKey(t){this.scrambleKey=Buffer.from(t,"ascii")}setUnwrap(t){this.unwrap=t}close(){return Promise.resolve()}}NP.isSupported=gP.isSupported,NP.list=()=>gP.isSupported().then((t=>t?[null]:[])),NP.listen=t=>{let e=!1;return gP.isSupported().then((r=>{e||(r?(t.next({type:"add",descriptor:null}),t.complete()):t.error(new _P("U2F browser support is needed for Ledger. Please use Chrome, Opera or Firefox with a U2F extension. Also make sure you're on an HTTPS connection","U2FNotSupported")))})),{unsubscribe:()=>{e=!0}}};var xP=Object.freeze({__proto__:null,default:NP}),BP=te.exports,LP=EE,UP=f.exports.Buffer,CP=new Array(16);function DP(){LP.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function HP(t,e){return t<>>32-e}function FP(t,e,r,n,i,o,s){return HP(t+(e&r|~e&n)+i+o|0,s)+e|0}function jP(t,e,r,n,i,o,s){return HP(t+(e&n|r&~n)+i+o|0,s)+e|0}function qP(t,e,r,n,i,o,s){return HP(t+(e^r^n)+i+o|0,s)+e|0}function GP(t,e,r,n,i,o,s){return HP(t+(r^(e|~n))+i+o|0,s)+e|0}BP(DP,LP),DP.prototype._update=function(){for(var t=CP,e=0;e<16;++e)t[e]=this._block.readInt32LE(4*e);var r=this._a,n=this._b,i=this._c,o=this._d;r=FP(r,n,i,o,t[0],3614090360,7),o=FP(o,r,n,i,t[1],3905402710,12),i=FP(i,o,r,n,t[2],606105819,17),n=FP(n,i,o,r,t[3],3250441966,22),r=FP(r,n,i,o,t[4],4118548399,7),o=FP(o,r,n,i,t[5],1200080426,12),i=FP(i,o,r,n,t[6],2821735955,17),n=FP(n,i,o,r,t[7],4249261313,22),r=FP(r,n,i,o,t[8],1770035416,7),o=FP(o,r,n,i,t[9],2336552879,12),i=FP(i,o,r,n,t[10],4294925233,17),n=FP(n,i,o,r,t[11],2304563134,22),r=FP(r,n,i,o,t[12],1804603682,7),o=FP(o,r,n,i,t[13],4254626195,12),i=FP(i,o,r,n,t[14],2792965006,17),r=jP(r,n=FP(n,i,o,r,t[15],1236535329,22),i,o,t[1],4129170786,5),o=jP(o,r,n,i,t[6],3225465664,9),i=jP(i,o,r,n,t[11],643717713,14),n=jP(n,i,o,r,t[0],3921069994,20),r=jP(r,n,i,o,t[5],3593408605,5),o=jP(o,r,n,i,t[10],38016083,9),i=jP(i,o,r,n,t[15],3634488961,14),n=jP(n,i,o,r,t[4],3889429448,20),r=jP(r,n,i,o,t[9],568446438,5),o=jP(o,r,n,i,t[14],3275163606,9),i=jP(i,o,r,n,t[3],4107603335,14),n=jP(n,i,o,r,t[8],1163531501,20),r=jP(r,n,i,o,t[13],2850285829,5),o=jP(o,r,n,i,t[2],4243563512,9),i=jP(i,o,r,n,t[7],1735328473,14),r=qP(r,n=jP(n,i,o,r,t[12],2368359562,20),i,o,t[5],4294588738,4),o=qP(o,r,n,i,t[8],2272392833,11),i=qP(i,o,r,n,t[11],1839030562,16),n=qP(n,i,o,r,t[14],4259657740,23),r=qP(r,n,i,o,t[1],2763975236,4),o=qP(o,r,n,i,t[4],1272893353,11),i=qP(i,o,r,n,t[7],4139469664,16),n=qP(n,i,o,r,t[10],3200236656,23),r=qP(r,n,i,o,t[13],681279174,4),o=qP(o,r,n,i,t[0],3936430074,11),i=qP(i,o,r,n,t[3],3572445317,16),n=qP(n,i,o,r,t[6],76029189,23),r=qP(r,n,i,o,t[9],3654602809,4),o=qP(o,r,n,i,t[12],3873151461,11),i=qP(i,o,r,n,t[15],530742520,16),r=GP(r,n=qP(n,i,o,r,t[2],3299628645,23),i,o,t[0],4096336452,6),o=GP(o,r,n,i,t[7],1126891415,10),i=GP(i,o,r,n,t[14],2878612391,15),n=GP(n,i,o,r,t[5],4237533241,21),r=GP(r,n,i,o,t[12],1700485571,6),o=GP(o,r,n,i,t[3],2399980690,10),i=GP(i,o,r,n,t[10],4293915773,15),n=GP(n,i,o,r,t[1],2240044497,21),r=GP(r,n,i,o,t[8],1873313359,6),o=GP(o,r,n,i,t[15],4264355552,10),i=GP(i,o,r,n,t[6],2734768916,15),n=GP(n,i,o,r,t[13],1309151649,21),r=GP(r,n,i,o,t[4],4149444226,6),o=GP(o,r,n,i,t[11],3174756917,10),i=GP(i,o,r,n,t[2],718787259,15),n=GP(n,i,o,r,t[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0},DP.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var t=UP.allocUnsafe(16);return t.writeInt32LE(this._a,0),t.writeInt32LE(this._b,4),t.writeInt32LE(this._c,8),t.writeInt32LE(this._d,12),t};var KP=DP,WP=i(Bv),VP=f.exports.Buffer,$P=ww.Transform,zP=WP.StringDecoder;function XP(t){$P.call(this),this.hashMode="string"==typeof t,this.hashMode?this[t]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}(0,te.exports)(XP,$P),XP.prototype.update=function(t,e,r){"string"==typeof t&&(t=VP.from(t,e));var n=this._update(t);return this.hashMode?this:(r&&(n=this._toString(n,r)),n)},XP.prototype.setAutoPadding=function(){},XP.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},XP.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},XP.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},XP.prototype._transform=function(t,e,r){var n;try{this.hashMode?this._update(t):this.push(this._update(t))}catch(t){n=t}finally{r(n)}},XP.prototype._flush=function(t){var e;try{this.push(this.__final())}catch(t){e=t}t(e)},XP.prototype._finalOrDigest=function(t){var e=this.__final()||VP.alloc(0);return t&&(e=this._toString(e,t,!0)),e},XP.prototype._toString=function(t,e,r){if(this._decoder||(this._decoder=new zP(e),this._encoding=e),this._encoding!==e)throw new Error("can't switch encodings");var n=this._decoder.write(t);return r&&(n+=this._decoder.end()),n};var YP=XP,JP=te.exports,ZP=KP,QP=FE,tk=jE.exports,ek=YP;function rk(t){ek.call(this,"digest"),this._hash=t}JP(rk,ek),rk.prototype._update=function(t){this._hash.update(t)},rk.prototype._final=function(){return this._hash.digest()};var nk=function(t){return"md5"===(t=t.toLowerCase())?new ZP:"rmd160"===t||"ripemd160"===t?new QP:new rk(tk(t))},ik=Object.freeze(e({__proto__:null,default:nk},[nk]));t.Btc=vT,t.Log=JI,t.TransportU2F=xP,t.TransportWebUSB=YA,t.createHash=ik,Object.defineProperty(t,"__esModule",{value:!0})})); +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util'), require('string_decoder')) : + typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util', 'string_decoder'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.EventEmitter, global.require$$1, global.require$$2)); +})(this, (function (exports, require$$0$2, require$$0$3, require$$0$4, EventEmitter, require$$1, require$$2) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); + } + + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); + var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); + var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); + var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); + var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); + var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + + var runtime = {exports: {}}; + + /** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + (function (module) { + var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined$1; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + define(Gp, "constructor", GeneratorFunctionPrototype); + define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined$1) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined$1; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined$1; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + define(Gp, iteratorSymbol, function() { + return this; + }); + + define(Gp, "toString", function() { + return "[object Generator]"; + }); + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined$1; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined$1, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined$1; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined$1; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined$1; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined$1; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports + )); + + try { + regeneratorRuntime = runtime; + } catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, in modern engines + // we can explicitly access globalThis. In older engines we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } + } + }(runtime)); + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + 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]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (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) + } + + function write (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; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use 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+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer$i.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + function kMaxLength () { + return Buffer$i.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$i.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$i(length); + } + that.length = length; + } + + return that + } + + /** + * 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$i (arg, encodingOrOffset, length) { + if (!Buffer$i.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$i)) { + return new Buffer$i(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from$2(this, arg, encodingOrOffset, length) + } + + Buffer$i.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$i._augment = function (arr) { + arr.__proto__ = Buffer$i.prototype; + return arr + }; + + function from$2 (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, 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$i.from = function (value, encodingOrOffset, length) { + return from$2(null, value, encodingOrOffset, length) + }; + + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + Buffer$i.prototype.__proto__ = Uint8Array.prototype; + Buffer$i.__proto__ = Uint8Array; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer$i.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$i.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$i.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer$i.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$i.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.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') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$i.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer$i.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer$i.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var 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$i.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$i.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$i.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$i.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + 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 utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer$i.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var 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 coersion 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; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$i.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer$i.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer$i.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer$i.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var 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$i.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer$i.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$i.compare(this, b) === 0 + }; + + Buffer$i.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer$i.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + 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 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var 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 (isNaN(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$i.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(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 (Buffer$i.TYPED_ARRAY_SUPPORT && + 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) { + var indexSize = 1; + var arrLength = arr.length; + var 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) + } + } + + var i; + if (dir) { + var 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--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer$i.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer$i.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer$i.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(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 latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, 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$i.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; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var 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'; + + var 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': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(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$i.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 fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var 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 + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var 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". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex$1(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer$i.prototype.slice = function slice (start, end) { + var 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; + + var newBuf; + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$i.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$i(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + 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$i.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer$i.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer$i.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer$i.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer$i.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer$i.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer$i.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer$i.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var 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$i.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var 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$i.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer$i.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$i.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$i.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer$i.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer$i.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer$i.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer$i.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer$i.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(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$i.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$i.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$i.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer$i.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$i.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer$i.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$i.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer$i.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var 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$i.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var 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$i.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer$i.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$i.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer$i.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$i.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; + if (Buffer$i.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + 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) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer$i.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer$i.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer$i.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer$i.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer$i.prototype.copy = function copy (target, targetStart, start, end) { + 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('sourceStart out of bounds') + 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; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$i.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer$i.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 (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$i.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // 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; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer$i(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).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 stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex$1 (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var 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) { + var byteArray = []; + for (var 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) { + var c, hi, lo; + var byteArray = []; + for (var 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 toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + /* + * Bitcoin BIP32 path helpers + * (C) 2016 Alex Beregszaszi + */ + + const HARDENED = 0x80000000; + + var BIPPath = function (path) { + if (!Array.isArray(path)) { + throw new Error('Input must be an Array') + } + if (path.length === 0) { + throw new Error('Path must contain at least one level') + } + for (var i = 0; i < path.length; i++) { + if (typeof path[i] !== 'number') { + throw new Error('Path element is not a number') + } + } + this.path = path; + }; + + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false + } + }; + + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false + } + }; + + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) + }; + + BIPPath.fromString = function (text, reqRoot) { + // skip the root + if (/^m\//i.test(text)) { + text = text.slice(2); + } else if (reqRoot) { + throw new Error('Root element is required') + } + + var path = text.split('/'); + var ret = new Array(path.length); + for (var i = 0; i < path.length; i++) { + var tmp = /(\d+)([hH\']?)/.exec(path[i]); + if (tmp === null) { + throw new Error('Invalid input') + } + ret[i] = parseInt(tmp[1], 10); + + if (ret[i] >= HARDENED) { + throw new Error('Invalid child index') + } + + if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { + ret[i] += HARDENED; + } else if (tmp[2].length != 0) { + throw new Error('Invalid modifier') + } + } + return new BIPPath(ret) + }; + + BIPPath.prototype.toPathArray = function () { + return this.path + }; + + BIPPath.prototype.toString = function (noRoot, oldStyle) { + var ret = new Array(this.path.length); + for (var i = 0; i < this.path.length; i++) { + var tmp = this.path[i]; + if (tmp & HARDENED) { + ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); + } else { + ret[i] = tmp; + } + } + return (noRoot ? '' : 'm/') + ret.join('/') + }; + + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; + + var bip32Path = BIPPath; + + var createHash$3 = window.createHash; + + var safeBuffer = {exports: {}}; + + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer = require$$0__default$1["default"]; + 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) + }; + }(safeBuffer, safeBuffer.exports)); + + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; + } + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; + } + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } + } + var src$2 = base$2; + + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + var bs58 = basex(ALPHABET$1); + + var base58 = bs58; + var Buffer$h = safeBuffer.exports.Buffer; + + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); + + return base58.encode(Buffer$h.concat([ + payload, + checksum + ], payload.length + 4)) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } + }; + + var createHash$2 = createHash$3; + var bs58checkBase = base$1; + + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() + } + + var bs58check$5 = bs58checkBase(sha256x2); + + function pathElementsToBuffer(paths) { + var buffer = Buffer$i.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } + + var src$1 = {}; + + var src = {}; + + var bip32$1 = {}; + + var crypto$4 = {}; + + var createHmac$2 = require$$0__default["default"].createHmac; + + Object.defineProperty(crypto$4, "__esModule", { value: true }); + const createHash$1 = createHash$3; + const createHmac$1 = createHmac$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } + } + crypto$4.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$4.hmacSHA512 = hmacSHA512; + + var tinySecp256k1 = {exports: {}}; + + var bn$1 = {exports: {}}; + + (function (module) { + (function (module, exports) { + + // 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 = require('buffer').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) ; 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); + }; + })(module, commonjsGlobal); + }(bn$1)); + + var elliptic = {}; + + var name = "elliptic"; + var version$1 = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0$1 = { + name: name, + version: version$1, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; + + var utils$n = {}; + + var bn = {exports: {}}; + + (function (module) { + (function (module, exports) { + + // 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 = require('buffer').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) ; 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); + }; + })(module, commonjsGlobal); + }(bn)); + + var minimalisticAssert = assert$f; + + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } + + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; + + var utils$m = {}; + + (function (exports) { + + 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; + }; + }(utils$m)); + + (function (exports) { + + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; + + 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; + }(utils$n)); + + var brorand = {exports: {}}; + + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; + } + brorand.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$3 = require('crypto'); + if (typeof crypto$3.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$3.randomBytes(n); + }; + } catch (e) { + } + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); + } + } + var base = 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$e(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$e(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]; + 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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; + }; + + var inherits$f = {exports: {}}; + + var inherits_browser = {exports: {}}; + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } + + try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + inherits$f.exports = util.inherits; + } catch (e) { + /* istanbul ignore next */ + inherits$f.exports = inherits_browser.exports; + } + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$e = inherits$f.exports; + var Base$3 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$3.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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$e(ShortCurve, Base$3); + var short = 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$7(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$7(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$d(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$7(vec.a, 16), + b: new BN$7(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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { + Base$3.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$e(Point$2, Base$3.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.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$2.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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$3.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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$e(JPoint, Base$3.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$7(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; + }; + + var BN$6 = bn.exports; + var inherits$d = inherits$f.exports; + var Base$2 = base; + + var utils$j = utils$n; + + function MontCurve(conf) { + Base$2.call(this, 'mont', conf); + + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$d(MontCurve, Base$2); + var mont = 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$1(curve, x, z) { + Base$2.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$6(x, 16); + this.z = new BN$6(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$d(Point$1, Base$2.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); + }; + + Point$1.prototype.precompute = function precompute() { + // No-op + }; + + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; + + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point$1.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$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$c = inherits$f.exports; + var Base$1 = base; + + var assert$c = utils$i.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$1.call(this, 'edwards', conf); + + this.a = new BN$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$c(EdwardsCurve, Base$1); + var edwards = 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$5(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$5(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$1.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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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$c(Point, Base$1.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; + + (function (exports) { + + var curve = exports; + + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); + + var curves$2 = {}; + + var hash$3 = {}; + + var utils$h = {}; + + var assert$b = minimalisticAssert; + var inherits$b = inherits$f.exports; + + utils$h.inherits = inherits$b; + + 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; + } + utils$h.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.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; + } + utils$h.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.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; + } + utils$h.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.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; + } + utils$h.split32 = split32; + + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; + + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; + + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; + + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; + + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; + + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; + + function sum64$1(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; + } + utils$h.sum64 = sum64$1; + + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; + + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; + + function sum64_4_hi$1(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; + } + utils$h.sum64_4_hi = sum64_4_hi$1; + + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; + + function sum64_5_hi$1(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; + } + utils$h.sum64_5_hi = sum64_5_hi$1; + + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; + + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; + + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; + + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; + + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; + + var common$5 = {}; + + var utils$g = utils$h; + var assert$a = minimalisticAssert; + + function BlockHash$4() { + 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; + } + common$5.BlockHash = BlockHash$4; + + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); + + return this._digest(enc); + }; + + BlockHash$4.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; + }; + + var sha$3 = {}; + + var common$4 = {}; + + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; + + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); + } + common$4.ft_1 = ft_1$1; + + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; + + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + common$4.maj32 = maj32$1; + + function p32(x, y, z) { + return x ^ y ^ z; + } + common$4.p32 = p32; + + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$4.s0_256 = s0_256$1; + + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$4.s1_256 = s1_256$1; + + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + common$4.g0_256 = g0_256$1; + + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + common$4.g1_256 = g1_256$1; + + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; + + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; + + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; + + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); + } + + utils$e.inherits(SHA1, BlockHash$3); + var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; + + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; + + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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$2 = common$2.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$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; + + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; + + SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } + + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; + + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; + + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; + + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; + + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; + + var BlockHash$1 = common$1.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$2() { + if (!(this instanceof SHA512$2)) + return new SHA512$2(); + + BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); + var _512 = SHA512$2; + + SHA512$2.blockSize = 1024; + SHA512$2.outSize = 512; + SHA512$2.hmacStrength = 192; + SHA512$2.padLength = 128; + + SHA512$2.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$2.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$8(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); + 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); + 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$2.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.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; + } + + var utils$a = utils$h; + + var SHA512$1 = _512; + + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512$1.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; + } + utils$a.inherits(SHA384, SHA512$1); + var _384 = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); + }; + + sha$3.sha1 = _1; + sha$3.sha224 = _224; + sha$3.sha256 = _256; + sha$3.sha384 = _384; + sha$3.sha512 = _512; + + var ripemd = {}; + + var utils$9 = utils$h; + var common = common$5; + + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; + var BlockHash = common.BlockHash; + + function RIPEMD160$2() { + if (!(this instanceof RIPEMD160$2)) + return new RIPEMD160$2(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; + } + utils$9.inherits(RIPEMD160$2, BlockHash); + ripemd.ripemd160 = RIPEMD160$2; + + RIPEMD160$2.blockSize = 512; + RIPEMD160$2.outSize = 160; + RIPEMD160$2.hmacStrength = 192; + RIPEMD160$2.padLength = 64; + + RIPEMD160$2.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$4(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$2.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$9.toHex32(this.h, 'little'); + else + return utils$9.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$4(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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); + } + var hmac = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(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); + }; + + (function (exports) { + var hash = exports; + + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha$3; + hash.ripemd = ripemd; + hash.hmac = hmac; + + // 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; + }(hash$3)); + + (function (exports) { + + var curves = exports; + + var hash = hash$3; + var curve$1 = curve; + var utils = utils$n; + + var assert = utils.assert; + + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.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 = require('./precomputed/secp256k1'); + } 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, + ], + }); + }(curves$2)); + + var hash$2 = hash$3; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; + + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; + + HmacDRBG$1.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$1.prototype._hmac = function hmac() { + return new hash$2.hmac(this.hash, this.K); + }; + + HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); + + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG$1.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$7.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$7.encode(res, enc); + }; + + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; + + function KeyPair$4(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); + } + var key$1 = KeyPair$4; + + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; + + KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + var signature$1 = Signature$3; + + 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$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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$3(r); + this.s = new BN$3(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$3.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$5.encode(res, enc); + }; + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); + }; + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); + }; + + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; + + EC$1.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(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + + EC$1.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$1.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$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); + } + + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; + + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; + + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; + + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; + + var key = KeyPair$2; + + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.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$1(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes$1(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + 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$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + var signature = Signature$1; + + var hash$1 = hash$3; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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$1.sha512; + } + + var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0$1.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = createHmac$2; + + const ONE1 = Buffer$i.alloc(1, 1); + const ZERO1 = Buffer$i.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$i.alloc(32, 0); + let v = Buffer$i.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; + } + + return T + } + + var rfc6979 = deterministicGenerateK$1; + + const BN = bn$1.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer$i.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$i.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$i.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 + } + + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false + + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true + } + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false + } + + function __isPointCompressed (p) { + return p[0] !== 0x04 + } + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) + } + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 + } + + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } + + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$i, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$i.from(P._encode(compressed)) } + + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) + } + + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) + } + + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + + const compressed = assumeCompression(__compressed, p); + + return getEncoded(pp, compressed) + } + + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) + } + + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null + + return getEncoded(qq, compressed) + } + + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function sign$1 (hash, x) { + return __sign(hash, x) + } + + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) + } + + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); + + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); + + if (Q.isInfinity()) return false + + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer$i.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer + } + + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) + } + + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign: sign$1, + signWithEntropy, + verify + }; + + try { + tinySecp256k1.exports = require('./native'); + } catch (err) { + tinySecp256k1.exports = js; + } + + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); + } + + var native$1 = types$c; + + var native = native$1; + + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } + + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); + } + } + + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' + } + + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') + } + + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); + + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + } + + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } + + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); + } + + captureStackTrace(e); + return e + } + + var errors$1 = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors$1; + + function _Buffer (value) { + return isBuffer(value) + } + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors$1; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str + }; + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; + } + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) }; + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected }; + + return _value + } + }; + + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; + + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) + } + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce$b(compile(type), value, strict) + } + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } + } + + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$i(compressed ? 34 : 33); + + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result + } + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) + } + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw + }; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$2 = crypto$4; + const bs58check$3 = bs58check$5; + const ecc$6 = tinySecp256k1.exports; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); + } + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; + } + get depth() { + return this.__DEPTH; + } + get index() { + return this.__INDEX; + } + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; + } + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; + } + get privateKey() { + return this.__D; + } + get identifier() { + return crypto$2.hash160(this.publicKey); + } + get fingerprint() { + return this.identifier.slice(0, 4); + } + get compressed() { + return true; + } + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; + } + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$i.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$i.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$2.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$i.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); + } + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); + } + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) + } + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } + return hd; + } + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$2.hmacSHA512(Buffer$i.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; + + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; + + var address$1 = {}; + + var networks$3 = {}; + + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + + var payments$4 = {}; + + var embed = {}; + + var script$1 = {}; + + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$i.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { + return ( + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); + } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$g = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } + + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + } + } + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$g.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature + } + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$i.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$i.concat([ZERO$1, x], 1 + x.length); + return x; + } + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$i.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$i.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$i.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$i.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); + } + + return size + } + + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; + + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; + + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; + + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; + + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + + number = buffer.readUInt32LE(offset + 1); + size = 5; + } + + return { + opcode: opcode, + number: number, + size: size + } + } + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; + + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; + } + + var map_1 = map; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = tinySecp256k1.exports; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); + } + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); + } + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); + } + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; + } + function chunksIsBuffer(buf) { + return isBuffer(buf); + } + function chunksIsArray(buf) { + return types.Array(buf); + } + function singleChunkIsBuffer(buf) { + return isBuffer(buf); + } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$i.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; + } + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; + } + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); + } + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$i.from(chunkStr, 'hex'); + }), + ); + } + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$i.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); + } + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); + } + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; + } + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); + + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); + } + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; + } + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); + } + embed.p2data = p2data; + + var p2ms$3 = {}; + + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = tinySecp256k1.exports; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + + var p2pk$3 = {}; + + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = tinySecp256k1.exports; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); + } + p2pk$3.p2pk = p2pk$2; + + var p2pkh$4 = {}; + + var crypto$1 = {}; + + Object.defineProperty(crypto$1, '__esModule', { value: true }); + const createHash = createHash$3; + function ripemd160$2(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } + } + crypto$1.ripemd160 = ripemd160$2; + function sha1$1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$1.sha1 = sha1$1; + function sha256$2(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$1.sha256 = sha256$2; + function hash160$1(buffer) { + return ripemd160$2(sha256$2(buffer)); + } + crypto$1.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$2(sha256$2(buffer)); + } + crypto$1.hash256 = hash256$1; + + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$1; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = tinySecp256k1.exports; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$i.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$i.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2pkh$4.p2pkh = p2pkh$3; + + var p2sh$1 = {}; + + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$1; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; + } + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); + return { + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$i.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$i.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); + } + p2sh$1.p2sh = p2sh; + + var p2wpkh$2 = {}; + + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk + } + + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + + return result + } + + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' + + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } + + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) + } + + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result + } + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } + + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$1; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = tinySecp256k1.exports; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$i.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$i.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$i.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2wpkh$2.p2wpkh = p2wpkh$1; + + var p2wsh$1 = {}; + + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$1; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = tinySecp256k1.exports; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$i.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + function chunkHasUncompressedPubkey(chunk) { + if ( + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; + } + } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$i.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$i.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$i.from(data), + }; + } + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$i.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); + } + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); + } + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } + } + throw new Error(address + ' has no matching Script'); + } + address$1.toOutputScript = toOutputScript; + + var ecpair = {}; + + var randombytes = require$$0__default["default"].randomBytes; + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = tinySecp256k1.exports; + const randomBytes = randombytes; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$i.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer$f = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer$f.allocUnsafe(encodingLength$1(number)); + if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; + } + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number + } + } + + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$i.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; + } + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; + } + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$1; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$i.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$i.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$i.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$i.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$i.from(hex, 'hex'), false); + } + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer$i.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$i.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$i.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$i.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$i.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$i.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$i.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$i.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$i.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$i.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; + } + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$1; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(Buffer$i.from(hex, 'hex')); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$i.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$i.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$i.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$i && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$i && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); + } + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$i.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } + } + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); + } + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); + } + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$i.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$i.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$i.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); + } + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); + } + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$i.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; + } + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$i.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; + } + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); + } + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; + } + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$i.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; + } + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); + } + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); + } + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$i.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; + } + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); + } + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; + } + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$i.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$i.concat([head, pSig.pubkey]), + value: pSig.signature, + }; + } + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); + } + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$i.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer$i.from(data, 'utf8'), + }; + } + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); + } + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$i.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$i.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; + } + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; + } + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; + } + sighashType$1.canAdd = canAdd$1; + + var witnessUtxo$1 = {}; + + var tools = {}; + + var varint$1 = {}; + + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); + } + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$i.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); + } + return buffer; + } + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; + + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$i.from([0])); + return Buffer$i.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$i.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; + + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$i.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$i.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; + + var bip32Derivation$1 = {}; + + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer$i.from([TYPE_BYTE]); + const key = Buffer$i.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$i.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; + } + bip32Derivation$1.makeConverter = makeConverter$2; + + var checkPubkey$1 = {}; + + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } + } + checkPubkey$1.makeChecker = makeChecker; + + var redeemScript$1 = {}; + + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$i.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + redeemScript$1.makeConverter = makeConverter$1; + + var witnessScript$1 = {}; + + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$i.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + witnessScript$1.makeConverter = makeConverter; + + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; + + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$i.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + + var toBuffer = {}; + + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$i.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$i.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$i.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); + } + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); + }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; + + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); + + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); + } + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; + } + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; + } + + var utils = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; + } + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; + } + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } + } + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; + } + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; + } + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); + } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; + } + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$i.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer$i.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$1; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + static fromBase64(data, opts = {}) { + const buffer = Buffer$i.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer$i.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); + } + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); + } + return results.every(res => res === true); + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } + } + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$i.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + throws = true; + } + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); + } + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); + } + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; + } + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; + } + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; + } + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$i.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$i.concat([buffer, Buffer$i.from(slice)]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$i.concat([buffer, Buffer$i.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } + + var transaction_builder = {}; + + var classify$1 = {}; + + var multisig$1 = {}; + + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); + } + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; + }; + + var output$e = {}; + + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; + }; + + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; + + var nulldata = {}; + + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; + }; + const output$c = { check: check$b }; + nulldata.output = output$c; + + var pubkey = {}; + + var input$9 = {}; + + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; + }; + + var output$b = {}; + + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; + }; + + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; + + var pubkeyhash = {}; + + var input$7 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; + }; + + var output$9 = {}; + + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; + }; + + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; + + var scripthash = {}; + + var input$5 = {}; + + var output$7 = {}; + + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; + + var output$6 = {}; + + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); + } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; + + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); + } + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; + } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; + + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); + } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; + + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; + + var witnesscommitment = {}; + + var output$3 = {}; + + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$i.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); + } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$i.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; + + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; + + var witnesspubkeyhash = {}; + + var input$3 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; + + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; + + var witnessscripthash = {}; + + var input$1 = {}; + + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; + + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; + + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; + + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$1; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); + } + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); + } + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, + }); + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; + } + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; + } + this.__USE_LOW_R = setting; + return setting; + } + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); + } + this.__TX.locktime = locktime; + } + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; + } + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$i.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); + } + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); + } + build() { + return this.__build(false); + } + buildIncomplete() { + return this.__build(true); + } + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); + } + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } + prevOutType = expanded.type; + } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; + } + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } + } + return tx; + } + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); + } + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); + } + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; + } + } + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; + } + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; + } + } + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); + } + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; + } + } + return { type }; + } + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, + }); + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); + } + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); + } + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); + } + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + } + } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); + } + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; + } + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); + } + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); + } + if (keyPair === undefined) { + throw new Error('sign requires keypair'); + } + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); + } + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } + + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$1; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$2 = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop$2() {} + + var on = noop$2; + var addListener = noop$2; + var once$2 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser$2, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once$2, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + const debug$4 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$4; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$3 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } + + debug$3('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$3('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$3('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self + } + + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted + } + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } + } + + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } + } + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$2('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$2 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$2('comp', comp, options); + comp = replaceCarets(comp, options); + debug$2('caret', comp); + comp = replaceTildes(comp, options); + debug$2('tildes', comp); + comp = replaceXRanges(comp, options); + debug$2('xrange', comp); + comp = replaceStars(comp, options); + debug$2('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$2('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$2('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$2('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$2('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$2('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$2('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } + + debug$2('caret return', ret); + return ret + }) + }; + + const replaceXRanges = (comp, options) => { + debug$2('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$2('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$2('xRange return', ret); + + return ret + }) + }; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$2('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; + + const replaceGTE0 = (comp, options) => { + debug$2('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$2(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + }; + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } + } + + debug$1('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug$1('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug$1('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } + } + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug$1 = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true + }; + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; + + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$i.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$i.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$i.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + var readable = {exports: {}}; + + var stream = require$$0__default$2["default"]; + + function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + + function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + var _require$2 = require$$0__default$1["default"], + Buffer$e = _require$2.Buffer; + + var _require2 = require$$1__default["default"], + inspect = _require2.inspect; + + var custom = inspect && inspect.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$e.prototype.copy.call(src, target, offset); + } + + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$e.alloc(0); + var ret = Buffer$e.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$e.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread$1({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; + }(); + + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); + } else { + nextTick(emitCloseNT, _this); + } + }); + + return this; + } + + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.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(self, err) { + self.emit('error', err); + } + + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } + + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; + + var errors = {}; + + const codes = {}; + + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; + } + + // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + + errors.codes = codes; + + var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; + } + + var state = { + getHighWaterMark: getHighWaterMark$2 + }; + + /** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + + var node = require$$1__default["default"].deprecate; + + var _stream_writable = Writable$1; + // there will be only 2 of these for each stream + + + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ + + /**/ + + + var Duplex$3; + /**/ + + Writable$1.WritableState = WritableState; + /**/ + + var internalUtil = { + deprecate: node + }; + /**/ + + /**/ + + var Stream$1 = stream; + /**/ + + + var Buffer$d = require$$0__default$1["default"].Buffer; + + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$d.from(chunk); + } + + function _isUint8Array$1(obj) { + return Buffer$d.isBuffer(obj) || obj instanceof OurUint8Array$1; + } + + var destroyImpl$1 = destroy_1; + + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; + + var _require$codes$3 = errors.codes, + ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + + inherits$f.exports(Writable$1, Stream$1); + + function nop() {} + + function WritableState(options, stream, isDuplex) { + Duplex$3 = Duplex$3 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + + + var realHasInstance; + + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$1, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$1) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } + + function Writable$1(options) { + Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$3; + if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. + + + Writable$1.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; + + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + + + function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } + + return true; + } + + Writable$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$d.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; + + Writable$1.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$d.from(chunk, encoding); + } + + return chunk; + } + + Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + + + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } // if there's something in the buffer waiting, then process it + + + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; + + Writable$1.prototype._writev = null; + + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + + function prefinish$1(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish$1(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; + } + + Object.defineProperty(Writable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl$1.destroy; + Writable$1.prototype._undestroy = destroyImpl$1.undestroy; + + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; + + /**/ + + var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; + }; + /**/ + + + var _stream_duplex = Duplex$2; + + var Readable$1 = _stream_readable; + + var Writable = _stream_writable; + + inherits$f.exports(Duplex$2, Readable$1); + + { + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; + } + } + + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); + Readable$1.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } + } + + Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer + + function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + Object.defineProperty(Duplex$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + var string_decoder = {}; + + /**/ + + var Buffer$c = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$c.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$c.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. + string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$c.allocUnsafe(nb); + } + + StringDecoder$2.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$2.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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); + 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) : ''; + } + + var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; + + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; + } + + function noop$1() {} + + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } + + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } + + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty$1(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty$1(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty$1(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; + + var async_iterator = createReadableStreamAsyncIterator$1; + + 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); }); }; } + + 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; + + function from$1(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; + } + + var from_1 = from$1; + + var _stream_readable = Readable; + /**/ + + var Duplex$1; + /**/ + + Readable.ReadableState = ReadableState; + /**/ + + EventEmitter__default["default"].EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + /**/ + + + var Stream = stream; + /**/ + + + var Buffer$b = require$$0__default$1["default"].Buffer; + + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer(chunk) { + return Buffer$b.from(chunk); + } + + function _isUint8Array(obj) { + return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ + + + var debugUtil = require$$1__default["default"]; + + var debug; + + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function debug() {}; + } + /**/ + + + var BufferList = buffer_list; + + var destroyImpl = destroy_1; + + var _require = state, + getHighWaterMark = _require.getHighWaterMark; + + var _require$codes$2 = errors.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; + + inherits$f.exports(Readable, Stream); + + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState(options, stream, isDuplex) { + Duplex$1 = Duplex$1 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + Duplex$1 = Duplex$1 || _stream_duplex; + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$1; + this._readableState = new ReadableState(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); + } + + Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + + + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer$b.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() + + + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$b.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + + maybeReadMore(stream, state); + } + + function chunkInvalid(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; + } + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. + + + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB + + + var MAX_HWM = 0x40000000; + + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; + } // you can override either this method, or the async _read(n) below. + + + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; + }; + + function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + + + function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_, stream); + } + } + + function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + + + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something + + + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + nextTick(nReadingNextTick, this); + } + } + } + + return res; + }; + + Readable.prototype.addListener = Readable.prototype.on; + + Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + + + Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume(this, state); + } + + state.paused = false; + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + + + Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } + + return createReadableStreamAsyncIterator(this); + }; + } + + Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + + if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = from_1; + } + + return from(Readable, iterable, opts); + }; + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; + } + + var _stream_transform = Transform$3; + + var _require$codes$1 = errors.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + + var Duplex = _stream_duplex; + + inherits$f.exports(Transform$3, Duplex); + + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform$3(options) { + if (!(this instanceof Transform$3)) return new Transform$3(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish); + } + + function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + + Transform$3.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + + + Transform$3.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + + Transform$3.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + + + Transform$3.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform$3.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + + var _stream_passthrough = PassThrough; + + var Transform$2 = _stream_transform; + + inherits$f.exports(PassThrough, Transform$2); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform$2.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + var eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + + var _require$codes = errors.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } + + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + + function call(fn) { + fn(); + } + + function pipe(from, to) { + return from.pipe(to); + } + + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + + var pipeline_1 = pipeline; + + (function (module, exports) { + var Stream = require$$0__default$2["default"]; + { + exports = module.exports = _stream_readable; + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + } + }(readable, readable.exports)); + + var Buffer$a = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$a = inherits$f.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$a.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } + + function HashBase$2 (blockSize) { + Transform$1.call(this); + + this._block = Buffer$a.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + + this._finalized = false; + } + + inherits$a(HashBase$2, Transform$1); + + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$a.isBuffer(data)) data = Buffer$a.from(data, encoding); + + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } + + return this + }; + + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; + + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; + + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); + + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; + + return digest + }; + + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; + + var hashBase = HashBase$2; + + var Buffer$9 = require$$0__default$1["default"].Buffer; + var inherits$9 = inherits$f.exports; + var HashBase$1 = hashBase; + + var ARRAY16$1 = new Array(16); + + var zl = [ + 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 zr = [ + 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 sl = [ + 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 sr = [ + 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 + ]; + + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + + function RIPEMD160$1 () { + HashBase$1.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } + + inherits$9(RIPEMD160$1, HashBase$1); + + RIPEMD160$1.prototype._update = function () { + var words = ARRAY16$1; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; + + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } + + al = el; + el = dl; + dl = rotl$1(cl, 10); + cl = bl; + bl = tl; + + ar = er; + er = dr; + dr = rotl$1(cr, 10); + cr = br; + br = tr; + } + + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; + + RIPEMD160$1.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$9.alloc ? Buffer$9.alloc(20) : new Buffer$9(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; + + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + var ripemd160$1 = RIPEMD160$1; + + var sha_js = {exports: {}}; + + var Buffer$8 = safeBuffer.exports.Buffer; + + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$8.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$8.from(data, enc); + } + + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } + } + + this._len += length; + return this + }; + + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; + + this._block[rem] = 0x80; + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + + var bits = this._len * 8; + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; + + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash + }; + + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; + + var hash = Hash$7; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits$8 = inherits$f.exports; + var Hash$6 = hash; + var Buffer$7 = safeBuffer.exports.Buffer; + + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; + + Hash$6.call(this, 64, 56); + } + + inherits$8(Sha, Hash$6); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } + + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha$2 = Sha; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits$7 = inherits$f.exports; + var Hash$5 = hash; + var Buffer$6 = safeBuffer.exports.Buffer; + + var K$2 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); + } + + inherits$7(Sha1, Hash$5); + + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha1.prototype._hash = function () { + var H = Buffer$6.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha1 = Sha1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$6 = inherits$f.exports; + var Hash$4 = hash; + var Buffer$5 = safeBuffer.exports.Buffer; + + var K$1 = [ + 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 W$3 = new Array(64); + + function Sha256$1 () { + this.init(); + + this._w = W$3; // new Array(64) + + Hash$4.call(this, 64, 56); + } + + inherits$6(Sha256$1, Hash$4); + + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; + + return this + }; + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256$1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; + + Sha256$1.prototype._hash = function () { + var H = Buffer$5.allocUnsafe(32); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + + return H + }; + + var sha256$1 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$5 = inherits$f.exports; + var Sha256 = sha256$1; + var Hash$3 = hash; + var Buffer$4 = safeBuffer.exports.Buffer; + + var W$2 = new Array(64); + + function Sha224 () { + this.init(); + + this._w = W$2; // new Array(64) + + Hash$3.call(this, 64, 56); + } + + inherits$5(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this + }; + + Sha224.prototype._hash = function () { + var H = Buffer$4.allocUnsafe(28); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H + }; + + var sha224 = Sha224; + + var inherits$4 = inherits$f.exports; + var Hash$2 = hash; + var Buffer$3 = safeBuffer.exports.Buffer; + + 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 W$1 = new Array(160); + + function Sha512 () { + this.init(); + this._w = W$1; + + Hash$2.call(this, 128, 112); + } + + inherits$4(Sha512, Hash$2); + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this + }; + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } + + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } + + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } + + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } + + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w; + + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); + + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; + + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; + + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + + W[i] = Wih; + W[i + 1] = Wil; + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; + + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); + + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j]; + var Kil = K[j + 1]; + + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); + + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } + + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; + + Sha512.prototype._hash = function () { + var H = Buffer$3.allocUnsafe(64); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + + return H + }; + + var sha512 = Sha512; + + var inherits$3 = inherits$f.exports; + var SHA512 = sha512; + var Hash$1 = hash; + var Buffer$2 = safeBuffer.exports.Buffer; + + var W = new Array(160); + + function Sha384 () { + this.init(); + this._w = W; + + Hash$1.call(this, 128, 112); + } + + inherits$3(Sha384, SHA512); + + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; + + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; + + return this + }; + + Sha384.prototype._hash = function () { + var H = Buffer$2.allocUnsafe(48); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H + }; + + var sha384 = Sha384; + + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() + }; + + exports$1.sha = sha$2; + exports$1.sha1 = sha1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$1; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; + + var sha$1 = sha_js.exports; + + function hashPublicKey(buffer) { + return new ripemd160$1().update(sha$1("sha256").update(buffer).digest()).digest(); + } + + var __extends$4 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$4(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$4(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$4(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$i.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$i.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$i.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$i.concat([ + Buffer$i.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$i.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$4(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$i.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$i.concat([Buffer$i.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$4(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$i.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$i.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$i.concat([Buffer$i.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$i.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$i.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$i.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$i.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$i.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$i.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } + + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$5.apply(this, arguments); + }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); + }; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); + }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + }; + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); + }; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$i.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); + } + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; + } + }; + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$i.from(k.substring(2), "hex")); + } + }); + return result; + }; + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$i.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); + }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$i.from([])); + this.globalMap.set(key.toString(), value); + }; + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); + }; + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); + }; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); + }; + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$i.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); + }; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; + } + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$i.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer$i.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$i.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + var b = Buffer$i.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); + } + } + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); + } + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); + } + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$i.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$i.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$i.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$i.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$i.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$i.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$i.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$i.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$i.concat([ + inputBuffer, + input.prevout, + Buffer$i.from([0x00]), + input.sequence, + ]) + : Buffer$i.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$i.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$i.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$i.alloc(0), + transaction.extraData || Buffer$i.alloc(0), + ]); + } + return Buffer$i.concat([ + transaction.version, + timestamp ? timestamp : Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), + useWitness ? Buffer$i.from("0001", "hex") : Buffer$i.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } + /** + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. + */ + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; + } + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$i.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); + }; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$i.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); + }; + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$i.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); + }; + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); + }); + }; + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$i.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); + }; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$i.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); + }); + }; + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$2 = 0; + var subscribers$1 = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log$1 = function (type, message, data) { + var obj = { + type: type, + id: String(++id$2), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch$1(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen$1 = function (cb) { + subscribers$1.push(cb); + return function () { + var i = subscribers$1.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; + subscribers$1.pop(); + } + }; + }; + function dispatch$1(log) { + for (var i = 0; i < subscribers$1.length; i++) { + try { + subscribers$1[i](log); + } + catch (e) { + console.error(e); + } + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen$1; + } + + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log$1, + listen: listen$1 + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var invariant_1 = invariant; + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$i.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$i.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$i.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$i.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$i.concat([ + transaction.version, + transaction.timestamp || Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$i.compare(version, Buffer$i.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$i.from([0x00]) + : Buffer$i.alloc(0); + data = Buffer$i.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$i.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$i.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$i.concat([ + output.amount, + isDecred ? Buffer$i.from([0x00, 0x00]) : Buffer$i.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$i.concat(endData); + extraPart = isDecred + ? data + : Buffer$i.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$i.concat([locktime, extraPart || Buffer$i.alloc(0)]))]; + case 20: + res = _c.sent(); + invariant_1(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$i.concat([ + transaction.version, + transaction.timestamp || Buffer$i.alloc(0), + transaction.nVersionGroupId || Buffer$i.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$i.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$i.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$i.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$i.from([0x00]); + } + } + data = Buffer$i.concat([ + prefix, + inputValue, + isDecred ? Buffer$i.from([0x00]) : Buffer$i.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$i.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha$1("sha256") + .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$i.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$i.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$i.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$i.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$i.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$i.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$i.from([0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([sigHashType]), + ]) + : Buffer$i.concat([ + pathsBuffer, + Buffer$i.from([0x00]), + lockTimeBuffer, + Buffer$i.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$i.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + invariant_1(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } + + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$i.alloc(0); + nullPrevout = Buffer$i.alloc(0); + defaultVersion = Buffer$i.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$i.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$i.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log$1("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$i.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$i.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$i.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$i.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$i.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$i.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$i.concat([ + Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$i.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$i.concat([ + Buffer$i.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$i.alloc(1); + keySize = Buffer$i.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$i.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$i.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$i.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$i.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$i.concat([ + Buffer$i.from("02", "hex"), + Buffer$i.from([signatures[i].length]), + signatures[i], + Buffer$i.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$i.concat([witness, tmpScriptData]); + } + result = Buffer$i.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$i.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$i.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$i.alloc(0), + targetTransaction.extraData || Buffer$i.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$i.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$i.concat([ + decredWitness_1, + Buffer$i.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([0x00, 0x00, 0x00, 0x00]), + Buffer$i.from([0xff, 0xff, 0xff, 0xff]), + Buffer$i.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$i.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } + + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$i.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$i.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$i.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } + + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$i.alloc(0); + nullPrevout = Buffer$i.alloc(0); + defaultVersion = Buffer$i.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$i.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$i.from(trustedInput, "hex") + : Buffer$i.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$i.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$i.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } + + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$i.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$i.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$i.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$i.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$i.concat([ + Buffer$i.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$i.concat([ + asBufferUInt32BE(version), + Buffer$i.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$i.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$1("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$1().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$i.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$i.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$i.from(request.subarray(1))); + this.progressCallback(); + return Buffer$i.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$i.from([known_preimage[i]])); + } + } + return Buffer$i.concat([ + preimage_len_varint, + Buffer$i.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$i.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$i.from([proof.length]), + Buffer$i.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$i.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$i.concat([Buffer$i.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$i.concat(__spreadArray$1([ + Buffer$i.from([n_returned_elements]), + Buffer$i.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } + } + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$i.concat([Buffer$i.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); + + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$i.concat([ + Buffer$i.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$i.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$i.concat([ + Buffer$i.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$i.alloc(32, 0), + Buffer$i.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$i.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$i.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$i.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$i.alloc(0); + var nExpiryHeight = Buffer$i.alloc(0); + var nVersionGroupId = Buffer$i.alloc(0); + var extraData = Buffer$i.alloc(0); + var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); + var transaction = Buffer$i.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$i.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$i.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$i.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$i.from([0x02, 0x00, 0x00, 0x00])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$i.alloc(0); + var tree = Buffer$i.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } + + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@backpacker69/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses$1 = {}; + var deserializers$1 = {}; + var addCustomErrorDeserializer$1 = function (name, deserializer) { + deserializers$1[name] = deserializer; + }; + var createCustomErrorClass$1 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$1[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers$1[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass$1(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); + var AmountRequired = createCustomErrorClass$1("AmountRequired"); + var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass$1("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass$1("NetworkDown"); + var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); + var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass$1("FeeRequired"); + var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); + var SyncError = createCustomErrorClass$1("SyncError"); + var PairingFailed = createCustomErrorClass$1("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); + var DBNotReset = createCustomErrorClass$1("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$1(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); + var StatusCodes$1 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$1(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$1(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$1(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); + + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass$1, + addCustomErrorDeserializer: addCustomErrorDeserializer$1, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition$1, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError$1, + StatusCodes: StatusCodes$1, + getAltStatusMessage: getAltStatusMessage$1, + TransportStatusError: TransportStatusError$1 + }); + + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport$1 = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter__default["default"](); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$i.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$i.concat([ + Buffer$i.from([cla, ins, p1, p2]), + Buffer$i.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError$1(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; + } + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); + }; + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); + }; + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); + }; + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + }; + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } + } + }; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); + + var hidFraming$1 = {}; + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$i.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$i.alloc(0), + dataLength: 0, + sequence: 0 + }; + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$i.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$i.concat([ + data, + Buffer$i.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$i.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$i.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$i.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + exports["default"] = createHIDframing; + + }(hidFraming$1)); + + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + + var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + var _a; + var DeviceModelId; + (function (DeviceModelId) { + DeviceModelId["blue"] = "blue"; + DeviceModelId["nanoS"] = "nanoS"; + DeviceModelId["nanoSP"] = "nanoSP"; + DeviceModelId["nanoX"] = "nanoX"; + })(DeviceModelId || (DeviceModelId = {})); + var devices = (_a = {}, + _a[DeviceModelId.blue] = { + id: DeviceModelId.blue, + productName: "Ledger Blue", + productIdMM: 0x00, + legacyUsbProductId: 0x0000, + usbOnly: true, + memorySize: 480 * 1024, + masks: [0x31000000, 0x31010000], + getBlockSize: function (_firwareVersion) { return 4 * 1024; } + }, + _a[DeviceModelId.nanoS] = { + id: DeviceModelId.nanoS, + productName: "Ledger Nano S", + productIdMM: 0x10, + legacyUsbProductId: 0x0001, + usbOnly: true, + memorySize: 320 * 1024, + masks: [0x31100000], + getBlockSize: function (firmwareVersion) { + var _a; + return semver.lt((_a = semver.coerce(firmwareVersion)) !== null && _a !== void 0 ? _a : "", "2.0.0") + ? 4 * 1024 + : 2 * 1024; + } + }, + _a[DeviceModelId.nanoSP] = { + id: DeviceModelId.nanoSP, + productName: "Ledger Nano SP", + productIdMM: 0x50, + legacyUsbProductId: 0x0005, + usbOnly: true, + memorySize: 1533 * 1024, + masks: [0x33100000], + getBlockSize: function (_firmwareVersion) { return 32; } + }, + _a[DeviceModelId.nanoX] = { + id: DeviceModelId.nanoX, + productName: "Ledger Nano X", + productIdMM: 0x40, + legacyUsbProductId: 0x0004, + usbOnly: false, + memorySize: 2 * 1024 * 1024, + masks: [0x33000000], + getBlockSize: function (_firwareVersion) { return 4 * 1024; }, + bluetoothSpec: [ + { + // this is the legacy one (prototype version). we will eventually drop it. + serviceUuid: "d973f2e0-b19e-11e2-9e96-0800200c9a66", + notifyUuid: "d973f2e1-b19e-11e2-9e96-0800200c9a66", + writeUuid: "d973f2e2-b19e-11e2-9e96-0800200c9a66", + writeCmdUuid: "d973f2e3-b19e-11e2-9e96-0800200c9a66" + }, + { + serviceUuid: "13d63400-2c97-0004-0000-4c6564676572", + notifyUuid: "13d63400-2c97-0004-0001-4c6564676572", + writeUuid: "13d63400-2c97-0004-0002-4c6564676572", + writeCmdUuid: "13d63400-2c97-0004-0003-4c6564676572" + }, + ] + }, + _a); + ({ + Blue: DeviceModelId.blue, + "Nano S": DeviceModelId.nanoS, + "Nano X": DeviceModelId.nanoX + }); + var devicesList = Object.values(devices); + /** + * + */ + var ledgerUSBVendorId = 0x2c97; + /** + * + */ + var identifyUSBProductId = function (usbProductId) { + var legacy = devicesList.find(function (d) { return d.legacyUsbProductId === usbProductId; }); + if (legacy) + return legacy; + var mm = usbProductId >> 8; + var deviceModel = devicesList.find(function (d) { return d.productIdMM === mm; }); + return deviceModel; + }; + var bluetoothServices = []; + var serviceUuidToInfos = {}; + for (var id$1 in devices) { + var deviceModel = devices[id$1]; + var bluetoothSpec = deviceModel.bluetoothSpec; + if (bluetoothSpec) { + for (var i = 0; i < bluetoothSpec.length; i++) { + var spec = bluetoothSpec[i]; + bluetoothServices.push(spec.serviceUuid); + serviceUuidToInfos[spec.serviceUuid] = serviceUuidToInfos[spec.serviceUuid.replace(/-/g, "")] = __assign({ deviceModel: deviceModel }, spec); + } + } + } + + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var ledgerDevices = [ + { + vendorId: ledgerUSBVendorId + }, + ]; + function requestLedgerDevice() { + return __awaiter$1(this, void 0, void 0, function () { + var device; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, navigator.usb.requestDevice({ + filters: ledgerDevices + })]; + case 1: + device = _a.sent(); + return [2 /*return*/, device]; + } + }); + }); + } + function getLedgerDevices() { + return __awaiter$1(this, void 0, void 0, function () { + var devices; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, navigator.usb.getDevices()]; + case 1: + devices = _a.sent(); + return [2 /*return*/, devices.filter(function (d) { return d.vendorId === ledgerUSBVendorId; })]; + } + }); + }); + } + function getFirstLedgerDevice() { + return __awaiter$1(this, void 0, void 0, function () { + var existingDevices; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getLedgerDevices()]; + case 1: + existingDevices = _a.sent(); + if (existingDevices.length > 0) + return [2 /*return*/, existingDevices[0]]; + return [2 /*return*/, requestLedgerDevice()]; + } + }); + }); + } + var isSupported$1 = function () { + return Promise.resolve(!!navigator && + !!navigator.usb && + typeof navigator.usb.getDevices === "function"); + }; + + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var configurationValue = 1; + var endpointNumber = 3; + /** + * WebUSB Transport implementation + * @example + * import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; + * ... + * TransportWebUSB.create().then(transport => ...) + */ + var TransportWebUSB = /** @class */ (function (_super) { + __extends(TransportWebUSB, _super); + function TransportWebUSB(device, interfaceNumber) { + var _this = _super.call(this) || this; + _this.channel = Math.floor(Math.random() * 0xffff); + _this.packetSize = 64; + _this._disconnectEmitted = false; + _this._emitDisconnect = function (e) { + if (_this._disconnectEmitted) + return; + _this._disconnectEmitted = true; + _this.emit("disconnect", e); + }; + _this.device = device; + _this.interfaceNumber = interfaceNumber; + _this.deviceModel = identifyUSBProductId(device.productId); + return _this; + } + /** + * Similar to create() except it will always display the device permission (even if some devices are already accepted). + */ + TransportWebUSB.request = function () { + return __awaiter(this, void 0, void 0, function () { + var device; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, requestLedgerDevice()]; + case 1: + device = _a.sent(); + return [2 /*return*/, TransportWebUSB.open(device)]; + } + }); + }); + }; + /** + * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). + */ + TransportWebUSB.openConnected = function () { + return __awaiter(this, void 0, void 0, function () { + var devices; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getLedgerDevices()]; + case 1: + devices = _a.sent(); + if (devices.length === 0) + return [2 /*return*/, null]; + return [2 /*return*/, TransportWebUSB.open(devices[0])]; + } + }); + }); + }; + /** + * Create a Ledger transport with a USBDevice + */ + TransportWebUSB.open = function (device) { + return __awaiter(this, void 0, void 0, function () { + var iface, interfaceNumber, e_1, transport, onDisconnect; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, device.open()]; + case 1: + _a.sent(); + if (!(device.configuration === null)) return [3 /*break*/, 3]; + return [4 /*yield*/, device.selectConfiguration(configurationValue)]; + case 2: + _a.sent(); + _a.label = 3; + case 3: return [4 /*yield*/, gracefullyResetDevice(device)]; + case 4: + _a.sent(); + iface = device.configurations[0].interfaces.find(function (_a) { + var alternates = _a.alternates; + return alternates.some(function (a) { return a.interfaceClass === 255; }); + }); + if (!iface) { + throw new TransportInterfaceNotAvailable("No WebUSB interface found for your Ledger device. Please upgrade firmware or contact techsupport."); + } + interfaceNumber = iface.interfaceNumber; + _a.label = 5; + case 5: + _a.trys.push([5, 7, , 9]); + return [4 /*yield*/, device.claimInterface(interfaceNumber)]; + case 6: + _a.sent(); + return [3 /*break*/, 9]; + case 7: + e_1 = _a.sent(); + return [4 /*yield*/, device.close()]; + case 8: + _a.sent(); + throw new TransportInterfaceNotAvailable(e_1.message); + case 9: + transport = new TransportWebUSB(device, interfaceNumber); + onDisconnect = function (e) { + if (device === e.device) { + // $FlowFixMe + navigator.usb.removeEventListener("disconnect", onDisconnect); + transport._emitDisconnect(new DisconnectedDevice()); + } + }; + // $FlowFixMe + navigator.usb.addEventListener("disconnect", onDisconnect); + return [2 /*return*/, transport]; + } + }); + }); + }; + /** + * Release the transport device + */ + TransportWebUSB.prototype.close = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.exchangeBusyPromise]; + case 1: + _a.sent(); + return [4 /*yield*/, this.device.releaseInterface(this.interfaceNumber)]; + case 2: + _a.sent(); + return [4 /*yield*/, gracefullyResetDevice(this.device)]; + case 3: + _a.sent(); + return [4 /*yield*/, this.device.close()]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }; + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + TransportWebUSB.prototype.exchange = function (apdu) { + return __awaiter(this, void 0, void 0, function () { + var b; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { + var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = this, channel = _a.channel, packetSize = _a.packetSize; + log$1("apdu", "=> " + apdu.toString("hex")); + framing = hidFraming(channel, packetSize); + blocks = framing.makeBlocks(apdu); + i = 0; + _b.label = 1; + case 1: + if (!(i < blocks.length)) return [3 /*break*/, 4]; + return [4 /*yield*/, this.device.transferOut(endpointNumber, blocks[i])]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: + if (!!(result = framing.getReducedResult(acc))) return [3 /*break*/, 6]; + return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; + case 5: + r = _b.sent(); + buffer = Buffer$i.from(r.data.buffer); + acc = framing.reduceResponse(acc, buffer); + return [3 /*break*/, 4]; + case 6: + log$1("apdu", "<= " + result.toString("hex")); + return [2 /*return*/, result]; + } + }); + }); })["catch"](function (e) { + if (e && e.message && e.message.includes("disconnected")) { + _this._emitDisconnect(e); + throw new DisconnectedDeviceDuringOperation(e.message); + } + throw e; + })]; + case 1: + b = _a.sent(); + return [2 /*return*/, b]; + } + }); + }); + }; + TransportWebUSB.prototype.setScrambleKey = function () { }; + /** + * Check if WebUSB transport is supported. + */ + TransportWebUSB.isSupported = isSupported$1; + /** + * List the WebUSB devices that was previously authorized by the user. + */ + TransportWebUSB.list = getLedgerDevices; + /** + * Actively listen to WebUSB devices and emit ONE device + * that was either accepted before, if not it will trigger the native permission UI. + * + * Important: it must be called in the context of a UI click! + */ + TransportWebUSB.listen = function (observer) { + var unsubscribed = false; + getFirstLedgerDevice().then(function (device) { + if (!unsubscribed) { + var deviceModel = identifyUSBProductId(device.productId); + observer.next({ + type: "add", + descriptor: device, + deviceModel: deviceModel + }); + observer.complete(); + } + }, function (error) { + if (window.DOMException && + error instanceof window.DOMException && + error.code === 18) { + observer.error(new TransportWebUSBGestureRequired(error.message)); + } + else { + observer.error(new TransportOpenUserCancelled(error.message)); + } + }); + function unsubscribe() { + unsubscribed = true; + } + return { + unsubscribe: unsubscribe + }; + }; + return TransportWebUSB; + }(Transport$1)); + function gracefullyResetDevice(device) { + return __awaiter(this, void 0, void 0, function () { + var err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, device.reset()]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + err_1 = _a.sent(); + console.warn(err_1); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': TransportWebUSB + }); + + /** Namespace for the U2F api. + * @type {Object} + */ + var u2f = u2f || {}; + + var googleU2fApi = u2f; // Adaptation for u2f-api package + + /** + * The U2F extension id + * @type {string} + * @const + */ + u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; + + /** + * Message types for messsages to/from the extension + * @const + * @enum {string} + */ + u2f.MessageTypes = { + 'U2F_REGISTER_REQUEST': 'u2f_register_request', + 'U2F_SIGN_REQUEST': 'u2f_sign_request', + 'U2F_REGISTER_RESPONSE': 'u2f_register_response', + 'U2F_SIGN_RESPONSE': 'u2f_sign_response' + }; + + /** + * Response status codes + * @const + * @enum {number} + */ + u2f.ErrorCodes = { + 'OK': 0, + 'OTHER_ERROR': 1, + 'BAD_REQUEST': 2, + 'CONFIGURATION_UNSUPPORTED': 3, + 'DEVICE_INELIGIBLE': 4, + 'TIMEOUT': 5 + }; + + /** + * A message type for registration requests + * @typedef {{ + * type: u2f.MessageTypes, + * signRequests: Array., + * registerRequests: ?Array., + * timeoutSeconds: ?number, + * requestId: ?number + * }} + */ + u2f.Request; + + /** + * A message for registration responses + * @typedef {{ + * type: u2f.MessageTypes, + * responseData: (u2f.Error | u2f.RegisterResponse | u2f.SignResponse), + * requestId: ?number + * }} + */ + u2f.Response; + + /** + * An error object for responses + * @typedef {{ + * errorCode: u2f.ErrorCodes, + * errorMessage: ?string + * }} + */ + u2f.Error; + + /** + * Data object for a single sign request. + * @typedef {{ + * version: string, + * challenge: string, + * keyHandle: string, + * appId: string + * }} + */ + u2f.SignRequest; + + /** + * Data object for a sign response. + * @typedef {{ + * keyHandle: string, + * signatureData: string, + * clientData: string + * }} + */ + u2f.SignResponse; + + /** + * Data object for a registration request. + * @typedef {{ + * version: string, + * challenge: string, + * appId: string + * }} + */ + u2f.RegisterRequest; + + /** + * Data object for a registration response. + * @typedef {{ + * registrationData: string, + * clientData: string + * }} + */ + u2f.RegisterResponse; + + + // Low level MessagePort API support + + /** + * Call MessagePort disconnect + */ + u2f.disconnect = function() { + if (u2f.port_ && u2f.port_.port_) { + u2f.port_.port_.disconnect(); + u2f.port_ = null; + } + }; + + /** + * Sets up a MessagePort to the U2F extension using the + * available mechanisms. + * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback + */ + u2f.getMessagePort = function(callback) { + if (typeof chrome != 'undefined' && chrome.runtime) { + // The actual message here does not matter, but we need to get a reply + // for the callback to run. Thus, send an empty signature request + // in order to get a failure response. + var msg = { + type: u2f.MessageTypes.U2F_SIGN_REQUEST, + signRequests: [] + }; + chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { + if (!chrome.runtime.lastError) { + // We are on a whitelisted origin and can talk directly + // with the extension. + u2f.getChromeRuntimePort_(callback); + } else { + // chrome.runtime was available, but we couldn't message + // the extension directly, use iframe + u2f.getIframePort_(callback); + } + }); + } else { + // chrome.runtime was not available at all, which is normal + // when this origin doesn't have access to any extensions. + u2f.getIframePort_(callback); + } + }; + + /** + * Connects directly to the extension via chrome.runtime.connect + * @param {function(u2f.WrappedChromeRuntimePort_)} callback + * @private + */ + u2f.getChromeRuntimePort_ = function(callback) { + var port = chrome.runtime.connect(u2f.EXTENSION_ID, + {'includeTlsChannelId': true}); + setTimeout(function() { + callback(null, new u2f.WrappedChromeRuntimePort_(port)); + }, 0); + }; + + /** + * A wrapper for chrome.runtime.Port that is compatible with MessagePort. + * @param {Port} port + * @constructor + * @private + */ + u2f.WrappedChromeRuntimePort_ = function(port) { + this.port_ = port; + }; + + /** + * Posts a message on the underlying channel. + * @param {Object} message + */ + u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { + this.port_.postMessage(message); + }; + + /** + * Emulates the HTML 5 addEventListener interface. Works only for the + * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. + * @param {string} eventName + * @param {function({data: Object})} handler + */ + u2f.WrappedChromeRuntimePort_.prototype.addEventListener = + function(eventName, handler) { + var name = eventName.toLowerCase(); + if (name == 'message' || name == 'onmessage') { + this.port_.onMessage.addListener(function(message) { + // Emulate a minimal MessageEvent object + handler({'data': message}); + }); + } else { + console.error('WrappedChromeRuntimePort only supports onMessage'); + } + }; + + /** + * Sets up an embedded trampoline iframe, sourced from the extension. + * @param {function(MessagePort)} callback + * @private + */ + u2f.getIframePort_ = function(callback) { + // Create the iframe + var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; + var iframe = document.createElement('iframe'); + iframe.src = iframeOrigin + '/u2f-comms.html'; + iframe.setAttribute('style', 'display:none'); + document.body.appendChild(iframe); + + var hasCalledBack = false; + + var channel = new MessageChannel(); + var ready = function(message) { + if (message.data == 'ready') { + channel.port1.removeEventListener('message', ready); + if (!hasCalledBack) + { + hasCalledBack = true; + callback(null, channel.port1); + } + } else { + console.error('First event on iframe port was not "ready"'); + } + }; + channel.port1.addEventListener('message', ready); + channel.port1.start(); + + iframe.addEventListener('load', function() { + // Deliver the port to the iframe and initialize + iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); + }); + + // Give this 200ms to initialize, after that, we treat this method as failed + setTimeout(function() { + if (!hasCalledBack) + { + hasCalledBack = true; + callback(new Error("IFrame extension not supported")); + } + }, 200); + }; + + + // High-level JS API + + /** + * Default extension response timeout in seconds. + * @const + */ + u2f.EXTENSION_TIMEOUT_SEC = 30; + + /** + * A singleton instance for a MessagePort to the extension. + * @type {MessagePort|u2f.WrappedChromeRuntimePort_} + * @private + */ + u2f.port_ = null; + + /** + * Callbacks waiting for a port + * @type {Array.} + * @private + */ + u2f.waitingForPort_ = []; + + /** + * A counter for requestIds. + * @type {number} + * @private + */ + u2f.reqCounter_ = 0; + + /** + * A map from requestIds to client callbacks + * @type {Object.} + * @private + */ + u2f.callbackMap_ = {}; + + /** + * Creates or retrieves the MessagePort singleton to use. + * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback + * @private + */ + u2f.getPortSingleton_ = function(callback) { + if (u2f.port_) { + callback(null, u2f.port_); + } else { + if (u2f.waitingForPort_.length == 0) { + u2f.getMessagePort(function(err, port) { + if (!err) { + u2f.port_ = port; + u2f.port_.addEventListener('message', + /** @type {function(Event)} */ (u2f.responseHandler_)); + } + + // Careful, here be async callbacks. Maybe. + while (u2f.waitingForPort_.length) + u2f.waitingForPort_.shift()(err, port); + }); + } + u2f.waitingForPort_.push(callback); + } + }; + + /** + * Handles response messages from the extension. + * @param {MessageEvent.} message + * @private + */ + u2f.responseHandler_ = function(message) { + var response = message.data; + var reqId = response['requestId']; + if (!reqId || !u2f.callbackMap_[reqId]) { + console.error('Unknown or missing requestId in response.'); + return; + } + var cb = u2f.callbackMap_[reqId]; + delete u2f.callbackMap_[reqId]; + cb(null, response['responseData']); + }; + + /** + * Calls the callback with true or false as first and only argument + * @param {Function} callback + */ + u2f.isSupported = function(callback) { + u2f.getPortSingleton_(function(err, port) { + callback(!err); + }); + }; + + /** + * Dispatches an array of sign requests to available U2F tokens. + * @param {Array.} signRequests + * @param {function((u2f.Error|u2f.SignResponse))} callback + * @param {number=} opt_timeoutSeconds + */ + u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { + u2f.getPortSingleton_(function(err, port) { + if (err) + return callback(err); + + var reqId = ++u2f.reqCounter_; + u2f.callbackMap_[reqId] = callback; + var req = { + type: u2f.MessageTypes.U2F_SIGN_REQUEST, + signRequests: signRequests, + timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? + opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), + requestId: reqId + }; + port.postMessage(req); + }); + }; + + /** + * Dispatches register requests to available U2F tokens. An array of sign + * requests identifies already registered tokens. + * @param {Array.} registerRequests + * @param {Array.} signRequests + * @param {function((u2f.Error|u2f.RegisterResponse))} callback + * @param {number=} opt_timeoutSeconds + */ + u2f.register = function(registerRequests, signRequests, + callback, opt_timeoutSeconds) { + u2f.getPortSingleton_(function(err, port) { + if (err) + return callback(err); + + var reqId = ++u2f.reqCounter_; + u2f.callbackMap_[reqId] = callback; + var req = { + type: u2f.MessageTypes.U2F_REGISTER_REQUEST, + signRequests: signRequests, + registerRequests: registerRequests, + timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? + opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), + requestId: reqId + }; + port.postMessage(req); + }); + }; + + var u2fApi$1 = API; + + var chromeApi = googleU2fApi; + + // Feature detection (yes really) + var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; + var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) + && !navigator.userAgent.match( /Chrome\// ); + var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); + + var _backend = null; + function getBackend( Promise ) + { + if ( !_backend ) + _backend = new Promise( function( resolve, reject ) + { + function notSupported( ) + { + // Note; {native: true} means *not* using Google's hack + resolve( { u2f: null, native: true } ); + } + + if ( !isBrowser ) + return notSupported( ); + + if ( isSafari ) + // Safari doesn't support U2F, and the Safari-FIDO-U2F + // extension lacks full support (Multi-facet apps), so we + // block it until proper support. + return notSupported( ); + + var hasNativeSupport = + ( typeof window.u2f !== 'undefined' ) && + ( typeof window.u2f.sign === 'function' ); + + if ( hasNativeSupport ) + resolve( { u2f: window.u2f, native: true } ); + + if ( isEDGE ) + // We don't want to check for Google's extension hack on EDGE + // as it'll cause trouble (popups, etc) + return notSupported( ); + + if ( location.protocol === 'http:' ) + // U2F isn't supported over http, only https + return notSupported( ); + + if ( typeof MessageChannel === 'undefined' ) + // Unsupported browser, the chrome hack would throw + return notSupported( ); + + // Test for google extension support + chromeApi.isSupported( function( ok ) + { + if ( ok ) + resolve( { u2f: chromeApi, native: false } ); + else + notSupported( ); + } ); + } ); + + return _backend; + } + + function API( Promise ) + { + return { + isSupported : isSupported.bind( Promise ), + ensureSupport : ensureSupport.bind( Promise ), + register : register.bind( Promise ), + sign : sign.bind( Promise ), + ErrorCodes : API.ErrorCodes, + ErrorNames : API.ErrorNames + }; + } + + API.ErrorCodes = { + CANCELLED: -1, + OK: 0, + OTHER_ERROR: 1, + BAD_REQUEST: 2, + CONFIGURATION_UNSUPPORTED: 3, + DEVICE_INELIGIBLE: 4, + TIMEOUT: 5 + }; + API.ErrorNames = { + "-1": "CANCELLED", + "0": "OK", + "1": "OTHER_ERROR", + "2": "BAD_REQUEST", + "3": "CONFIGURATION_UNSUPPORTED", + "4": "DEVICE_INELIGIBLE", + "5": "TIMEOUT" + }; + + function makeError( msg, err ) + { + var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR + var type = API.ErrorNames[ '' + code ]; + var error = new Error( msg ); + error.metaData = { + type: type, + code: code + }; + return error; + } + + function deferPromise( Promise, promise ) + { + var ret = { }; + ret.promise = new Promise( function( resolve, reject ) { + ret.resolve = resolve; + ret.reject = reject; + promise.then( resolve, reject ); + } ); + /** + * Reject request promise and disconnect port if 'disconnect' flag is true + * @param {string} msg + * @param {boolean} disconnect + */ + ret.promise.cancel = function( msg, disconnect ) + { + getBackend( Promise ) + .then( function( backend ) + { + if ( disconnect && !backend.native ) + backend.u2f.disconnect( ); + + ret.reject( makeError( msg, { errorCode: -1 } ) ); + } ); + }; + return ret; + } + + function isSupported( ) + { + var Promise = this; + + return getBackend( Promise ) + .then( function( backend ) + { + return !!backend.u2f; + } ); + } + + function _ensureSupport( backend ) + { + if ( !backend.u2f ) + { + if ( location.protocol === 'http:' ) + throw new Error( "U2F isn't supported over http, only https" ); + throw new Error( "U2F not supported" ); + } + } + + function ensureSupport( ) + { + var Promise = this; + + return getBackend( Promise ) + .then( _ensureSupport ); + } + + function register( registerRequests, signRequests /* = null */, timeout ) + { + var Promise = this; + + if ( !Array.isArray( registerRequests ) ) + registerRequests = [ registerRequests ]; + + if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) + { + timeout = signRequests; + signRequests = null; + } + + if ( !signRequests ) + signRequests = [ ]; + + return deferPromise( Promise, getBackend( Promise ) + .then( function( backend ) + { + _ensureSupport( backend ); + + var native = backend.native; + var u2f = backend.u2f; + + return new Promise( function( resolve, reject ) + { + function cbNative( response ) + { + if ( response.errorCode ) + reject( makeError( "Registration failed", response ) ); + else + { + delete response.errorCode; + resolve( response ); + } + } + + function cbChrome( err, response ) + { + if ( err ) + reject( err ); + else if ( response.errorCode ) + reject( makeError( "Registration failed", response ) ); + else + resolve( response ); + } + + if ( native ) + { + var appId = registerRequests[ 0 ].appId; + + u2f.register( + appId, registerRequests, signRequests, cbNative, timeout ); + } + else + { + u2f.register( + registerRequests, signRequests, cbChrome, timeout ); + } + } ); + } ) ).promise; + } + + function sign( signRequests, timeout ) + { + var Promise = this; + + if ( !Array.isArray( signRequests ) ) + signRequests = [ signRequests ]; + + return deferPromise( Promise, getBackend( Promise ) + .then( function( backend ) + { + _ensureSupport( backend ); + + var native = backend.native; + var u2f = backend.u2f; + + return new Promise( function( resolve, reject ) + { + function cbNative( response ) + { + if ( response.errorCode ) + reject( makeError( "Sign failed", response ) ); + else + { + delete response.errorCode; + resolve( response ); + } + } + + function cbChrome( err, response ) + { + if ( err ) + reject( err ); + else if ( response.errorCode ) + reject( makeError( "Sign failed", response ) ); + else + resolve( response ); + } + + if ( native ) + { + var appId = signRequests[ 0 ].appId; + var challenge = signRequests[ 0 ].challenge; + + u2f.sign( appId, challenge, signRequests, cbNative, timeout ); + } + else + { + u2f.sign( signRequests, cbChrome, timeout ); + } + } ); + } ) ).promise; + } + + function makeDefault( func ) + { + API[ func ] = function( ) + { + if ( !commonjsGlobal.Promise ) + // This is very unlikely to ever happen, since browsers + // supporting U2F will most likely support Promises. + throw new Error( "The platform doesn't natively support promises" ); + + var args = [ ].slice.call( arguments ); + return API( commonjsGlobal.Promise )[ func ].apply( null, args ); + }; + } + + // Provide default functions using the built-in Promise if available. + makeDefault( 'isSupported' ); + makeDefault( 'ensureSupport' ); + makeDefault( 'register' ); + makeDefault( 'sign' ); + + var u2fApi = u2fApi$1; + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; + }; + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; + }; + + createCustomErrorClass("AccountNameRequired"); + createCustomErrorClass("AccountNotSupported"); + createCustomErrorClass("AmountRequired"); + createCustomErrorClass("BluetoothRequired"); + createCustomErrorClass("BtcUnmatchedApp"); + createCustomErrorClass("CantOpenDevice"); + createCustomErrorClass("CashAddrNotSupported"); + createCustomErrorClass("CurrencyNotSupported"); + createCustomErrorClass("DeviceAppVerifyNotSupported"); + createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + createCustomErrorClass("DeviceNotGenuine"); + createCustomErrorClass("DeviceOnDashboardExpected"); + createCustomErrorClass("DeviceOnDashboardUnexpected"); + createCustomErrorClass("DeviceInOSUExpected"); + createCustomErrorClass("DeviceHalted"); + createCustomErrorClass("DeviceNameInvalid"); + createCustomErrorClass("DeviceSocketFail"); + createCustomErrorClass("DeviceSocketNoBulkStatus"); + createCustomErrorClass("DisconnectedDevice"); + createCustomErrorClass("DisconnectedDeviceDuringOperation"); + createCustomErrorClass("EnpointConfig"); + createCustomErrorClass("EthAppPleaseEnableContractData"); + createCustomErrorClass("FeeEstimationFailed"); + createCustomErrorClass("FirmwareNotRecognized"); + createCustomErrorClass("HardResetFail"); + createCustomErrorClass("InvalidXRPTag"); + createCustomErrorClass("InvalidAddress"); + createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + createCustomErrorClass("LatestMCUInstalledError"); + createCustomErrorClass("UnknownMCU"); + createCustomErrorClass("LedgerAPIError"); + createCustomErrorClass("LedgerAPIErrorWithMessage"); + createCustomErrorClass("LedgerAPINotAvailable"); + createCustomErrorClass("ManagerAppAlreadyInstalled"); + createCustomErrorClass("ManagerAppRelyOnBTC"); + createCustomErrorClass("ManagerAppDepInstallRequired"); + createCustomErrorClass("ManagerAppDepUninstallRequired"); + createCustomErrorClass("ManagerDeviceLocked"); + createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + createCustomErrorClass("ManagerNotEnoughSpace"); + createCustomErrorClass("ManagerUninstallBTCDep"); + createCustomErrorClass("NetworkDown"); + createCustomErrorClass("NoAddressesFound"); + createCustomErrorClass("NotEnoughBalance"); + createCustomErrorClass("NotEnoughBalanceToDelegate"); + createCustomErrorClass("NotEnoughBalanceInParentAccount"); + createCustomErrorClass("NotEnoughSpendableBalance"); + createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + createCustomErrorClass("NoAccessToCamera"); + createCustomErrorClass("NotEnoughGas"); + createCustomErrorClass("NotSupportedLegacyAddress"); + createCustomErrorClass("GasLessThanEstimate"); + createCustomErrorClass("PasswordsDontMatch"); + createCustomErrorClass("PasswordIncorrect"); + createCustomErrorClass("RecommendSubAccountsToEmpty"); + createCustomErrorClass("RecommendUndelegation"); + createCustomErrorClass("TimeoutTagged"); + createCustomErrorClass("UnexpectedBootloader"); + createCustomErrorClass("MCUNotGenuineToDashboard"); + createCustomErrorClass("RecipientRequired"); + createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + createCustomErrorClass("UpdateFetchFileFail"); + createCustomErrorClass("UpdateIncorrectHash"); + createCustomErrorClass("UpdateIncorrectSig"); + createCustomErrorClass("UpdateYourApp"); + createCustomErrorClass("UserRefusedDeviceNameChange"); + createCustomErrorClass("UserRefusedAddress"); + createCustomErrorClass("UserRefusedFirmwareUpdate"); + createCustomErrorClass("UserRefusedAllowManager"); + createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + createCustomErrorClass("TransportOpenUserCancelled"); + createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + createCustomErrorClass("TransportWebUSBGestureRequired"); + createCustomErrorClass("DeviceShouldStayInApp"); + createCustomErrorClass("WebsocketConnectionError"); + createCustomErrorClass("WebsocketConnectionFailed"); + createCustomErrorClass("WrongDeviceForAccount"); + createCustomErrorClass("WrongAppForCurrency"); + createCustomErrorClass("ETHAddressNonEIP"); + createCustomErrorClass("CantScanQRCode"); + createCustomErrorClass("FeeNotLoaded"); + createCustomErrorClass("FeeRequired"); + createCustomErrorClass("FeeTooHigh"); + createCustomErrorClass("SyncError"); + createCustomErrorClass("PairingFailed"); + createCustomErrorClass("GenuineCheckFailed"); + createCustomErrorClass("LedgerAPI4xx"); + createCustomErrorClass("LedgerAPI5xx"); + createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + createCustomErrorClass("NoDBPathGiven"); + createCustomErrorClass("DBWrongPassword"); + createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa, + }; + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); + + /** + */ + + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + class Transport { + constructor() { + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter__default["default"](); + + this.send = async (cla, ins, p1, p2, data = Buffer$i.alloc(0), statusList = [StatusCodes.OK]) => { + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + + const response = await this.exchange(Buffer$i.concat([Buffer$i.from([cla, ins, p1, p2]), Buffer$i.from([data.length]), data])); + const sw = response.readUInt16BE(response.length - 2); + + if (!statusList.some(s => s === sw)) { + throw new TransportStatusError(sw); + } + + return response; + }; + + this.exchangeBusyPromise = void 0; + + this.exchangeAtomicImpl = async f => { + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } + + let resolveBusy; + const busyPromise = new Promise(r => { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + let unresponsiveReached = false; + const timeout = setTimeout(() => { + unresponsiveReached = true; + this.emit("unresponsive"); + }, this.unresponsiveTimeout); + + try { + const res = await f(); + + if (unresponsiveReached) { + this.emit("responsive"); + } + + return res; + } finally { + clearTimeout(timeout); + if (resolveBusy) resolveBusy(); + this.exchangeBusyPromise = null; + } + }; + + this._appAPIlock = null; + } + + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + exchange(_apdu) { + throw new Error("exchange not implemented"); + } + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + + + setScrambleKey(_key) {} + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + + + close() { + return Promise.resolve(); + } + + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + on(eventName, cb) { + this._events.on(eventName, cb); + } + /** + * Stop listening to an event on an instance of transport. + */ + + + off(eventName, cb) { + this._events.removeListener(eventName, cb); + } + + emit(event, ...args) { + this._events.emit(event, ...args); + } + /** + * Enable or not logs of the binary exchange + */ + + + setDebugMode() { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + } + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + + + setExchangeTimeout(exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + } + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + + + setExchangeUnresponsiveTimeout(unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + } + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + + + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + static create(openTimeout = 3000, listenTimeout) { + return new Promise((resolve, reject) => { + let found = false; + const sub = this.listen({ + next: e => { + found = true; + if (sub) sub.unsubscribe(); + if (listenTimeoutId) clearTimeout(listenTimeoutId); + this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: e => { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + reject(e); + }, + complete: () => { + if (listenTimeoutId) clearTimeout(listenTimeoutId); + + if (!found) { + reject(new TransportError(this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + const listenTimeoutId = listenTimeout ? setTimeout(() => { + sub.unsubscribe(); + reject(new TransportError(this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) : null; + }); + } + + decorateAppAPIMethods(self, methods, scrambleKey) { + for (let methodName of methods) { + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + + decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { + return async (...args) => { + const { + _appAPIlock + } = this; + + if (_appAPIlock) { + return Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked")); + } + + try { + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return await f.apply(ctx, args); + } finally { + this._appAPIlock = null; + } + }; + } + + } + Transport.isSupported = void 0; + Transport.list = void 0; + Transport.listen = void 0; + Transport.open = void 0; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + + /** + * A Log object + */ + let id = 0; + const subscribers = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + + const log = (type, message, data) => { + const obj = { + type, + id: String(++id), + date: new Date() + }; + if (message) obj.message = message; + if (data) obj.data = data; + dispatch(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + + const listen = cb => { + subscribers.push(cb); + return () => { + const i = subscribers.indexOf(cb); + + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + + function dispatch(log) { + for (let i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } catch (e) { + console.error(e); + } + } + } // for debug purpose + + + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; + } + + function wrapU2FTransportError(originalError, message, id) { + const err = new TransportError(message, id); // $FlowFixMe + + err.originalError = originalError; + return err; + } + + function wrapApdu(apdu, key) { + const result = Buffer$i.alloc(apdu.length); + + for (let i = 0; i < apdu.length; i++) { + result[i] = apdu[i] ^ key[i % key.length]; + } + + return result; + } // Convert from normal to web-safe, strip trailing "="s + + + const webSafe64 = base64 => base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Convert from web-safe to normal, add trailing "="s + + + const normal64 = base64 => base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); + + function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { + const keyHandle = wrapApdu(apdu, scrambleKey); + const challenge = Buffer$i.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const signRequest = { + version: "U2F_V2", + keyHandle: webSafe64(keyHandle.toString("base64")), + challenge: webSafe64(challenge.toString("base64")), + appId: location.origin + }; + log("apdu", "=> " + apdu.toString("hex")); + return u2fApi.sign(signRequest, timeoutMillis / 1000).then(response => { + const { + signatureData + } = response; + + if (typeof signatureData === "string") { + const data = Buffer$i.from(normal64(signatureData), "base64"); + let result; + + if (!unwrap) { + result = data; + } else { + result = data.slice(5); + } + + log("apdu", "<= " + result.toString("hex")); + return result; + } else { + throw response; + } + }); + } + + let transportInstances = []; + + function emitDisconnect() { + transportInstances.forEach(t => t.emit("disconnect")); + transportInstances = []; + } + + function isTimeoutU2FError(u2fError) { + return u2fError.metaData.code === 5; + } + /** + * U2F web Transport implementation + * @example + * import TransportU2F from "@ledgerhq/hw-transport-u2f"; + * ... + * TransportU2F.create().then(transport => ...) + */ + + + class TransportU2F extends Transport { + /* + */ + + /* + */ + + /** + * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) + */ + static async open(_, _openTimeout = 5000) { + return new TransportU2F(); + } + + constructor() { + super(); + this.scrambleKey = void 0; + this.unwrap = true; + transportInstances.push(this); + } + /** + * Exchange with the device using APDU protocol. + * @param apdu + * @returns a promise of apdu response + */ + + + async exchange(apdu) { + try { + return await attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); + } catch (e) { + const isU2FError = typeof e.metaData === "object"; + + if (isU2FError) { + if (isTimeoutU2FError(e)) { + emitDisconnect(); + } // the wrapping make error more usable and "printable" to the end user. + + + throw wrapU2FTransportError(e, "Failed to sign with Ledger device: U2F " + e.metaData.type, "U2F_" + e.metaData.code); + } else { + throw e; + } + } + } + /** + */ + + + setScrambleKey(scrambleKey) { + this.scrambleKey = Buffer$i.from(scrambleKey, "ascii"); + } + /** + */ + + + setUnwrap(unwrap) { + this.unwrap = unwrap; + } + + close() { + // u2f have no way to clean things up + return Promise.resolve(); + } + + } + TransportU2F.isSupported = u2fApi.isSupported; + + TransportU2F.list = () => // this transport is not discoverable but we are going to guess if it is here with isSupported() + u2fApi.isSupported().then(supported => supported ? [null] : []); + + TransportU2F.listen = observer => { + let unsubscribed = false; + u2fApi.isSupported().then(supported => { + if (unsubscribed) return; + + if (supported) { + observer.next({ + type: "add", + descriptor: null + }); + observer.complete(); + } else { + observer.error(new TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); + } + }); + return { + unsubscribe: () => { + unsubscribed = true; + } + }; + }; + + var TransportU2F$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': TransportU2F + }); + + var inherits$2 = inherits$f.exports; + var HashBase = hashBase; + var Buffer$1 = safeBuffer.exports.Buffer; + + var ARRAY16 = new Array(16); + + function MD5$1 () { + HashBase.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } + + inherits$2(MD5$1, HashBase); + + MD5$1.prototype._update = function () { + var M = ARRAY16; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; + + MD5$1.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$1.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } + + function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } + + function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } + + function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } + + var md5_js = MD5$1; + + var Buffer = safeBuffer.exports.Buffer; + var Transform = require$$0__default$2["default"].Transform; + var StringDecoder = require$$2__default["default"].StringDecoder; + var inherits$1 = inherits$f.exports; + + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits$1(CipherBase, Transform); + + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc); + } + + var outData = this._update(data); + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + + return outData + }; + + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; + + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; + + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; + + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); + } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } + + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; + + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + + return out + }; + + var cipherBase = CipherBase; + + var inherits = inherits$f.exports; + var MD5 = md5_js; + var RIPEMD160 = ripemd160$1; + var sha = sha_js.exports; + var Base = cipherBase; + + function Hash (hash) { + Base.call(this, 'digest'); + + this._hash = hash; + } + + inherits(Hash, Base); + + Hash.prototype._update = function (data) { + this._hash.update(data); + }; + + Hash.prototype._final = function () { + return this._hash.digest() + }; + + var browser = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) + }; + + var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser + }, [browser])); + + exports.Btc = Btc$1; + exports.Log = index; + exports.TransportU2F = TransportU2F$1; + exports.TransportWebUSB = TransportWebUSB$1; + exports.createHash = browser$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; From 62e9783e81d4d24fe12add0c44bac0c58325330c Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 22:13:35 +1100 Subject: [PATCH 18/78] buffer --- js/ledger.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index b6caa9d7..6e8de09c 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2881,7 +2881,7 @@ window.Buffer = buffer.Buffer; (function (module, exports) { /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0__default$1["default"]; + var buffer = window.Buffer; var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers From 4f30af22c924ada8dd68cc1de3ab5fb517e4abbb Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 18 Jan 2022 22:17:52 +1100 Subject: [PATCH 19/78] .. --- js/ledger.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index 6e8de09c..00716cfe 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -2882,7 +2882,7 @@ window.Buffer = buffer.Buffer; (function (module, exports) { /* eslint-disable node/no-deprecated-api */ var buffer = window.Buffer; - var Buffer = buffer.Buffer; + var Buffer = buffer; // alternative to using Object.keys for old browsers function copyProps (src, dst) { From 4e97b3e25a924c5e3434d273c2dfbecd5afa20ac Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 10:51:12 +1100 Subject: [PATCH 20/78] ? --- js/ledger.js | 51657 +++++++++++++++++++++++++------------------------ 1 file changed, 25912 insertions(+), 25745 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 00716cfe..df2ab024 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -3,10 +3,10 @@ window.global = window; window.Buffer = buffer.Buffer; (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('crypto'), require('buffer'), require('stream'), require('events'), require('util'), require('string_decoder')) : - typeof define === 'function' && define.amd ? define(['exports', 'crypto', 'buffer', 'stream', 'events', 'util', 'string_decoder'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$0$4, global.EventEmitter, global.require$$1, global.require$$2)); -})(this, (function (exports, require$$0$2, require$$0$3, require$$0$4, EventEmitter, require$$1, require$$2) { 'use strict'; + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('buffer'), require('events'), require('stream'), require('string_decoder')) : + typeof define === 'function' && define.amd ? define(['exports', 'buffer', 'events', 'stream', 'string_decoder'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$1, global.require$$2)); +})(this, (function (exports, require$$0$2, require$$0$3, require$$1, require$$2) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -27,8 +27,6 @@ window.Buffer = buffer.Buffer; var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); - var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4); - var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); @@ -1042,12 +1040,12 @@ window.Buffer = buffer.Buffer; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$i.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$i.TYPED_ARRAY_SUPPORT + return Buffer$l.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1056,14 +1054,14 @@ window.Buffer = buffer.Buffer; if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$i.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$i(length); + that = new Buffer$l(length); } that.length = length; } @@ -1081,9 +1079,9 @@ window.Buffer = buffer.Buffer; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$i (arg, encodingOrOffset, length) { - if (!Buffer$i.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$i)) { - return new Buffer$i(arg, encodingOrOffset, length) + function Buffer$l (arg, encodingOrOffset, length) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { + return new Buffer$l(arg, encodingOrOffset, length) } // Common case. @@ -1095,18 +1093,18 @@ window.Buffer = buffer.Buffer; } return allocUnsafe(this, arg) } - return from$2(this, arg, encodingOrOffset, length) + return from$1(this, arg, encodingOrOffset, length) } - Buffer$i.poolSize = 8192; // not used by this implementation + Buffer$l.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$i._augment = function (arr) { - arr.__proto__ = Buffer$i.prototype; + Buffer$l._augment = function (arr) { + arr.__proto__ = Buffer$l.prototype; return arr }; - function from$2 (that, value, encodingOrOffset, length) { + function from$1 (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1130,13 +1128,13 @@ window.Buffer = buffer.Buffer; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$i.from = function (value, encodingOrOffset, length) { - return from$2(null, value, encodingOrOffset, length) + Buffer$l.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$i.TYPED_ARRAY_SUPPORT) { - Buffer$i.prototype.__proto__ = Uint8Array.prototype; - Buffer$i.__proto__ = Uint8Array; + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + Buffer$l.prototype.__proto__ = Uint8Array.prototype; + Buffer$l.__proto__ = Uint8Array; } function assertSize (size) { @@ -1167,14 +1165,14 @@ window.Buffer = buffer.Buffer; * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$i.alloc = function (size, fill, encoding) { + Buffer$l.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1185,13 +1183,13 @@ window.Buffer = buffer.Buffer; /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$i.allocUnsafe = function (size) { + Buffer$l.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$i.allocUnsafeSlow = function (size) { + Buffer$l.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1200,7 +1198,7 @@ window.Buffer = buffer.Buffer; encoding = 'utf8'; } - if (!Buffer$i.isEncoding(encoding)) { + if (!Buffer$l.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1247,10 +1245,10 @@ window.Buffer = buffer.Buffer; array = new Uint8Array(array, byteOffset, length); } - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$i.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1297,12 +1295,12 @@ window.Buffer = buffer.Buffer; } return length | 0 } - Buffer$i.isBuffer = isBuffer; + Buffer$l.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$i.compare = function compare (a, b) { + Buffer$l.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1325,7 +1323,7 @@ window.Buffer = buffer.Buffer; return 0 }; - Buffer$i.isEncoding = function isEncoding (encoding) { + Buffer$l.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1344,13 +1342,13 @@ window.Buffer = buffer.Buffer; } }; - Buffer$i.concat = function concat (list, length) { + Buffer$l.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$i.alloc(0) + return Buffer$l.alloc(0) } var i; @@ -1361,7 +1359,7 @@ window.Buffer = buffer.Buffer; } } - var buffer = Buffer$i.allocUnsafe(length); + var buffer = Buffer$l.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1417,7 +1415,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$i.byteLength = byteLength; + Buffer$l.byteLength = byteLength; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1491,7 +1489,7 @@ window.Buffer = buffer.Buffer; // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$i.prototype._isBuffer = true; + Buffer$l.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1499,7 +1497,7 @@ window.Buffer = buffer.Buffer; b[m] = i; } - Buffer$i.prototype.swap16 = function swap16 () { + Buffer$l.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1510,7 +1508,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$i.prototype.swap32 = function swap32 () { + Buffer$l.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1522,7 +1520,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$i.prototype.swap64 = function swap64 () { + Buffer$l.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1536,20 +1534,20 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$i.prototype.toString = function toString () { + Buffer$l.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$i.prototype.equals = function equals (b) { + Buffer$l.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$i.compare(this, b) === 0 + return Buffer$l.compare(this, b) === 0 }; - Buffer$i.prototype.inspect = function inspect () { + Buffer$l.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1559,7 +1557,7 @@ window.Buffer = buffer.Buffer; return '' }; - Buffer$i.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1658,7 +1656,7 @@ window.Buffer = buffer.Buffer; // Normalize val if (typeof val === 'string') { - val = Buffer$i.from(val, encoding); + val = Buffer$l.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1670,7 +1668,7 @@ window.Buffer = buffer.Buffer; return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$i.TYPED_ARRAY_SUPPORT && + if (Buffer$l.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1740,15 +1738,15 @@ window.Buffer = buffer.Buffer; return -1 } - Buffer$i.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$i.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$i.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1799,7 +1797,7 @@ window.Buffer = buffer.Buffer; return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$i.prototype.write = function write (string, offset, length, encoding) { + Buffer$l.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1871,7 +1869,7 @@ window.Buffer = buffer.Buffer; } }; - Buffer$i.prototype.toJSON = function toJSON () { + Buffer$l.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2024,7 +2022,7 @@ window.Buffer = buffer.Buffer; return res } - Buffer$i.prototype.slice = function slice (start, end) { + Buffer$l.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2046,12 +2044,12 @@ window.Buffer = buffer.Buffer; if (end < start) end = start; var newBuf; - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$i.prototype; + newBuf.__proto__ = Buffer$l.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$i(sliceLen, undefined); + newBuf = new Buffer$l(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2068,7 +2066,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$i.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2083,7 +2081,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$i.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2099,22 +2097,22 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$i.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$i.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$i.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$i.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2123,7 +2121,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] * 0x1000000) }; - Buffer$i.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2132,7 +2130,7 @@ window.Buffer = buffer.Buffer; this[offset + 3]) }; - Buffer$i.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2150,7 +2148,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$i.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2168,25 +2166,25 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$i.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$i.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$i.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$i.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2195,7 +2193,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] << 24) }; - Buffer$i.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2204,22 +2202,22 @@ window.Buffer = buffer.Buffer; (this[offset + 3]) }; - Buffer$i.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$i.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$i.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$i.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2230,7 +2228,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$i.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2249,7 +2247,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$i.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2268,11 +2266,11 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$i.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2285,11 +2283,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$i.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2298,11 +2296,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$i.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2318,11 +2316,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$i.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2333,11 +2331,11 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$i.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2348,7 +2346,7 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$i.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2371,7 +2369,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$i.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2394,21 +2392,21 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$i.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$i.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$i.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2417,11 +2415,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$i.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2430,11 +2428,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$i.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2445,12 +2443,12 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$i.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$l.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; - if (Buffer$i.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2474,11 +2472,11 @@ window.Buffer = buffer.Buffer; return offset + 4 } - Buffer$i.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$i.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2490,16 +2488,16 @@ window.Buffer = buffer.Buffer; return offset + 8 } - Buffer$i.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$i.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$i.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2531,7 +2529,7 @@ window.Buffer = buffer.Buffer; for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$i.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2551,7 +2549,7 @@ window.Buffer = buffer.Buffer; // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$i.prototype.fill = function fill (val, start, end, encoding) { + Buffer$l.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2571,7 +2569,7 @@ window.Buffer = buffer.Buffer; if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$i.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2600,7 +2598,7 @@ window.Buffer = buffer.Buffer; } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$i(val, encoding).toString()); + : utf8ToBytes(new Buffer$l(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -2873,7 +2871,35 @@ window.Buffer = buffer.Buffer; var bip32Path = BIPPath; - var createHash$3 = window.createHash; + var inherits_browser = {exports: {}}; + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } var safeBuffer = {exports: {}}; @@ -2881,8 +2907,8 @@ window.Buffer = buffer.Buffer; (function (module, exports) { /* eslint-disable node/no-deprecated-api */ - var buffer = window.Buffer; - var Buffer = buffer; + var buffer = require$$0__default["default"]; + var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers function copyProps (src, dst) { @@ -2946,28138 +2972,28549 @@ window.Buffer = buffer.Buffer; }; }(safeBuffer, safeBuffer.exports)); - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; - } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; + var readableBrowser = {exports: {}}; + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str - } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } - } - var src$2 = base$2; - - var basex = src$2; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - - var bs58 = basex(ALPHABET$1); - - var base58 = bs58; - var Buffer$h = safeBuffer.exports.Buffer; - - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); - - return base58.encode(Buffer$h.concat([ - payload, - checksum - ], payload.length + 4)) - } - - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return - - return payload - } - - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return - - return decodeRaw(buffer) - } - - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload - } - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } - }; - var createHash$2 = createHash$3; - var bs58checkBase = base$1; + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$2('sha256').update(buffer).digest(); - return createHash$2('sha256').update(tmp).digest() + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } - var bs58check$5 = bs58checkBase(sha256x2); + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - function pathElementsToBuffer(paths) { - var buffer = Buffer$i.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; } } - return []; + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$6 = true; + var env = {}; + var argv = []; + var version$1 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config$1 = {}; - var src$1 = {}; + function noop$2() {} - var src = {}; + var on = noop$2; + var addListener = noop$2; + var once$2 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; - var bip32$1 = {}; + function binding(name) { + throw new Error('process.binding is not supported'); + } - var crypto$4 = {}; + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } - var createHmac$2 = require$$0__default["default"].createHmac; + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; - Object.defineProperty(crypto$4, "__esModule", { value: true }); - const createHash$1 = createHash$3; - const createHmac$1 = createHmac$2; - function hash160$2(buffer) { - const sha256Hash = createHash$1('sha256') - .update(buffer) - .digest(); - try { - return createHash$1('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$1('ripemd160') - .update(sha256Hash) - .digest(); + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; } + } + return [seconds,nanoseconds] } - crypto$4.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; } - crypto$4.hmacSHA512 = hmacSHA512; - var tinySecp256k1 = {exports: {}}; + var process = { + nextTick: nextTick, + title: title, + browser: browser$6, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once$2, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config$1, + uptime: uptime + }; - var bn$1 = {exports: {}}; + var streamBrowser = require$$0__default$1["default"].EventEmitter; - (function (module) { - (function (module, exports) { + var _nodeResolve_empty = {}; - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); - // 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; - } + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - // BN + 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 BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - this.negative = 0; - this.words = null; - this.length = 0; + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - // Reduction context - this.red = null; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - BN.BN = BN; - BN.wordSize = 26; + var _require$2 = require$$0__default["default"], + Buffer$k = _require$2.Buffer; - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require('buffer').Buffer; - } - } catch (e) { - } + var _require2 = require$$3, + inspect = _require2.inspect; - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } + var custom = inspect && inspect.custom || 'inspect'; - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; + function copyBuffer(src, target, offset) { + Buffer$k.prototype.copy.call(src, target, offset); + } - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + this.head = null; + this.tail = null; + this.length = 0; + } - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; } - - if (base === 'hex') { - base = 16; + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; - 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); - } + while (p = p.next) { + ret += s + p.data; } - } - }; - 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; + return ret; } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$k.alloc(0); + var ret = Buffer$k.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; - if (endian !== 'le') return; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - 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; - } + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; - 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; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. - 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++; + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; } + + ++c; } - } 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++; + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$k.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; } + + ++c; } - } - 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; - } - } + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); } - 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; - } + return BufferList; + }(); - // 24-bits chunks - var off = 0; - var j = 0; + function destroy(err, cb) { + var _this = this; - 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; - } + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); } } - this.strip(); - }; + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - 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; + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + if (this._writableState) { + this._writableState.destroyed = true; + } - // '0' - '9' + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); } else { - r += c; + nextTick(emitCloseNT, _this); } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); + } else { + nextTick(emitCloseNT, _this); } - return r; + }); + + return this; + } + + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); + } + + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + 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; + } + } - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + function emitErrorNT(self, err) { + self.emit('error', err); + } - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + var errorsBrowser = {}; - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - for (i = 0; i < mod; i++) { - pow *= base; - } + var codes = {}; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); } + } - this.strip(); - }; + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - 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]; + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; } - 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; - }; + return NodeError; + }(Base); - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - // 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; + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); } - return this; - }; + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - /* + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - var zeros = []; - var groupSizes = []; - var groupBases = []; - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - 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; + + return str.substring(this_len - search.length, this_len) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; } - */ + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } - 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' - ]; + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; - 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 - ]; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - 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 - ]; + var msg; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } - 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; - } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + errorsBrowser.codes = codes; - 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); + var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; - 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; - } + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } - assert(false, 'Base should be between 2 and 36'); - }; + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - 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'); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); } - 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); - }; + return Math.floor(hwm); + } // Default value - 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'); + return state.objectMode ? 16 : 16 * 1024; + } - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + var state = { + getHighWaterMark: getHighWaterMark$2 + }; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + /** + * Module exports. + */ - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + var browser$5 = deprecate; - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ - res[i] = b; - } + function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } - for (; i < reqLength; i++) { - res[i] = 0; + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); } + warned = true; } + return fn.apply(this, arguments); + } - return res; - }; + return deprecated; + } - 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; - }; + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; } + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; + } - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + var _stream_writable = Writable$1; + // there will be only 2 of these for each stream - 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 CorkedRequest(state) { + var _this = this; - function toBitArray (num) { - var w = new Array(num.bitLength()); + this.next = null; + this.entry = null; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ - 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 Duplex$3; + /**/ - 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; - }; + Writable$1.WritableState = WritableState; + /**/ - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + var internalUtil = { + deprecate: browser$5 + }; + /**/ - 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(); - }; + var Stream$1 = streamBrowser; + /**/ - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + var Buffer$j = require$$0__default["default"].Buffer; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - return this; - }; + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$j.from(chunk); + } - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + function _isUint8Array$1(obj) { + return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } + var destroyImpl$1 = destroy_1; - return this.strip(); - }; + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - // 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); - }; + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + inherits_browser.exports(Writable$1, Stream$1); - // 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; - } + function nop() {} - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } + function WritableState(options, stream, isDuplex) { + Duplex$3 = Duplex$3 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - this.length = b.length; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - return this.strip(); - }; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - // 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); - }; + this.finalCalled = false; // drain event flag. - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + this.needDrain = false; // at the start of calling end() - // 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; - } + this.ending = false; // when end() has been called, and returned - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + this.ended = false; // when 'finish' is emitted - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + this.finished = false; // has it been destroyed - this.length = a.length; + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - return this.strip(); - }; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - // 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); - }; + this.length = 0; // a flag to see when we're in the middle of a write. - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + this.writing = false; // when true all writes will be buffered until .uncork() call - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - if (bitsLeft > 0) { - bytesNeeded--; - } + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // 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)); - } + this.writecb = null; // the amount that is being written when _write is called. - // And remove leading zeroes - return this.strip(); - }; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + this.prefinished = false; // True if the error was already emitted and should not be thrown again - var off = (bit / 26) | 0; - var wbit = bit % 26; + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - this._expand(off + 1); + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + this.autoDestroy = !!options.autoDestroy; // count buffered requests - return this.strip(); - }; + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + this.corkedRequestsFree = new CorkedRequest(this); + } - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + while (current) { + out.push(current); + current = current.next; + } - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return out; + }; - 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; - } + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. - 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; - }; + var realHasInstance; - // 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 (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$1, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$1) return false; + return object && object._writableState instanceof WritableState; } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } - if (this.length > num.length) return this.clone().iadd(num); + function Writable$1(options) { + Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 - return num.clone().iadd(this); - }; + var isDuplex = this instanceof Duplex$3; + if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. - // 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.writable = true; - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } - // At this point both numbers are positive - var cmp = this.cmp(num); + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; + + Writable$1.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; + + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + + + function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); + } + + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } + + return true; + } + + Writable$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$j.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; + + Writable$1.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$j.from(chunk, encoding); + } + + return chunk; + } + + Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } + } - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; } else { - a = num; - b = this; + state.bufferedRequest = state.lastBufferedRequest; } - 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; - } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + return ret; + } - this.length = Math.max(this.length, i); + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - if (a !== this) { - this.negative = 1; - } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - return this.strip(); - }; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error - 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; + finishMaybe(stream, state); + } + } - // 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; + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; - 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 (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - if (carry !== 0) { - out.words[k] = carry | 0; + + if (sync) { + nextTick(afterWrite, stream, state, finished, cb); } else { - out.length--; + afterWrite(stream, state, finished, cb); } + } + } - return out.strip(); + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + + + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } + } // if there's something in the buffer waiting, then process it - // 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) ; 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); - }; - })(module, commonjsGlobal); - }(bn$1)); - - var elliptic = {}; - - var name = "elliptic"; - var version$1 = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0$1 = { - name: name, - version: version$1, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; - - var utils$n = {}; - - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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 = require('buffer').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++; + + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - return out; - }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; + state.pendingcb++; + state.lastBufferedRequest = null; - 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; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + if (state.writing) { + break; } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; } - if (carry !== 0) { - out.words[k] = carry; + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; + + Writable$1.prototype._writev = null; + + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + + function prefinish$1(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); } else { - out.length--; + state.prefinished = true; + stream.emit('prefinish'); } + } + } - return out.strip(); + function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish$1(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } } - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } - 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); - } + state.ended = true; + stream.writable = false; + } - return res; - }; + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - 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); + state.corkedRequestsFree.next = corkReq; + } + + Object.defineProperty(Writable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; } - return t; - }; + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - // 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; - } + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl$1.destroy; + Writable$1.prototype._undestroy = destroyImpl$1.undestroy; - return rb; - }; + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; - // 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); + var objectKeys = Object.keys || function (obj) { + var keys = []; - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; + for (var key in obj) { + keys.push(key); + } - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); + return keys; + }; + /**/ - 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 _stream_duplex = Duplex$2; - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; + var Readable$1 = _stream_readable; - var rx = rtwdf_ * ro - itwdf_ * io; + var Writable = _stream_writable; - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; + inherits_browser.exports(Duplex$2, Readable$1); - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + { + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; + } + } - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); + Readable$1.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } - }; + } + } - 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++; + Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer + + function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + Object.defineProperty(Duplex$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - return 1 << i + 1 + odd; - }; + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + var string_decoder = {}; - t = iws[i]; + /**/ - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; + var Buffer$i = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$i.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$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } - 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; + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$i.allocUnsafe(nb); + } - ws[i] = w & 0x3ffffff; + StringDecoder$2.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 || ''; + }; - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } + StringDecoder$2.prototype.end = utf8End; - return ws; - }; + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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; + }; - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + // 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; + } - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 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'; + } + } + } + } - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; + // 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); + 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; + } - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } + // 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); + } - return ph; - }; + // 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; + } - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); + // 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); + } - var rbt = this.makeRBT(N); + // 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; + } - var _ = this.stub(N); + 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); + } - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(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; + } - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } - var rmws = out.words; - rmws.length = N; + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; - 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; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - 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); + callback.apply(this, args); }; + } - // 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); - }; + function noop$1() {} - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - // 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; - } + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } + var writableEnded = stream._writableState && stream._writableState.finished; - return this; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); }; - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); }; - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); + var onerror = function onerror(err) { + callback.call(stream, err); }; - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + var onclose = function onclose() { + var err; - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - 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); - } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - - 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; - } + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; - this.length += s; - } + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - return this.strip(); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); }; + } - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; + var endOfStream = eos$1; - // 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 _Object$setPrototypeO; - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - h -= s; - h = Math.max(0, h); + var finished = endOfStream; - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); - if (s === 0) ; 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; - } + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } - 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; - } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } + } + } - 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); - }; + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); + iter[kHandlePromise](resolve, reject); + }, reject); }; + } - // 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); - }; + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - // 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; + next: function next() { + var _this = this; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - if (this.length <= s) { - return this; + if (error !== null) { + return Promise.reject(error); } - if (r !== 0) { - s++; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); } - this.length = Math.min(s, this.length); - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - return this.strip(); - }; - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + var lastPromise = this[kLastPromise]; + var promise; - // 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); + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); - // 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; + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); } - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + promise = new Promise(this[kHandlePromise]); } - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; - // 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]++; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; } - } - 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); + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; - this.words[0] -= num; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); - 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; + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; } - } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error - return this.strip(); - }; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + iterator[kError] = err; + return; + } - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; + var resolve = iterator[kLastResolve]; - BN.prototype.iabs = function iabs () { - this.negative = 0; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } - return this; - }; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + var async_iterator = createReadableStreamAsyncIterator$1; - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') + }; - this._expand(len); + var _stream_readable = Readable; + /**/ - 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; - } + var Duplex$1; + /**/ - if (carry === 0) return this.strip(); + Readable.ReadableState = ReadableState; + /**/ - // 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; + require$$0__default$1["default"].EventEmitter; - return this.strip(); - }; + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - 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; - } + var Stream = streamBrowser; + /**/ - // 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 Buffer$h = require$$0__default["default"].Buffer; - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); + } - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ - 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); - } + var debugUtil = require$$3; - return { - div: q || null, - mod: a - }; - }; + var debug$4; - // 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 (debugUtil && debugUtil.debuglog) { + debug$4 = debugUtil.debuglog('stream'); + } else { + debug$4 = function debug() {}; + } + /**/ - 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); + var BufferList = buffer_list; - if (mode !== 'mod') { - div = res.div.neg(); - } + var destroyImpl = destroy_1; - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - return { - div: div, - mod: mod - }; - } + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - if (mode !== 'mod') { - div = res.div.neg(); - } + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; - return { - div: div, - mod: res.mod - }; - } + inherits_browser.exports(Readable, Stream); - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. - return { - div: res.div, - mod: mod - }; - } + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } - // Both numbers are positive at this point + function ReadableState(options, stream, isDuplex) { + Duplex$1 = Duplex$1 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - return this._wordDiv(num, mode); - }; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + this.readingMore = false; + this.decoder = null; + this.encoding = null; - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } + } - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; + function Readable(options) { + Duplex$1 = Duplex$1 || _stream_duplex; + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; + var isDuplex = this instanceof Duplex$1; + this._readableState = new ReadableState(options, this, isDuplex); // legacy - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } + this.readable = true; - return acc; - }; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); + Stream.call(this); + } - 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; + Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; } - return this.strip(); - }; + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; - var x = this; - var y = p.clone(); + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. - 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); + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; - var g = 0; + if (encoding !== state.encoding) { + chunk = Buffer$h.from(chunk, encoding); + encoding = ''; + } - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; + skipChunkCheck = true; } + } else { + skipChunkCheck = true; + } - var yp = y.clone(); - var xp = x.clone(); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - 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); - } - } + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; - 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); - } + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$4('readableAddChunk', chunk); + var state = stream._readableState; - C.iushrn(1); - D.iushrn(1); - } + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + chunk = _uint8ArrayToBuffer(chunk); } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; } else { - y.isub(x); - C.isub(A); - D.isub(B); + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - 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); + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } - var delta = b.clone(); + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } - 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); - } + maybeReadMore(stream, state); + } - x1.iushrn(1); - } - } + function chunkInvalid(state, chunk) { + var er; - 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); - } + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - x2.iushrn(1); - } - } + return er; + } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - if (res.cmpn(0) < 0) { - res.iadd(p); - } + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - return res; - }; + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); + var p = this._readableState.buffer.head; + var content = ''; - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } + this._readableState.buffer.clear(); - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - 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); + var MAX_HWM = 0x40000000; - return b.iushln(shift); - }; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - // 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; - } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough - // 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; - }; + if (!state.ended) { + state.needReadable = true; + return 0; + } - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; + return state.length; + } // you can override either this method, or the async _read(n) below. - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + Readable.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - this.strip(); + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - assert(num <= 0x3ffffff, 'Number is too big'); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - 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 doRead = state.needReadable; + debug$4('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - // 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 (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; + if (state.length === 0) state.needReadable = true; // call internal read method - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; + this._read(state.highWaterMark); - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; + if (!state.reading) n = howMuchToRead(nOrig, state); + } - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + if (nOrig !== n && state.ended) endReadable(this); + } - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + if (ret !== null) this.emit('data', ret); + return ret; + }; - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + function onEofChunk(stream, state) { + debug$4('onEofChunk'); + if (state.ended) return; - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + if (state.decoder) { + var chunk = state.decoder.end(); - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } - 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); - }; + state.ended = true; - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. - 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); - }; + function emitReadable(stream) { + var state = stream._readableState; + debug$4('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_, stream); + } + } - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + function emitReadable_(stream) { + var state = stream._readableState; + debug$4('emitReadable_', state.destroyed, state.length, state.ended); - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - 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); - }; + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. - 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); - }; + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } - // 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); - }; + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. - 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); - }; + Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + }; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - // 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); + case 1: + state.pipes = [state.pipes, dest]; + break; - this.tmp = this._tmp(); + default: + state.pipes.push(dest); + break; } - 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; + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + function onunpipe(readable, unpipeInfo) { + debug$4('onunpipe'); - 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(); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); } } + } - return r; - }; + function onend() { + debug$4('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); + function cleanup() { + debug$4('cleanup'); // cleanup event handlers once the pipe is broken - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } + src.on('data', ondata); - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + function ondata(chunk) { + debug$4('ondata'); + var ret = dest.write(chunk); + debug$4('dest.write', ret); - 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; + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); } - }; + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - 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); - } + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - // 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'); + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - inherits(P224, MPrime); - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + dest.once('close', onclose); + + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); } - inherits(P192, MPrime); - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + dest.once('finish', onfinish); + + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); } - 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; + return dest; + }; - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } - 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]; + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - 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; + if (state.pipesCount === 0) return this; // just one destination. most common case. - return prime; - }; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - // - // 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; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); } - } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + return this; + } // try to find the right one. - 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); - }; + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - return this.m.sub(a)._forceRed(this); - }; + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$4('on readable', state.length, state.reading); + + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + nextTick(nReadingNextTick, this); + } } - return res._forceRed(this); - }; + } - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + return res; + }; - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + Readable.prototype.addListener = Readable.prototype.on; - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); + return res; + }; - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; + Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + return res; + }; - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + Readable.prototype.resume = function () { + var state = this._readableState; - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } + if (!state.flowing) { + debug$4('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - // 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()); + state.flowing = !state.readableListening; + resume(this, state); + } - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); + state.paused = false; + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + debug$4('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } - // 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); + Readable.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } + if (this._readableState.flowing !== false) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } - 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)); + this._readableState.paused = true; + return this; + }; - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } + function flow(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); - return r; - }; + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. - 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(); + Readable.prototype.wrap = function (stream) { + var _this = this; - 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 state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$4('wrapped end'); - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); } - 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); - } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + var ret = _this.push(chunk); - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; + if (!ret) { + paused = true; + stream.pause(); } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - return res; - }; + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - // - // Montgomery method engine - // + this._read = function (n) { + debug$4('wrapped _read', n); - BN.mont = function mont (num) { - return new Mont(num); + if (paused) { + paused = false; + stream.resume(); + } }; - function Mont (m) { - Red.call(this, m); + return this; + }; - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); + if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; } - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + return createReadableStreamAsyncIterator(this); + }; + } - 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); + Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; } - inherits(Mont, Red); + }); + Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + Readable._fromList = fromList; + Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } + function endReadable(stream) { + var state = stream._readableState; + debug$4('endReadable', state.endEmitted); - 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 (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } + function endReadableNT(state, stream) { + debug$4('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - return res._forceRed(this); - }; + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; - 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); + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } } + } + } - return res._forceRed(this); - }; + if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } - 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); + return from(Readable, iterable, opts); }; - })(module, commonjsGlobal); - }(bn)); + } - var minimalisticAssert = assert$f; + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); + return -1; } - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; + var _stream_transform = Transform$3; - var utils$m = {}; + var _require$codes$1 = errorsBrowser.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - (function (exports) { + var Duplex = _stream_duplex; - var utils = exports; + inherits_browser.exports(Transform$3, Duplex); - 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); - } + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - return res; - } - utils.toArray = toArray; - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils.zero2 = zero2; + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } } - utils.toHex = toHex; - utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; - }; - }(utils$m)); + function Transform$3(options) { + if (!(this instanceof Transform$3)) return new Transform$3(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. - (function (exports) { + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; + this._readableState.sync = false; - utils.assert = minAssert; - utils.toArray = minUtils.toArray; - utils.zero2 = minUtils.zero2; - utils.toHex = minUtils.toHex; - utils.encode = minUtils.encode; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // 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(); + this.on('prefinish', prefinish); + } - 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; - } + function prefinish() { + var _this = this; - naf[i] = z; - k.iushrn(1); + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } - - return naf; } - utils.getNAF = getNAF; - // Represent k1, k2 in a Joint Sparse Form - function getJSF(k1, k2) { - var jsf = [ - [], - [], - ]; + Transform$3.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. - 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); + Transform$3.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + + Transform$3.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); + Transform$3.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } + }; - return jsf; - } - utils.getJSF = getJSF; + Transform$3.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; - 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 done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided - function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); } - utils.parseBytes = parseBytes; - function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); - } - utils.intFromLE = intFromLE; - }(utils$n)); + var _stream_passthrough = PassThrough; - var brorand = {exports: {}}; + var Transform$2 = _stream_transform; - var r$1; + inherits_browser.exports(PassThrough, Transform$2); - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform$2.call(this, options); + } - return r$1.generate(len); + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; - function Rand(rand) { - this.rand = rand; + var eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } - brorand.exports.Rand = Rand; - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + var _require$codes = errorsBrowser.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; - }; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - 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; - }; + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + + function call(fn) { + fn(); + } + + function pipe(from, to) { + return from.pipe(to); + } + + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; } - } else { - // Node.js or Web worker with no crypto support - try { - var crypto$3 = require('crypto'); - if (typeof crypto$3.randomBytes !== 'function') - throw new Error('Not supported'); - Rand.prototype._rand = function _rand(n) { - return crypto$3.randomBytes(n); - }; - } catch (e) { + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); } - var curve = {}; + var pipeline_1 = pipeline; - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; + (function (module, exports) { + exports = module.exports = _stream_readable; + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + }(readableBrowser, readableBrowser.exports)); - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$1 = readableBrowser.exports.Transform; + var inherits$g = inherits_browser.exports; - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); + function HashBase$2 (blockSize) { + Transform$1.call(this); - // Curve configuration, optional - this.n = conf.n && new BN$8(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + this._finalized = false; + } - this._bitLength = this.n ? this.n.bitLength() : 0; + inherits$g(HashBase$2, Transform$1); - // 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); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - } - var base = BaseCurve; - BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); + callback(error); }; - BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); - }; + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$e(p.precomputed); - var doubles = p._getDoubles(); + callback(error); + }; - var naf = getNAF(k, 1, this._bitLength); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - // 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); + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - 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); + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; } - return a.toP(); + + return this }; - BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - // Get NAF form - var naf = getNAF(k, w, this._bitLength); + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - // 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); + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - if (i < 0) - break; - var z = naf[i]; - assert$e(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; + return digest }; - BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - // 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; - } + var hashBase = HashBase$2; - // 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 inherits$f = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; + var ARRAY16$1 = new Array(16); - // 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()); - } + function MD5$2 () { + HashBase$1.call(this, 64); - 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 */ - ]; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } - 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; + inherits$f(MD5$2, HashBase$1); + + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - var k = 0; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - 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; + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - for (j = 0; j < len; j++) { - var z = tmp[j]; - 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(); + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (i = 0; i < len; i++) - wnd[i] = null; + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } - if (jacobianResult) - return acc; - else - return acc.toP(); - }; + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } - BaseCurve.BasePoint = BasePoint; - BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); - }; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); - }; + var md5_js = MD5$2; - BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$l.toArray(bytes, enc); + var Buffer$e = require$$0__default["default"].Buffer; + var inherits$e = inherits_browser.exports; + var HashBase = hashBase; - var len = this.p.byteLength(); + var ARRAY16 = new Array(16); - // 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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(bytes[bytes.length - 1] % 2 === 1); + var zl = [ + 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 res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); + var zr = [ + 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 + ]; - 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'); - }; + var sl = [ + 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 + ]; - BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); - }; + var sr = [ + 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 + ]; - BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + function RIPEMD160$3 () { + HashBase.call(this, 64); - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); - }; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } - BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); - }; + inherits$e(RIPEMD160$3, HashBase); - BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - 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; + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - return this; - }; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } - var doubles = this.precomputed.doubles; - if (!doubles) - return false; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); - }; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - 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); + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - return { - step: step, - points: doubles, - }; - }; - BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - 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, - }; + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer }; - BasePoint.prototype._getBeta = function _getBeta() { - return null; - }; + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; - }; + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - var inherits$f = {exports: {}}; + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } - var inherits_browser = {exports: {}}; + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - inherits_browser.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; - } - }; + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - inherits$f.exports = util.inherits; - } catch (e) { - /* istanbul ignore next */ - inherits$f.exports = inherits_browser.exports; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$e = inherits$f.exports; - var Base$3 = base; + var ripemd160$2 = RIPEMD160$3; - var assert$d = utils$k.assert; + var sha_js = {exports: {}}; - function ShortCurve(conf) { - Base$3.call(this, 'short', conf); + var Buffer$d = safeBuffer.exports.Buffer; - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } - // 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$e(ShortCurve, Base$3); - var short = ShortCurve; + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; } - } - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN$7(vec.a, 16), - b: new BN$7(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } } - return { - beta: beta, - lambda: lambda, - basis: basis, - }; + this._len += length; + return this }; - 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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); + this._block[rem] = 0x80; - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + + var bits = this._len * 8; + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; + + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash }; - ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(1); + var hash$3 = Hash$7; - // 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; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - 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)); + var inherits$d = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; + + Hash$6.call(this, 64, 56); + } - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } + inherits$d(Sha, Hash$6); - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ]; + return this }; - ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; - }; + Sha.prototype._update = function (M) { + var W = this._w; - ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$7(x, 16); - if (!x.red) - x = x.toRed(this.red); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - 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'); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - // 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(); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - return this.point(x, y); + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - var x = point.x; - var y = point.y; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - 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; + return H }; - 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(); + var sha$4 = Sha; - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - 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); + var inherits$c = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; - }; + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - function Point$2(curve, x, y, isRed) { - Base$3.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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; - } + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); } - inherits$e(Point$2, Base$3.BasePoint); - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; + inherits$c(Sha1, Hash$5); - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this }; - Point$2.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - 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; - }; + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - Point$2.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - 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), - }, - } ]; - }; + Sha1.prototype._update = function (M) { + var W = this._w; - Point$2.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; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; } - 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; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H }; - Point$2.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; + var sha1$1 = Sha1; - // P + O = P - if (p.inf) - return this; + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - // P + P = 2P - if (this.eq(p)) - return this.dbl(); + var inherits$b = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); + var K$2 = [ + 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 + ]; - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + var W$3 = new Array(64); - 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); - }; + function Sha256$1 () { + this.init(); - Point$2.prototype.dbl = function dbl() { - if (this.inf) - return this; + this._w = W$3; // new Array(64) - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); + Hash$4.call(this, 64, 56); + } - var a = this.curve.a; + inherits$b(Sha256$1, Hash$4); - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - 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); + return this }; - Point$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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); - }; + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } - Point$2.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); - }; + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } - Point$2.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); - }; + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - Point$2.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); - }; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - Point$2.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + Sha256$1.prototype._update = function (M) { + var W = this._w; - 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), - }, - }; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; } - return res; + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; + + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + + return H }; - Point$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + var sha256$2 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$a = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; + var W$2 = new Array(64); - function JPoint(curve, x, y, z) { - Base$3.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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); + function Sha224 () { + this.init(); - this.zOne = this.z === this.curve.one; + this._w = W$2; // new Array(64) + + Hash$3.call(this, 64, 56); } - inherits$e(JPoint, Base$3.BasePoint); - ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); + inherits$a(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this }; - JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); - return this.curve.point(ax, ay); + return H }; - JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }; + var sha224 = Sha224; - JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; + var inherits$9 = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - // P + O = P - if (p.isInfinity()) - return this; + var K$1 = [ + 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 + ]; - // 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 W$1 = new Array(160); - 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(); - } + function Sha512 () { + this.init(); + this._w = W$1; - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + Hash$2.call(this, 128, 112); + } - 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); + inherits$9(Sha512, Hash$2); - return this.curve.jpoint(nx, ny, nz); + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this }; - JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - // P + O = P - if (p.isInfinity()) - return this; + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - // 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); + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - 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(); - } + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - 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); + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - return this.curve.jpoint(nx, ny, nz); - }; + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (i = 0; i < pow; i++) - r = r.dbl(); - return r; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w; + + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - // 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 Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - 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); + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - jx = nx; - jz = nz; - jyd = dny; + W[i] = Wih; + W[i + 1] = Wil; } - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); - }; + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); - }; + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - 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 + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - // 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); + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - // 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 + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - // 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(); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - // 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); + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; + + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - return this.curve.jpoint(nx, ny, nz); + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + + return H }; - 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 + var sha512 = Sha512; - // 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 + var inherits$8 = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - // 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); - } + var W = new Array(160); + + function Sha384 () { + this.init(); + this._w = W; - return this.curve.jpoint(nx, ny, nz); - }; + Hash$1.call(this, 128, 112); + } - JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + inherits$8(Sha384, SHA512$2); - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + return this + }; - 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); + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - 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); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - return this.curve.jpoint(nx, ny, nz); + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H }; - JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); + var sha384 = Sha384; - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - // 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); + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - return this.curve.jpoint(nx, ny, nz); + return new Algorithm() }; - JPoint.prototype.mul = function mul(k, kbase) { - k = new BN$7(k, kbase); + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - return this.curve._wnafMul(this, k); - }; + var sha$3 = sha_js.exports; - JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + var Buffer$6 = safeBuffer.exports.Buffer; + var Transform = require$$1__default["default"].Transform; + var StringDecoder = require$$2__default["default"].StringDecoder; + var inherits$7 = inherits_browser.exports; - if (this === p) - return true; + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits$7(CipherBase, Transform); - // 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; + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer$6.from(data, inputEnc); + } - // 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; + var outData = this._update(data); + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + + return outData }; - 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; + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; - 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; + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; + + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); + } + } catch (e) { + err = e; + } finally { + next(err); } }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } - JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer$6.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData }; - JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + + return out }; - var BN$6 = bn.exports; - var inherits$d = inherits$f.exports; - var Base$2 = base; + var cipherBase = CipherBase; - var utils$j = utils$n; + var inherits$6 = inherits_browser.exports; + var MD5$1 = md5_js; + var RIPEMD160$2 = ripemd160$2; + var sha$2 = sha_js.exports; + var Base$5 = cipherBase; - function MontCurve(conf) { - Base$2.call(this, 'mont', conf); + function Hash (hash) { + Base$5.call(this, 'digest'); - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + this._hash = hash; } - inherits$d(MontCurve, Base$2); - var mont = 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(); + inherits$6(Hash, Base$5); - return y.redSqr().cmp(rhs) === 0; + Hash.prototype._update = function (data) { + this._hash.update(data); }; - function Point$1(curve, x, z) { - Base$2.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$6(x, 16); - this.z = new BN$6(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); + Hash.prototype._final = function () { + return this._hash.digest() + }; + + var browser$3 = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5$1() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() + + return new Hash(sha$2(alg)) + }; + + var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser$3 + }, [browser$3])); + + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; + } + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; + } + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode } } - inherits$d(Point$1, Base$2.BasePoint); + var src$2 = base$2; - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; + var bs58 = basex(ALPHABET$1); - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; + var base58 = bs58; + var Buffer$5 = safeBuffer.exports.Buffer; - Point$1.prototype.precompute = function precompute() { - // No-op - }; + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; + return base58.encode(Buffer$5.concat([ + payload, + checksum + ], payload.length + 4)) + } - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } }; - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + var createHash$2 = browser$3; + var bs58checkBase = base$1; + + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() + } + + var bs58check$5 = bs58checkBase(sha256x2); + + function pathElementsToBuffer(paths) { + var buffer = Buffer$l.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } + + var src$1 = {}; - Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A + var src = {}; - // 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); - }; + var bip32$1 = {}; - Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; + var crypto$5 = {}; - Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A + var inherits$5 = inherits_browser.exports; + var Buffer$4 = safeBuffer.exports.Buffer; - // 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); - }; + var Base$4 = cipherBase; - Point$1.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 + var ZEROS$1 = Buffer$4.alloc(128); + var blocksize = 64; - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); + function Hmac$2 (alg, key) { + Base$4.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$4.from(key); + } - 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(); - } + this._alg = alg; + this._key = key; + + if (key.length > blocksize) { + key = alg(key); + } else if (key.length < blocksize) { + key = Buffer$4.concat([key, ZEROS$1], blocksize); } - return b; - }; - Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); + var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; + this._hash = [ipad]; + } + + inherits$5(Hmac$2, Base$4); + + Hmac$2.prototype._update = function (data) { + this._hash.push(data); }; - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; + Hmac$2.prototype._final = function () { + var h = this._alg(Buffer$4.concat(this._hash)); + return this._alg(Buffer$4.concat([this._opad, h])) }; + var legacy = Hmac$2; - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); + var MD5 = md5_js; - return this.x.fromRed(); + var md5$1 = function (buffer) { + return new MD5().update(buffer).digest() }; - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$c = inherits$f.exports; - var Base$1 = base; + var inherits$4 = inherits_browser.exports; + var Legacy = legacy; + var Base$3 = cipherBase; + var Buffer$3 = safeBuffer.exports.Buffer; + var md5 = md5$1; + var RIPEMD160$1 = ripemd160$2; - var assert$c = utils$i.assert; + var sha$1 = sha_js.exports; - 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; + var ZEROS = Buffer$3.alloc(128); - Base$1.call(this, 'edwards', conf); + function Hmac$1 (alg, key) { + Base$3.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$3.from(key); + } - this.a = new BN$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; + this._alg = alg; + this._key = key; + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + key = hash.update(key).digest(); + } else if (key.length < blocksize) { + key = Buffer$3.concat([key, ZEROS], blocksize); + } + + var ipad = this._ipad = Buffer$3.allocUnsafe(blocksize); + var opad = this._opad = Buffer$3.allocUnsafe(blocksize); + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } + this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + this._hash.update(ipad); } - inherits$c(EdwardsCurve, Base$1); - var edwards = EdwardsCurve; - EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); + inherits$4(Hmac$1, Base$3); + + Hmac$1.prototype._update = function (data) { + this._hash.update(data); }; - EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); + Hmac$1.prototype._final = function () { + var h = this._hash.digest(); + var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); + return hash.update(this._opad).update(h).digest() }; - // Just for compatibility with Short curve - EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); + var browser$2 = function createHmac (alg, key) { + alg = alg.toLowerCase(); + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac$1('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac$1(alg, key) }; - EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$5(x, 16); - if (!x.red) - x = x.toRed(this.red); + Object.defineProperty(crypto$5, "__esModule", { value: true }); + const createHash$1 = browser$3; + const createHmac$1 = browser$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } + } + crypto$5.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$5.hmacSHA512 = hmacSHA512; - 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 bn$1 = {exports: {}}; - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + (function (module) { + (function (module, exports) { - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - return this.point(x, y); - }; + // 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; + } - EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN$5(y, 16); - if (!y.red) - y = y.toRed(this.red); + // BN - // 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()); + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } + this.negative = 0; + this.words = null; + this.length = 0; - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + // Reduction context + this.red = null; - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } - return this.point(x, y); - }; + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; + BN.BN = BN; + BN.wordSize = 26; - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; + } + } catch (e) { + } - 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))); + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - return lhs.cmp(rhs) === 0; - }; + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - function Point(curve, x, y, z, t) { - Base$1.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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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; + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - // 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()); + 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); } - } - } - inherits$c(Point, Base$1.BasePoint); - EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); - }; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); - }; + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); - }; + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + 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); + } + } + } + }; - 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)); - }; + 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; + } - Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S + if (endian !== 'le') return; - // 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); - }; + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - 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 + 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; + } - // 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(); + 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 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); + 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; } - } 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 + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } - // 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); - }; + 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; + } - Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S + // 24-bits chunks + var off = 0; + var j = 0; - // 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); - }; + 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; + } + } + } - Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; + this.strip(); + }; - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); - }; + 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; - Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); - }; + r *= mul; - Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); - }; + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); - }; + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; + // '0' - '9' + } else { + r += c; + } + } + return r; + } - // 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; - }; + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); - }; + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); - }; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); - }; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; - }; + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - 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; + for (i = 0; i < mod; i++) { + pow *= base; + } - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - // Compatibility with BaseCurve - Point.prototype.toP = Point.prototype.normalize; - Point.prototype.mixedAdd = Point.prototype.add; + this.strip(); + }; - (function (exports) { + 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; + }; - var curve = exports; + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; - var curves$2 = {}; + // 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(); + }; - var hash$3 = {}; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - var utils$h = {}; + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - var assert$b = minimalisticAssert; - var inherits$b = inherits$f.exports; + /* - utils$h.inherits = inherits$b; + var zeros = []; + var groupSizes = []; + var groupBases = []; - function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { - return false; - } - if (i < 0 || i + 1 >= msg.length) { - return false; + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; } - 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)); + 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; } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; + groupSizes[base] = groupSize; + groupBases[base] = groupBase; } - return res; - } - utils$h.toArray = toArray; - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils$h.toHex = toHex; + */ - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.htonl = htonl; + 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' + ]; - 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; - } - utils$h.toHex32 = toHex32; + 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 + ]; - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils$h.zero2 = zero2; + 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 + ]; - 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; - } - utils$h.zero8 = zero8; + 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; + } - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.join32 = join32; + 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); - 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; + 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; } - } - return res; - } - utils$h.split32 = split32; - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); - } - utils$h.rotr32 = rotr32$1; + assert(false, 'Base should be between 2 and 36'); + }; - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; + 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; + }; - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - utils$h.sum32_5 = sum32_5$2; + 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'); - function sum64$1(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; - } - utils$h.sum64 = sum64$1; + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - utils$h.sum64_hi = sum64_hi$1; + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - utils$h.sum64_lo = sum64_lo$1; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - function sum64_4_hi$1(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; + res[i] = b; + } - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; - } - utils$h.sum64_4_hi = sum64_4_hi$1; + for (; i < reqLength; i++) { + res[i] = 0; + } + } - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; + return res; + }; - function sum64_5_hi$1(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; + 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; + }; + } - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; - } - utils$h.sum64_5_hi = sum64_5_hi$1; + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; + 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 lo >>> 0; - } - utils$h.sum64_5_lo = sum64_5_lo$1; + // 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 rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - utils$h.rotr64_hi = rotr64_hi$1; + function toBitArray (num) { + var w = new Array(num.bitLength()); - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.rotr64_lo = rotr64_lo$1; + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - function shr64_hi$1(ah, al, num) { - return ah >>> num; - } - utils$h.shr64_hi = shr64_hi$1; + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.shr64_lo = shr64_lo$1; + return w; + } - var common$5 = {}; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - var utils$g = utils$h; - var assert$a = minimalisticAssert; + 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; + }; - function BlockHash$4() { - 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'; + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; - } - common$5.BlockHash = BlockHash$4; + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - // 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; + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; - msg = utils$g.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); - } + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } - return this; - }; + return this; + }; - BlockHash$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - return this._digest(enc); - }; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - BlockHash$4.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; + return this.strip(); + }; - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - 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; + // 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); + }; - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - return res; - }; + // 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; + } - var sha$3 = {}; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } - var common$4 = {}; + this.length = b.length; - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; + return this.strip(); + }; - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; + // 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); + }; - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; + // 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; + } - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; + 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); + }; - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; + // 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); + }; - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - common$4.g1_256 = g1_256$1; + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - var utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); + if (bitsLeft > 0) { + bytesNeeded--; + } - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); - } + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - utils$e.inherits(SHA1, BlockHash$3); - var _1 = SHA1; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - SHA1.blockSize = 512; - SHA1.outSize = 160; - SHA1.hmacStrength = 80; - SHA1.padLength = 64; + // And remove leading zeroes + return this.strip(); + }; - SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - for(; i < W.length; i++) - W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + var off = (bit / 26) | 0; + var wbit = bit % 26; - 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]; + this._expand(off + 1); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; - } + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); - }; + return this.strip(); + }; - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); - }; + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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; + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } - var BlockHash$2 = common$2.BlockHash; + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } - 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 - ]; + 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; + } - function SHA256$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); + 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]; + } + } - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$1; + return this; + }; - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; + // 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; + } - SHA256$1.prototype._update = function _update(msg, start) { - var W = this.W; + if (this.length > num.length) return this.clone().iadd(num); - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + return num.clone().iadd(this); + }; - 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]; + // 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(); - assert$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; + // At this point both numbers are positive + var cmp = this.cmp(num); - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); - else - return utils$d.split32(this.h, 'big'); - }; + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } - var utils$c = utils$h; - var SHA256 = _256; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); + 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; + } - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils$c.inherits(SHA224, SHA256); - var _224 = SHA224; + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - SHA224.blockSize = 512; - SHA224.outSize = 224; - SHA224.hmacStrength = 192; - SHA224.padLength = 64; + this.length = Math.max(this.length, i); - SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); - }; + if (a !== this) { + this.negative = 1; + } - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; + return this.strip(); + }; - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; - var BlockHash$1 = common$1.BlockHash; + 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; - 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 - ]; + // 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; - function SHA512$2() { - if (!(this instanceof SHA512$2)) - return new SHA512$2(); + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - BlockHash$1.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$b.inherits(SHA512$2, BlockHash$1); - var _512 = SHA512$2; + 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--; + } - SHA512$2.blockSize = 1024; - SHA512$2.outSize = 512; - SHA512$2.hmacStrength = 192; - SHA512$2.padLength = 128; + return out.strip(); + } - SHA512$2.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; + // 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; - // 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]; + 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; + }; - 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); + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; } - }; - - SHA512$2.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$8(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); - 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); - 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); + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - dh = ch; - dl = cl; + 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; - ch = bh; - cl = bl; + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; - bh = ah; - bl = al; + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + return out.strip(); } - 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$2.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.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); + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + 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); + } - var utils$a = utils$h; + return res; + }; - var SHA512$1 = _512; + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); + function FFTM (x, y) { + this.x = x; + this.y = y; + } - SHA512$1.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; - } - utils$a.inherits(SHA384, SHA512$1); - var _384 = SHA384; + 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); + } - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; + return t; + }; - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); - }; + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; - sha$3.sha1 = _1; - sha$3.sha224 = _224; - sha$3.sha256 = _256; - sha$3.sha384 = _384; - sha$3.sha512 = _512; + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } - var ripemd = {}; + return rb; + }; - var utils$9 = utils$h; - var common = common$5; + // 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]]; + } + }; - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; - var BlockHash = common.BlockHash; + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - function RIPEMD160$2() { - if (!(this instanceof RIPEMD160$2)) - return new RIPEMD160$2(); + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - BlockHash.call(this); + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils$9.inherits(RIPEMD160$2, BlockHash); - ripemd.ripemd160 = RIPEMD160$2; + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - RIPEMD160$2.blockSize = 512; - RIPEMD160$2.outSize = 160; - RIPEMD160$2.hmacStrength = 192; - RIPEMD160$2.padLength = 64; + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - RIPEMD160$2.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$4(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; - }; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; - RIPEMD160$2.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); - else - return utils$9.split32(this.h, 'little'); - }; + var rx = rtwdf_ * ro - itwdf_ * io; - 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)); - } + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; - function K$4(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; - } + rtws[p + j] = re + ro; + itws[p + j] = ie + io; - 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; - } + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; - 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 - ]; + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; - 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 - ]; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; - 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 - ]; + 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++; + } - 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 - ]; + return 1 << i + 1 + odd; + }; - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; - 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; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; - this._init(utils$8.toArray(key, enc)); - } - var hmac = Hmac; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(key.length <= this.blockSize); + t = iws[i]; - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); + 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; - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); - }; + ws[i] = w & 0x3ffffff; - Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; - }; + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } - Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); - }; + return ws; + }; - (function (exports) { - var hash = exports; + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha$3; - hash.ripemd = ripemd; - hash.hmac = hmac; + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } - // 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; - }(hash$3)); + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } - (function (exports) { + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; - var curves = exports; + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } - var hash = hash$3; - var curve$1 = curve; - var utils = utils$n; + return ph; + }; - var assert = utils.assert; + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; + var rbt = this.makeRBT(N); - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); - } - curves.PresetCurve = PresetCurve; + var _ = this.stub(N); - 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; - }, - }); - } + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); - 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', - ], - }); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); - 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', - ], - }); + var rmws = out.words; + rmws.length = N; - 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', - ], - }); + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); - 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', - ], - }); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); - 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', - ], - }); + 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; + } - 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', - ], - }); + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); - 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', + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658', - ], - }); + // 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); + }; - var pre; - try { - pre = require('./precomputed/secp256k1'); - } catch (e) { - pre = undefined; - } + // 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); + }; - 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, + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3', - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15', - }, - ], + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre, - ], - }); - }(curves$2)); + // 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; + } - var hash$2 = hash$3; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + return this; + }; - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; - var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; - HmacDRBG$1.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); - 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; - } + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 - }; + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; - HmacDRBG$1.prototype._hmac = function hmac() { - return new hash$2.hmac(this.hash, this.K); - }; + res = res.mul(q); + } + } - HmacDRBG$1.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; + return res; + }; - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); - }; + // 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; - HmacDRBG$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } + if (r !== 0) { + var carry = 0; - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); + 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); + } - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + if (carry) { + this.words[i] = carry; + this.length++; + } + } - this._update(entropy.concat(add || [])); - this._reseed = 1; - }; + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } - HmacDRBG$1.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); + for (i = 0; i < s; i++) { + this.words[i] = 0; + } - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } + this.length += s; + } - // Optional additional data - if (add) { - add = utils$7.toArray(add, addEnc || 'hex'); - this._update(add); - } + return this.strip(); + }; - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils$7.encode(res, enc); - }; + // 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 BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; - function KeyPair$4(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; + h -= s; + h = Math.max(0, h); - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); - } - var key$1 = KeyPair$4; + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; + if (s === 0) ; 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; + } - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); - }; + 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; + } - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); - }; + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } - KeyPair$4.prototype.validate = function validate() { - var pub = this.getPublic(); + return this.strip(); + }; - 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' }; + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; - return { result: true, reason: null }; - }; + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; - KeyPair$4.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; - if (!enc) - return this.pub; + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; - return this.pub.encode(enc, compact); - }; + // 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; - KeyPair$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(key, enc || 16); + // Check bit and return + var w = this.words[s]; - // 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); - }; + return !!(w & q); + }; - KeyPair$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(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); - }; + // 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; - // ECDH - KeyPair$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); - }; + assert(this.negative === 0, 'imaskn works only with positive numbers'); - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); - }; + if (this.length <= s) { + return this; + } - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); - }; + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); - KeyPair$4.prototype.inspect = function inspect() { - return ''; - }; + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } - var BN$3 = bn.exports; + return this.strip(); + }; - var utils$5 = utils$n; - var assert$4 = utils$5.assert; + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; + // 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); - if (this._importDER(options, enc)) - return; + // 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; + } - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } - function Position() { - this.place = 0; - } + // Add without checks + return this._iaddn(num); + }; - function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; - // Indefinite length or overflow - if (octetLen === 0 || octetLen > 4) { - return false; - } + // 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); - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - val >>>= 0; - } + return this; + }; - // Leading zeroes - if (val <= 0x7f) { - return false; - } + // 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); - p.place = off; - return val; - } + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } - 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); - } + this.words[0] -= num; - Signature$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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); + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; } else { - // Leading zeroes - return false; + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } } - } - - this.r = new BN$3(r); - this.s = new BN$3(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$3.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); + return this.strip(); + }; - r = rmPadding(r); - s = rmPadding(s); + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; - 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$5.encode(res, enc); - }; + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; + BN.prototype.iabs = function iabs () { + this.negative = 0; - var KeyPair$3 = key$1; - var Signature$2 = signature$1; + return this; + }; - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; - options = curves$1[options]; - } + this._expand(len); - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.PresetCurve) - options = { curve: options }; + 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; + } - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; + if (carry === 0) return this.strip(); - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); + // 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; - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; - } - var ec = EC$1; + return this.strip(); + }; - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); - }; + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); - }; + var a = this.clone(); + var b = num; - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); - }; + // 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; + } - EC$1.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; + // Initialize quotient + var m = a.length - b.length; + var q; - // 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(), - }); + 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 bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN$2(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); - EC$1.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; - }; + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - EC$1.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; + 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(); - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN$2(msg, 16)); + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); + return { + div: q || null, + mod: a + }; + }; - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); + // 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()); - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - }); + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } - // Number of bytes to generate - var ns1 = this.n.sub(new BN$2(1)); + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; + if (mode !== 'mod') { + div = res.div.neg(); + } - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + return { + div: div, + mod: mod + }; + } - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + if (mode !== 'mod') { + div = res.div.neg(); + } - // 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 { + div: div, + mod: res.mod + }; } - return new Signature$2({ r: r, s: s, recoveryParam: recoveryParam }); - } - }; - - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(signature, 'hex'); + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); - // 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; + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } - // 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; + return { + div: res.div, + mod: mod + }; + } - if (!this.curve._maxwellTrick) { - p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + // Both numbers are positive at this point - return p.getX().umod(this.n).cmp(r) === 0; - } + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } - p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } - // 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); - }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - EC$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); + return this._wordDiv(num, mode); + }; - var n = this.n; - var e = new BN$2(msg); - var r = signature.r; - var s = signature.s; + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; - // 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'); + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; - // 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); + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); - }; + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; - EC$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); - }; + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.cachedProperty; + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; - /** - * @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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes$2(params.pub); - } + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); - }; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); - }; + return acc; + }; - KeyPair$2.prototype.secret = function secret() { - return this._secret; - }; + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); + 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; + } - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); + return this.strip(); + }; - cachedProperty$1(KeyPair$2, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); - return a; - }); + var x = this; + var y = p.clone(); - cachedProperty$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); - }; + var g = 0; - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); - }; + var yp = y.clone(); + var xp = x.clone(); - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); - }; + 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); + } - var key = KeyPair$2; + A.iushrn(1); + B.iushrn(1); + } + } - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.parseBytes; + 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); + } - /** - * @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$1(eddsa, sig) { - this.eddsa = eddsa; + C.iushrn(1); + D.iushrn(1); + } + } - if (typeof sig !== 'object') - sig = parseBytes$1(sig); + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), + return { + a: C, + b: D, + gcd: y.iushln(g) }; - } + }; - assert$1(sig.R && sig.S, 'Signature without R or S'); + // 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()); - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - this._S = sig.S; + var a = this; + var b = p.clone(); - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; - } + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } - cachedProperty(Signature$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); + var x1 = new BN(1); + var x2 = new BN(0); - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); + var delta = b.clone(); - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); + 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); + } - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); + x1.iushrn(1); + } + } - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; + 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); + } - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; + x2.iushrn(1); + } + } - var signature = Signature$1; + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } - var hash$1 = hash$3; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); + if (res.cmpn(0) < 0) { + res.iadd(p); + } - if (!(this instanceof EDDSA)) - return new EDDSA(curve); + return res; + }; - curve = curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash$1.sha512; - } + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; - var eddsa = EDDSA; + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } - /** - * @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 }); - }; + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } - /** - * @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); - }; + 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; + } - EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils$1.intFromLE(hash.digest()).umod(this.curve.n); - }; + a.isub(b); + } while (true); - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; + return b.iushln(shift); + }; - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.fromSecret(this, secret); - }; + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; - EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); - }; + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; - /** - * * 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; - }; + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; - EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils$1.parseBytes(bytes); + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + // 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; - var y = utils$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); - }; + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } - EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); - }; + // 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; + }; - EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils$1.intFromLE(bytes); - }; + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; - (function (exports) { + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; - var elliptic = exports; + this.strip(); - elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); + assert(num <= 0x3ffffff, 'Number is too big'); - const createHmac = createHmac$2; + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; - const ONE1 = Buffer$i.alloc(1, 1); - const ZERO1 = Buffer$i.alloc(1, 0); + // 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; - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer$i.alloc(32, 0); - let v = Buffer$i.alloc(32, 1); + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + // 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; - // Step E - v = createHmac('sha256', k).update(v).digest(); + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; - // Step G - v = createHmac('sha256', k).update(v).digest(); + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; - let T = v; + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; - v = createHmac('sha256', k).update(v).digest(); + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; - } + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; - return T - } + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; - var rfc6979 = deterministicGenerateK$1; + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; - const BN = bn$1.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; - const ZERO32 = Buffer$i.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$i.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$i.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + 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); + }; - function isScalar (x) { - return isBuffer(x) && x.length === 32 - } + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G - } + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; - function isPoint (p) { - if (!isBuffer(p)) return false - if (p.length < 33) return false + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false - } + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - function __isPointCompressed (p) { - return p[0] !== 0x04 - } + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) - } + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G - } + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 - } + 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); + }; - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value - } + 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); + }; - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$i, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$i.from(P._encode(compressed)) } + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null + // 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); + }; - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) - } + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + // 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); + }; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; - return getEncoded(uu, compressed) - } + // 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); - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + this.tmp = this._tmp(); + } - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - const compressed = assumeCompression(__compressed, p); + 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; - return getEncoded(pp, compressed) - } + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + 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(); + } + } - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null + return r; + }; - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); - return getEncoded(qq, compressed) - } + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } - return dt - } + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + 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; + } + }; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; - return dt - } + // 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); + } - function sign$1 (hash, x) { - return __sign(hash, x) - } + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) - } + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); + 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; - if (Q.isInfinity()) return false + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; - r = Q.x.umod(n); - if (r.isZero() === 0) return false + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false + 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 true + return prime; }; - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); - - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); + // + // 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; + } } - const buffer = Buffer$i.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer - } + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + 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'); + }; - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } - if (strict && s.cmp(nDiv2) > 0) { - return false - } + return this.m.sub(a)._forceRed(this); + }; - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + Red.prototype.add = function add (a, b) { + this._verify2(a, b); - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; - // Compute s^-1 - const sInv = s.invm(n); + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign: sign$1, - signWithEntropy, - verify - }; + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; - try { - tinySecp256k1.exports = require('./native'); - } catch (err) { - tinySecp256k1.exports = js; - } + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } - }; + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; - // TODO: deprecate - types$c.Null = types$c.Nil; + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); - } + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); - var native$1 = types$c; + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); - var native = native$1; + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] - } + // 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()); - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) - } + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value - } + // 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); - function captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } - } + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - function tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' + 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)); - return type !== undefined ? type : '' - } + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); + return r; + }; - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') - } + 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); + } + }; - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } + 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); + } - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; + 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); + } - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) - } + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + return res; + }; - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) - } + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; + return r === num ? r.clone() : r; + }; - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } + // + // Montgomery method engine + // - captureStackTrace(e); - return e - } + BN.mont = function mont (num) { + return new Mont(num); + }; - var errors$1 = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 - }; + function Mont (m) { + Red.call(this, m); - var NATIVE$1 = native$1; - var ERRORS$1 = errors$1; + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } - function _Buffer (value) { - return isBuffer(value) - } + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } + 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); - function _LengthN (type, length) { - var name = type.toJSON(); + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - return Length - } + 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; - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - function Range$b (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) - } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` + return res._forceRed(this); }; - return _range - } - var INT53_MAX = Math.pow(2, 53) - 1; + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - function Finite (value) { - return typeof value === 'number' && isFinite(value) - } - function Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value - } - function UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value - } + 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); + } - var types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$b, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; + return res._forceRed(this); + }; - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); - } + 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); + }; + })(module, commonjsGlobal); + }(bn$1)); - var extra = types$b; + var elliptic = {}; - var ERRORS = errors$1; - var NATIVE = native$1; + var name = "elliptic"; + var version = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0$1 = { + name: name, + version: version, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; + var utils$n = {}; - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; + var bn = {exports: {}}; - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false + (function (module) { + (function (module, exports) { - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - return _arrayOf - }, + // 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; + } - maybe: function maybe (type) { - type = compile(type); + // BN - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; - - return _maybe - }, - - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + this.negative = 0; + this.words = null; + this.length = 0; - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } + // Reduction context + this.red = null; - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; } - return true + this._init(number || 0, base || 10, endian || 'be'); } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; + Buffer = require('buffer').Buffer; } + } catch (e) { + } - return _map - }, + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - object: function object (uncompiled) { - var type = {}; + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - var propertyName; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - throw new TfPropertyTypeError(undefined, propertyName) + 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); } } - - return true } - _object.toJSON = function () { return tfJSON(type) }; - - return _object - }, - - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); + }; - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) + 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; } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - return _anyOf - }, + if (endian !== 'le') return; - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) + 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; } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - - return _allOf - }, - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) + 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; } - _quacksLike.toJSON = function () { return type }; - - return _quacksLike - }, - - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); - - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) + 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++; + } + } } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; - - return _tuple - }, + return this.strip(); + }; - value: function value (expected) { - function _value (actual) { - return actual === expected + 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; } - _value.toJSON = function () { return expected }; - - return _value } - }; - - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; - - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; } - - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } - - return TYPES.value(type) - } - - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true - - throw new TfTypeError(surrogate || type, value) + return r; } - // JIT - return typeforce$b(compile(type), value, strict) - } + 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; + } - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } + // 24-bits chunks + var off = 0; + var j = 0; - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } + 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; + } + } + } - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } + this.strip(); + }; - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + 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; - var typeforce_1 = typeforce$b; + r *= mul; - var bs58check$4 = bs58check$5; + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false + // '0' - '9' + } else { + r += c; + } } + return r; } - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$i(compressed ? 34 : 33); + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - result.writeUInt8(version, 0); - privateKey.copy(result, 1); + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - if (compressed) { - result[33] = 0x01; - } + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - return result - } + for (i = 0; i < mod; i++) { + pow *= base; + } - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) - } + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + this.strip(); + }; - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } + 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; + }; - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw - }; + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$2 = crypto$4; - const bs58check$3 = bs58check$5; - const ecc$6 = tinySecp256k1.exports; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; - } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$2.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer$i.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer$i.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$2.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); + 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; } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); + 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; } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$i.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; + 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; } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } - } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) + + 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; } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + + 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 hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); - } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); - } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); - } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); - } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$2.hmacSHA512(Buffer$i.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); - } - bip32$1.fromSeed = fromSeed; + return (this.negative !== 0) ? -ret : ret; + }; - Object.defineProperty(src, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - var address$1 = {}; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - var networks$3 = {}; + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; + 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'); - var payments$4 = {}; + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); - var embed = {}; + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } - var script$1 = {}; + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - var script_number = {}; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); + 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; + }; } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; - } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); - } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer$i.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; - } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; - } - return buffer; - } - script_number.encode = encode$g; - var script_signature = {}; + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - var types$a = {}; + 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; + }; - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; - }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, - }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; + // 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; + }; - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use + function toBitArray (num) { + var w = new Array(num.bitLength()); - var Buffer$g = safeBuffer.exports.Buffer; + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false + return w; + } - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + 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; + }; - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true - } + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } - } + return this; + }; - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - var signature = Buffer$g.allocUnsafe(6 + lenR + lenS); + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); + return this.strip(); + }; - return signature - } + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f - }; + // 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); + }; - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$i.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer$i.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$i.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer$i.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$i.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer$i.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE - }; + // 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; - var OPS$9 = require$$7; + return this.strip(); + }; - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 - } + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); + // 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); + }; - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); - } + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - return size - } + if (bitsLeft > 0) { + bytesNeeded--; + } - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; + // And remove leading zeroes + return this.strip(); + }; - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - number = buffer.readUInt32LE(offset + 1); - size = 5; + 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(); } - return { - opcode: opcode, - number: number, - size: size + // 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; } - } - - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c - }; - var OPS$8 = require$$7; + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } + 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 map_1 = map; + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = tinySecp256k1.exports; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer$i.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode + if (carry !== 0) { + out.words[k] = carry; } else { - chunks.push(opcode); - i += 1; + out.length--; } + + return out.strip(); } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer$i.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$i.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); - var lazy$7 = {}; + 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); + } - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; + return res; }; - } - lazy$7.value = value; - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; } - return Object.assign(o, a); - } - embed.p2data = p2data; - var p2ms$3 = {}; + 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); + } - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = tinySecp256k1.exports; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); + 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; } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + + 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]]; } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); + }; + + 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; + } + } + } } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); + }; + + 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 Object.assign(o, a); - } - p2ms$3.p2ms = p2ms$2; - var p2pk$3 = {}; + return 1 << i + 1 + odd; + }; - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = tinySecp256k1.exports; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); + 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; } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); + }; + + 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; + } } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); + + 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; } - } - return Object.assign(o, a); - } - p2pk$3.p2pk = p2pk$2; - var p2pkh$4 = {}; + // 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 crypto$1 = {}; + var _ = this.stub(N); - Object.defineProperty(crypto$1, '__esModule', { value: true }); - const createHash = createHash$3; - function ripemd160$2(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); - } - } - crypto$1.ripemd160 = ripemd160$2; - function sha1$1(buffer) { - return createHash('sha1') - .update(buffer) - .digest(); - } - crypto$1.sha1 = sha1$1; - function sha256$2(buffer) { - return createHash('sha256') - .update(buffer) - .digest(); - } - crypto$1.sha256 = sha256$2; - function hash160$1(buffer) { - return ripemd160$2(sha256$2(buffer)); - } - crypto$1.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$2(sha256$2(buffer)); - } - crypto$1.hash256 = hash256$1; + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); - const bcrypto$6 = crypto$1; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = tinySecp256k1.exports; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + 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; } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; + + 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 (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); + + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - } - return Object.assign(o, a); - } - p2pkh$4.p2pkh = p2pkh$3; - var p2sh$1 = {}; + return this; + }; - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$1; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; + 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 (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + + 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); + } } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + + 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 (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } + + if (carry) { + this.words[i] = carry; + this.length++; } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; } - } - return Object.assign(o, a); - } - p2sh$1.p2sh = p2sh; - var p2wpkh$2 = {}; + return this.strip(); + }; - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); + // 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; + } - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; - } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) - } + 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) ; 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; + } - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + 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; + } - chk = polymodStep(chk) ^ (c >> 5); - } - chk = polymodStep(chk); + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk - } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + return this.strip(); + }; - prefix = prefix.toLowerCase(); + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } + // 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; - return result - } + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' + // Check bit and return + var w = this.words[s]; - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; + return !!(w & q); + }; - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str + // 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; - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' + assert(this.negative === 0, 'imaskn works only with positive numbers'); - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk + if (this.length <= s) { + return this; + } - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); - } + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } - } + return this.strip(); + }; - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - } + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res + // 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); - throw new Error(res) - } + // 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; + } - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; + // Add without checks + return this._iaddn(num); + }; - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); + 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); - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); + 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; } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' - } - return result - } + this.words[0] -= num; - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - } + 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; + } + } - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res + return this.strip(); + }; - throw new Error(res) - } + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - } + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res + BN.prototype.iabs = function iabs () { + this.negative = 0; - throw new Error(res) - } + return this; + }; - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords - }; + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); - const bcrypto$4 = crypto$1; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = tinySecp256k1.exports; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$i.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$i.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2wpkh$2.p2wpkh = p2wpkh$1; + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; - var p2wsh$1 = {}; + this._expand(len); - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$1; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = tinySecp256k1.exports; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$i.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - function chunkHasUncompressedPubkey(chunk) { - if ( - isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; - } else { - return false; - } - } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$i.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; - } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), - }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); + 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; } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer$i.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; + + 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; } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + 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; } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + + // 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; } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; } } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); + + 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; + } } - } - return Object.assign(o, a); - } - p2wsh$1.p2wsh = p2wsh; + if (q) { + q.strip(); + } + a.strip(); - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer$i.from(data), + return { + div: q || null, + mod: a + }; }; - } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$i.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); - } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); - } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); - } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; + + // 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 + }; } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; - var ecpair = {}; + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); - var randombytes = require$$0__default["default"].randomBytes; + if (mode !== 'mod') { + div = res.div.neg(); + } - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = tinySecp256k1.exports; - const randomBytes = randombytes; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$i.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); + 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 sig; + + return { + div: res.div, + mod: mod + }; } - } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; - var block = {}; + // Both numbers are positive at this point - var bufferutils = {}; + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } - var Buffer$f = safeBuffer.exports.Buffer; + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') - } + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - function encode$b (number, buffer, offset) { - checkUInt53$1(number); + return this._wordDiv(num, mode); + }; - if (!buffer) buffer = Buffer$f.allocUnsafe(encodingLength$1(number)); - if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + // 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; + } - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; + return acc; + }; - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; + 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; + } - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } + return this.strip(); + }; - return buffer - } + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; - function decode$a (buffer, offset) { - if (!Buffer$f.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); - var first = buffer.readUInt8(offset); + var x = this; + var y = p.clone(); - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); + var g = 0; - return number - } - } + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } - function encodingLength$1 (number) { - checkUInt53$1(number); + var yp = y.clone(); + var xp = x.clone(); - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } + 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); + } - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + A.iushrn(1); + B.iushrn(1); + } + } - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer$i.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; - } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); - } - } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); - } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); - } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; - } - } - bufferutils.BufferReader = BufferReader$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); + } - var transaction = {}; + C.iushrn(1); + D.iushrn(1); + } + } - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$1; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; - } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); - } - const EMPTY_SCRIPT = Buffer$i.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer$i.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer$i.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer$i.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, - }; - function isOutput(out) { - return out.value !== undefined; - } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; - } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); - } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); - } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); - } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer$i.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; - } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; + + 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); } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts + + var res; + if (a.cmpn(1) === 0) { + res = x1; } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; + res = x2; } - // serialize and hash - const buffer = Buffer$i.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer$i.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$i.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); + + if (res.cmpn(0) < 0) { + res.iadd(p); } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer$i.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); + + 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); } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer$i.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer$i.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); + + 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; } - tbuffer = Buffer$i.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$i.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$i.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + + // 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; } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); + 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 { - bufferWriter.writeSlice(txOut.valueBuffer); + // r is BN v5 instance + r._strip(); } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; + + 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'); } - } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; + inherits(K256, MPrime); - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - var length = values.length; - var results = values.concat(); + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; - while (length > 1) { - var j = 0; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$i.concat([left, right]); + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - results[j] = digestFn(data); + 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; } + }; - length = j; - } + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; - return results[0] - }; + // 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); + } - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$1; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer$i.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer$i.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer$i.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer$i.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$i && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer$i && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer$i.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; - } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); - } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; + 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; + } } - } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { - return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 - ); - } - function anyTxHasWitness(transactions) { - return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) - ); - } - var psbt$1 = {}; + 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 psbt = {}; + 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)); - var combiner = {}; + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } - var parser = {}; + return r; + }; - var fromBuffer = {}; + 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); + } + }; - var converter = {}; + 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 typeFields = {}; + 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); + } - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - var globalXpub$1 = {}; + 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); + } - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer$i.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$i.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$i.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, + 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; }; - } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); - } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 - ); - } - globalXpub$1.canAddToArray = canAddToArray$1; - var unsignedTx$1 = {}; + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer$i.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), + return r === num ? r.clone() : r; }; - } - unsignedTx$1.encode = encode$9; - var finalScriptSig$1 = {}; + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer$i.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; - var finalScriptWitness$1 = {}; + function Mont (m) { + Red.call(this, m); - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); + 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); } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer$i.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); - return { - key, - value: data, + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); - } - finalScriptWitness$1.canAdd = canAdd$4; - var nonWitnessUtxo$1 = {}; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer$i.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, + 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); }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; - } - nonWitnessUtxo$1.canAdd = canAdd$3; - var partialSig$1 = {}; + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, + 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); }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer$i.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer$i.concat([head, pSig.pubkey]), - value: pSig.signature, + + 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); }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) - ); - } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; + })(module, commonjsGlobal); + }(bn)); - var porCommitment$1 = {}; + var minimalisticAssert = assert$f; - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer$i.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); - return { - key, - value: Buffer$i.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; - } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); } - porCommitment$1.canAdd = canAdd$2; - var sighashType$1 = {}; + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); + var utils$m = {}; + + (function (exports) { + + 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; } - return keyVal.value.readUInt32LE(0); - } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer$i.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$i.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; + 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; } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; + utils.toArray = toArray; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; + utils.zero2 = zero2; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; } - sighashType$1.canAdd = canAdd$1; + utils.toHex = toHex; - var witnessUtxo$1 = {}; + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + }(utils$m)); - var tools = {}; + (function (exports) { - var varint$1 = {}; + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) - throw new RangeError('value out of range'); - } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer$i.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } - return buffer; - } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; - } - } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; - } - varint$1.encodingLength = encodingLength; + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$i.from([0])); - return Buffer$i.concat(buffers); - } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$i.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, - ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; - } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; - } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - tools.writeUInt64LE = writeUInt64LE; + // 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); - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + 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 { - script, - value, - }; - } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$i.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer$i.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, - }; - } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; - } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; + + return naf; } - witnessUtxo$1.canAdd = canAdd; + utils.getNAF = getNAF; - var bip32Derivation$1 = {}; + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); + 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; } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + 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; } - return data; - } - function encode(data) { - const head = Buffer$i.from([TYPE_BYTE]); - const key = Buffer$i.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$i.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + 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 { - decode, - encode, - check, - expected, - canAddToArray, + + 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); }; } - bip32Derivation$1.makeConverter = makeConverter$2; + utils.cachedProperty = cachedProperty; - var checkPubkey$1 = {}; + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; + } + utils.parseBytes = parseBytes; - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); - if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } - } - return pubkey; - } + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); } - checkPubkey$1.makeChecker = makeChecker; + utils.intFromLE = intFromLE; + }(utils$n)); - var redeemScript$1 = {}; + var brorand = {exports: {}}; - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$i.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; - } - return { - decode, - encode, - check, - expected, - canAdd, - }; + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; } - redeemScript$1.makeConverter = makeConverter$1; + brorand.exports.Rand = Rand; - var witnessScript$1 = {}; + Rand.prototype.generate = function generate(len) { + return this._rand(len); + }; - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$i.from([TYPE_BYTE]); - return { - key, - value: data, + // 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'); }; } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); + } else { + // Node.js or Web worker with no crypto support + try { + var crypto$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); } - return { - decode, - encode, - check, - expected, - canAdd, - }; } - witnessScript$1.makeConverter = makeConverter; + var base = BaseCurve; - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), + + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); }; - converter.outputs = outputs; - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; - } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); - return { - key, - value, - }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); - } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; - } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', - ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); - } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$e(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); } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); - } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); + + 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()); } - inputKeyVals.push(input); + a = a.add(b); } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); - } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); + 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$e(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()); } - outputKeyVals.push(output); } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); - } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$i.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); + 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; } - } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; - } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); + + // 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; } - } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - } + + 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; } - inputs.push(input); } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); + + 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]; + 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); } - outputs.push(output); } - return { globalMap, inputs, outputs }; - } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; - var toBuffer = {}; + if (jacobianResult) + return acc; + else + return acc.toP(); + }; - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer$i.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$i.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$i.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); + BaseCurve.BasePoint = BasePoint; + + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); - } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along + + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; + + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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 { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + step: step, + points: doubles, }; - } - toBuffer.psbtToKeyVals = psbtToKeyVals; + }; - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + 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; + }; + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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); } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); + inherits$3(ShortCurve, Base$2); + var short = ShortCurve; - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); + 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$7(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); } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); + if (conf.lambda) { + lambda = new BN$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, - }); - } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN$7(vec.a, 16), + b: new BN$7(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis, }; - } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; - } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); - }); - return set; - } + }; - var utils = {}; + 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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; - } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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; } - if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 - ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + 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; } - } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } - }); - return count; - } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); } - } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, - ); - } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; + + 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$7(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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); } - }; - } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); - } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); - } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); - } - txBuf.writeUInt32LE(version, 0); - return txBuf; - } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); + 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; } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); + inherits$3(Point$2, Base$2.BasePoint); - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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), + }, }; } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer$i.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer$i.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); + return beta; + }; + + Point$2.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$2.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); } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); + + 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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) return this; - } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); + + // 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$2.prototype.dbl = function dbl() { + if (this.inf) return this; - } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); + + // 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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(z, 16); } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); + 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$3(JPoint, Base$2.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(); } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); + + 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(); } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); + + 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; - } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); + 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; } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; + + // 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; } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } + + 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); } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; + + 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); } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); + + 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$7(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; + }; + + var BN$6 = bn.exports; + var inherits$2 = inherits_browser.exports; + var Base$1 = base; + + var utils$j = utils$n; + + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); + + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } - psbt.Psbt = Psbt$1; + inherits$2(MontCurve, Base$1); + var mont = MontCurve; - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$1; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, + 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; }; - /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. - */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); - } - static fromBase64(data, opts = {}) { - const buffer = Buffer$i.from(data, 'base64'); - return this.fromBuffer(buffer, opts); - } - static fromHex(data, opts = {}) { - const buffer = Buffer$i.from(data, 'hex'); - return this.fromBuffer(buffer, opts); - } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; - } - get inputCount() { - return this.data.inputs.length; - } - get version() { - return this.__CACHE.__TX.version; - } - set version(version) { - this.setVersion(version); - } - get locktime() { - return this.__CACHE.__TX.locktime; - } - set locktime(locktime) { - this.setLocktime(locktime); - } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); - } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); - } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; - } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; - } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; - } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; - } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; - } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); - } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; - } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; + + function Point$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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); } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + inherits$2(Point$1, Base$1.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); + }; + + Point$1.prototype.precompute = function precompute() { + // No-op + }; + + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; + + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point$1.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$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.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$1.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(); } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; + return b; + }; + + Point$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$1 = inherits_browser.exports; + var Base = base; + + var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$1(EdwardsCurve, Base); + var edwards = 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$5(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$5(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); } - addOutput(outputData) { - if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) - ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); + + 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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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()); } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); + } + inherits$1(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); } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); - return tx; - } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } 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); } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + 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); } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, - ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); + 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; } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), - ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + }; + + // Compatibility with BaseCurve + Point.prototype.toP = Point.prototype.normalize; + Point.prototype.mixedAdd = Point.prototype.add; + + (function (exports) { + + var curve = exports; + + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); + + var curves$2 = {}; + + var hash$2 = {}; + + var utils$h = {}; + + var assert$b = minimalisticAssert; + var inherits = inherits_browser.exports; + + utils$h.inherits = inherits; + + function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) - ); + if (i < 0 || i + 1 >= msg.length) { + return false; } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + 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; } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); + return res; + } + utils$h.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.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)); } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), - ); - return results.reduce((final, res) => res === true && final, true); + return res; + } + utils$h.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.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; + } + utils$h.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); + return res; + } + utils$h.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 results.every(res => res === true); } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; + return res; + } + utils$h.split32 = split32; + + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; + + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; + + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; + + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; + + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; + + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; + + function sum64$1(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; + } + utils$h.sum64 = sum64$1; + + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; + + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; + + function sum64_4_hi$1(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; + } + utils$h.sum64_4_hi = sum64_4_hi$1; + + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; + + function sum64_5_hi$1(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; + } + utils$h.sum64_5_hi = sum64_5_hi$1; + + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; + + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; + + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; + + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; + + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; + + var common$5 = {}; + + var utils$g = utils$h; + var assert$a = minimalisticAssert; + + function BlockHash$4() { + 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; + } + common$5.BlockHash = BlockHash$4; + + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.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$g.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); } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$1(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); + + return this; + }; + + BlockHash$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); + + return this._digest(enc); + }; + + BlockHash$4.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; } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; + + return res; + }; + + var sha = {}; + + var common$4 = {}; + + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; + + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); + } + common$4.ft_1 = ft_1$1; + + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; + + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + common$4.maj32 = maj32$1; + + function p32(x, y, z) { + return x ^ y ^ z; + } + common$4.p32 = p32; + + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$4.s0_256 = s0_256$1; + + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$4.s1_256 = s1_256$1; + + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + common$4.g0_256 = g0_256$1; + + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + common$4.g1_256 = g1_256$1; + + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; + + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; + + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; + + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); + } + + utils$e.inherits(SHA1, BlockHash$3); + var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); + + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; + + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; + + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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$2 = common$2.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$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; + + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; + + SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$1(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; + + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; + + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; + + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; + + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; + + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; + + var BlockHash$1 = common$1.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$1() { + if (!(this instanceof SHA512$1)) + return new SHA512$1(); + + BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); + var _512 = SHA512$1; + + SHA512$1.blockSize = 1024; + SHA512$1.outSize = 512; + SHA512$1.hmacStrength = 192; + SHA512$1.padLength = 128; + + SHA512$1.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); } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); + }; + + SHA512$1.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$8(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); + 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); + 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); } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; + + 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$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.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; + } + + var utils$a = utils$h; + + var SHA512 = _512; + + 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$a.inherits(SHA384, SHA512); + var _384 = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); + }; + + sha.sha1 = _1; + sha.sha224 = _224; + sha.sha256 = _256; + sha.sha384 = _384; + sha.sha512 = _512; + + var ripemd = {}; + + var utils$9 = utils$h; + var common = common$5; + + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.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$9.inherits(RIPEMD160, BlockHash); + ripemd.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; } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); + 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$9.toHex32(this.h, 'little'); + else + return utils$9.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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); + } + var hmac = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(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); + }; + + (function (exports) { + var hash = exports; + + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha; + hash.ripemd = ripemd; + hash.hmac = hmac; + + // 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; + }(hash$2)); + + (function (exports) { + + var curves = exports; + + var hash = hash$2; + var curve$1 = curve; + var utils = utils$n; + + var assert = utils.assert; + + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.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, }); - }); - } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); - } - toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); - } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); - } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; - } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); - } - return this; - } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; - } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; - } + return curve; + }, + }); } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer$i.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); - } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; - } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); - } - addOutput(output) { - if ( - output.script === undefined || - output.value === undefined || - !isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); - } - toBuffer() { - return this.tx.toBuffer(); - } + + 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 = require('./precomputed/secp256k1'); + } 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, + ], + }); + }(curves$2)); + + var hash$1 = hash$2; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; + + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; + var hmacDrbg = HmacDRBG$1; + + HmacDRBG$1.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; } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 + }; + + HmacDRBG$1.prototype._hmac = function hmac() { + return new hash$1.hmac(this.hash, this.K); + }; + + HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); + + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG$1.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; } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); + + // Optional additional data + if (add) { + add = utils$7.toArray(add, addEnc || 'hex'); + this._update(add); } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, - ); + + 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$7.encode(res, enc); + }; + + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; + + function KeyPair$4(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); } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } - }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } + var key$1 = KeyPair$4; + + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, - ); - } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); + }; + + KeyPair$4.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$4.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer$i.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); + }; + + KeyPair$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(key.x && key.y, 'Need both x and y coordinate'); } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); + this.pub = this.ec.curve.point(key.x, key.y); + return; } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; - } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, - ); - } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } + this.pub = this.ec.curve.decodePoint(key, enc); + }; + + // ECDH + KeyPair$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, - ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); - throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, - ); + var signature$1 = Signature$3; + + function Position() { + this.place = 0; + } + + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); + var octetLen = initial & 0xf; + + // Indefinite length or overflow + if (octetLen === 0 || octetLen > 4) { + return false; } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, - ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, - ); + + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; } - return { - script: meaningfulScript, - sighashType, - hash, - }; - } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; + + // Leading zeroes + if (val <= 0x7f) { + return false; } - return payment; - } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); + + p.place = off; + return val; } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, - }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } + + function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; + if (i === 0) { + return buf; } - return res; + return buf.slice(i); } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); + + Signature$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { - throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', - ); + var len = getLength(data, p); + if (len === false) { + return false; } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; - } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); - } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); + if ((len + p.place) !== data.length) { + return false; } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; + if (data[p.place++] !== 0x02) { + return false; } - function readVarSlice() { - return readSlice(readVarInt()); + var rlen = getLength(data, p); + if (rlen === false) { + return false; } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; } - return readVector(); - } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; + var slen = getLength(data, p); + if (slen === false) { + return false; } - return text; - } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer$i.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer$i.concat([buffer, Buffer$i.from(slice)]); + if (data.length !== slen + p.place) { + return false; } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer$i.concat([buffer, Buffer$i.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); + 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; + } } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); + if (s[0] === 0) { + if (s[1] & 0x80) { + s = s.slice(1); + } else { + // Leading zeroes + return false; + } } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); + + this.r = new BN$3(r); + this.s = new BN$3(s); + this.recoveryParam = null; + + return true; + }; + + function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; } - writeVector(witness); - return buffer; + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, + + Signature$3.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$5.encode(res, enc); + }; + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); + }; + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); + }; + + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; + + EC$1.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(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + + EC$1.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$1.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$2(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', }); - } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; + + // Number of bytes to generate + var ns1 = this.n.sub(new BN$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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; } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); + + return new Signature$2({ r: r, s: s, recoveryParam: recoveryParam }); } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); - } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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; } - return c[inputIndex]; - } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); + + // 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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); + + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; + + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; + + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; + + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; + + var key = KeyPair$2; + + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.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$1(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes$1(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; - if ( - !isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + + cachedProperty(Signature$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + var signature = Signature$1; + + var hash = hash$2; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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; } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + + var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0$1.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = browser$2; + + const ONE1 = Buffer$l.alloc(1, 1); + const ZERO1 = Buffer$l.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$l.alloc(32, 0); + let v = Buffer$l.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; + } + + return T } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + + var rfc6979 = deterministicGenerateK$1; + + const BN = bn$1.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer$l.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); + + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) - throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', - ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; + + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false + + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true } - return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', - }; + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); - } + + function __isPointCompressed (p) { + return p[0] !== 0x04 } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G } - function range$1(n) { - return [...Array(n).keys()]; + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 } - var transaction_builder = {}; + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } - var classify$1 = {}; + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } - var multisig$1 = {}; + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) - var input$b = {}; + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); - } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); - } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - var output$e = {}; + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - var nulldata = {}; + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + const compressed = assumeCompression(__compressed, p); + + return getEncoded(pp, compressed) } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - var pubkey = {}; + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - var input$9 = {}; + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; - var output$b = {}; + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG - ); + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null + + return getEncoded(qq, compressed) } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - var pubkeyhash = {}; + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null - var input$7 = {}; + return dt + } - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; - var output$9 = {}; + function sign$1 (hash, x) { + return __sign(hash, x) + } - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG - ); + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) - var scripthash = {}; + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); - var input$5 = {}; + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); - var output$7 = {}; + if (Q.isInfinity()) return false - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 - ); + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer$l.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; - }; - var output$6 = {}; + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; + + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign: sign$1, + signWithEntropy, + verify }; - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), - ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) - ); - } - // match types - if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; - } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } }; - var output$5 = {}; + // TODO: deprecate + types$c.Null = types$c.Nil; - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL - ); + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; - }; - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; + var native$1 = types$c; - var witnesscommitment = {}; + var native = native$1; - var output$3 = {}; + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer$i.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$i.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); + } } - output$3.decode = decode; - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' - var witnesspubkeyhash = {}; + return type !== undefined ? type : '' + } - var input$3 = {}; + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; - } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); - var witnessscripthash = {}; + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } - var input$1 = {}; + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; - if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; - } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) } - classify$1.witness = classifyWitness; - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$1; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); } + + captureStackTrace(e); + return e } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; - } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; + + var errors = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors; + + function _Buffer (value) { + return isBuffer(value) } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); - } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; - } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; - } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; - } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; - } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$i.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); - } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); - } - build() { - return this.__build(false); - } - buildIncomplete() { - return this.__build(true); - } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), - ); + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str + }; + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) } - prevOutType = expanded.type; } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); + + return true } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, - ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; - } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); - }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } } + + return true } - return tx; - } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); - }); - }); - } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; - } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); + _object.toJSON = function () { return tfJSON(type) }; + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } }) - ); - } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false } - return false; - }); - }); - } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; - } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; - } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; + }) } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; + _quacksLike.toJSON = function () { return type }; + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); - return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, - }; + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected } + _value.toJSON = function () { return expected }; + + return _value } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; + }; + + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; + + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) + } + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce$b(compile(type), value, strict) + } + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); + + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$l(compressed ? 34 : 33); + + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) + } + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw + }; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$3 = crypto$5; + const bs58check$3 = bs58check$5; + const ecc$6 = js; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); + } + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; + get depth() { + return this.__DEPTH; } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; + get index() { + return this.__INDEX; } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); - return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, - }; + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; } - } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, - }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); + get privateKey() { + return this.__D; } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + get identifier() { + return crypto$3.hash160(this.publicKey); } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + get fingerprint() { + return this.identifier.slice(0, 4); } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); + get compressed() { + return true; } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$l.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$l.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$3.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$l.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); - } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, - ); + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); } - } + return hd; } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, - ); - } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; - } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', - ); + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; + + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; + + var address$1 = {}; + + var networks$3 = {}; + + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + + var payments$4 = {}; + + var embed = {}; + + var script$1 = {}; + + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', - ); + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$l.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, - ); - // updates inline - Object.assign(input, prepared); - } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { + return ( + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); + } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$2 = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } + + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); + } + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature + } + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$l.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); + return x; + } + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$l.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$l.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$l.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; + + return size } - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; - const address = address$1; - src$1.address = address; - const crypto = crypto$1; - var crypto_1 = src$1.crypto = crypto; - const ECPair = ecpair; - src$1.ECPair = ECPair; - const networks = networks$3; - src$1.networks = networks; - const payments = payments$4; - src$1.payments = payments; - const script = script$1; - src$1.script = script; - var block_1 = block; - src$1.Block = block_1.Block; - var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$1.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; - var re$5 = {exports: {}}; + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH + number = buffer.readUInt32LE(offset + 1); + size = 5; + } + + return { + opcode: opcode, + number: number, + size: size + } + } + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c }; - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + var OPS$8 = require$$7; - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + + var map_1 = map; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = js; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); + } + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; + } + function chunksIsBuffer(buf) { + return isBuffer(buf); + } + function chunksIsArray(buf) { + return types.Array(buf); + } + function singleChunkIsBuffer(buf) { + return isBuffer(buf); + } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$l.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; + } + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; + } + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); + } + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$l.from(chunkStr, 'hex'); + }), + ); + } + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); + } + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); + } + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; + } + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); + } + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; + } + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + } + return Object.assign(o, a); + } + embed.p2data = p2data; + + var p2ms$3 = {}; + + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = js; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); } + } + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + var p2pk$3 = {}; - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = js; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); } + } + return Object.assign(o, a); + } + p2pk$3.p2pk = p2pk$2; + var p2pkh$4 = {}; + var crypto$2 = {}; + Object.defineProperty(crypto$2, '__esModule', { value: true }); + const createHash = browser$3; + function ripemd160$1(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } + crypto$2.ripemd160 = ripemd160$1; + function sha1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$2.sha1 = sha1; + function sha256$1(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$2.sha256 = sha256$1; + function hash160$1(buffer) { + return ripemd160$1(sha256$1(buffer)); } + crypto$2.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$1(sha256$1(buffer)); + } + crypto$2.hash256 = hash256$1; - function drainQueue() { - if (draining) { - return; + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$2; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = js; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser$2 = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop$2() {} + p2pkh$4.p2pkh = p2pkh$3; - var on = noop$2; - var addListener = noop$2; - var once$2 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; + var p2sh$1 = {}; - function binding(name) { - throw new Error('process.binding is not supported'); + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$2; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); } - - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; + } + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); + return { + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); } } - return [seconds,nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; + return Object.assign(o, a); } + p2sh$1.p2sh = p2sh; - var process = { - nextTick: nextTick, - title: title, - browser: browser$2, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once$2, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - const debug$4 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$4; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. + var p2wpkh$2 = {}; - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); - createToken('FULL', `^${src[t.FULLPLAIN]}$`); + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk + } - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + prefix = prefix.toLowerCase(); - createToken('GTLT', '((?:<|>)?=?)'); + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); + return result + } - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + throw new Error(res) + } - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; - if (anum && bnum) { - a = +a; - b = +b; + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + return result + } - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers - }; + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } - const debug$3 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); + throw new Error(res) + } - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) - } + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res - debug$3('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; + throw new Error(res) + } - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$2; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = js; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$l.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$l.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); } + return Object.assign(o, a); + } + p2wpkh$2.p2wpkh = p2wpkh$1; - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } + var p2wsh$1 = {}; - toString () { - return this.version + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$2; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = js; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$l.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + function chunkHasUncompressedPubkey(chunk) { + if ( + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; } - - compare (other) { - debug$3('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) + } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$l.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$3('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - } while (++i) + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; - default: - throw new Error(`invalid increment argument: ${release}`) + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$l.from(data), + }; + } + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); + } + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); + } + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } } - this.format(); - this.raw = this.version; - return this } + throw new Error(address + ' has no matching Script'); } + address$1.toOutputScript = toOutputScript; - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } + var ecpair = {}; - if (typeof version !== 'string') { - return null - } + var browser$1 = {exports: {}}; - if (version.length > MAX_LENGTH) { - return null - } + // limit of Crypto.getRandomValues() + // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + var MAX_BYTES = 65536; - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } + // Node supports requesting up to this number of bytes + // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 + var MAX_UINT32 = 4294967295; - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; + function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') + } - var parse_1 = parse$5; + var Buffer$1 = safeBuffer.exports.Buffer; + var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; + if (crypto$1 && crypto$1.getRandomValues) { + browser$1.exports = randomBytes$1; + } else { + browser$1.exports = oldBrowser; + } - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; + function randomBytes$1 (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') - const SemVer$c = semver$1; + var bytes = Buffer$1.allocUnsafe(size); - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); + } + } else { + crypto$1.getRandomValues(bytes); + } } - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null + if (typeof cb === 'function') { + return nextTick(function () { + cb(null, bytes); + }) } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - const parse$2 = parse_1; - const eq$1 = eq_1; + return bytes + } - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = js; + const randomBytes = browser$1.exports; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$l.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); } + return sig; } - return defaultResult // may be undefined } - }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; + var block = {}; - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; + var bufferutils = {}; - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1 = prerelease; + var Buffer = safeBuffer.exports.Buffer; - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1 = compareBuild$2; + function encode$b (number, buffer, offset) { + checkUInt53$1(number); - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; + } - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; + return buffer + } - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; + function decode$a (buffer, offset) { + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; + var first = buffer.readUInt8(offset); - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) - case '': - case '=': - case '==': - return eq(a, b, loose) + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) - case '!=': - return neq(a, b, loose) + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); - case '>': - return gt$2(a, b, loose) + return number + } + } - case '>=': - return gte$1(a, b, loose) + function encodingLength$1 (number) { + checkUInt53$1(number); - case '<': - return lt$1(a, b, loose) + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } - case '<=': - return lte$1(a, b, loose) + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; - default: - throw new TypeError(`Invalid operator: ${op}`) + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; } - }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$l.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; } - - if (typeof version === 'number') { - version = String(version); + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; } - - if (typeof version !== 'string') { - return null + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; } + } + bufferutils.BufferReader = BufferReader$1; - options = options || {}; + var transaction = {}; - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$2; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$l.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$l.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; } - - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1 = coerce; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; } + return true; } - - return self - } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); } - - if (prev) { - prev.next = next; + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); } - - if (node === this.head) { - this.head = next; + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); } - if (node === this.tail) { - this.tail = prev; + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return + virtualSize() { + return Math.ceil(this.weight() / 4); } - - if (node.list) { - node.list.removeNode(node); + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; } - - this.head = node; - if (!this.tail) { - this.tail = node; + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$l.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$l.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); } - - if (node.list) { - node.list.removeNode(node); + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); } - - this.tail = node; - if (!this.head) { - this.head = node; + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); } - this.length++; - }; - - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); } - return this.length - }; - - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; } - return this.length - }; + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res - }; + var length = values.length; + var results = values.concat(); - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } + while (length > 1) { + var j = 0; - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res - }; + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$l.concat([left, right]); - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; + results[j] = digestFn(data); + } - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; + length = j; } - }; - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } + return results[0] }; - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$2; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; } - }; - - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; } - return res - }; - - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; + static fromHex(hex) { + return Block.fromBuffer(Buffer$l.from(hex, 'hex')); } - return res - }; - - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$l.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; } - - return acc - }; - - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$l && result.length === 32)) return null; + return result; } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$l && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; } - - return acc - }; - - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; + hasWitness() { + return anyTxHasWitness(this.transactions); } - return arr - }; - - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; } - return arr - }; - - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); } - from = from || 0; - if (from < 0) { - from += this.length; + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); } - if (from < 0) { - from = 0; + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; } - if (to > this.length) { - to = this.length; + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); } - return ret - }; - - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; } - from = from || 0; - if (from < 0) { - from += this.length; + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; } - if (from < 0) { - from = 0; + } + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); + } + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); + } + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); } - if (to > this.length) { - to = this.length; + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); } - return ret - }; + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$l.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); + } + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); + } + globalXpub$1.canAddToArray = canAddToArray$1; - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } + var unsignedTx$1 = {}; - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; + } + unsignedTx$1.encode = encode$9; - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } + var finalScriptSig$1 = {}; - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); } + return keyVal.value; + } + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; + } + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); + } + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; + } + finalScriptSig$1.canAdd = canAdd$5; - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; + var finalScriptWitness$1 = {}; - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); } - this.head = tail; - this.tail = head; - return this - }; + return keyVal.value; + } + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; + } + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); + } + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); + } + finalScriptWitness$1.canAdd = canAdd$4; - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); + var nonWitnessUtxo$1 = {}; - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); } - - self.length++; - - return inserted + return keyVal.value; } - - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; - } - self.length++; + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; } - - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); } + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } - - this.list = list; - this.value = value; + var partialSig$1 = {}; - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); } - - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; } + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$l.concat([head, pSig.pubkey]), + value: pSig.signature, + }; + } + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); + } + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + var porCommitment$1 = {}; - const naiveLength = () => 1; + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer$l.from(data, 'utf8'), + }; + } + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; + var sighashType$1 = {}; - if (!options) - options = {}; + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); + } + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$l.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; + } + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; + } + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; + } + sighashType$1.canAdd = canAdd$1; - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; + var witnessUtxo$1 = {}; - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } + var tools = {}; - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') + var varint$1 = {}; - this[MAX] = mL || Infinity; - trim(this); + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); + } + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); } - get max () { - return this[MAX] + return buffer; + } + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; } + return buffer; + } + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$l.from([0])); + return Buffer$l.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$l.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA; - trim(this); + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); } - get maxAge () { - return this[MAX_AGE] + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; + var bip32Derivation$1 = {}; - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); } - } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list + return data; } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) + function encode(data) { + const head = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$l.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; } - - dumpLru () { - return this[LRU_LIST] + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; + } + bip32Derivation$1.makeConverter = makeConverter$2; - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; + var checkPubkey$1 = {}; - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true - } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) - } - - get (key) { - return get$1(this, key, true) - } - - peek (key) { - return get$1(this, key, false) + return pubkey; } + } + checkPubkey$1.makeChecker = makeChecker; - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null + var redeemScript$1 = {}; - del(this, node); - return node.value + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; } - - del (key) { - del(this, this[CACHE].get(key)); + function encode(data) { + const key = Buffer$l.from([TYPE_BYTE]); + return { + key, + value: data, + }; } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } - } - } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; } + return { + decode, + encode, + check, + expected, + canAdd, + }; } + redeemScript$1.makeConverter = makeConverter$1; - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); - } - } - return hit.value - } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; + var witnessScript$1 = {}; - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); } + return keyVal.value; } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); + function encode(data) { + const key = Buffer$l.from([TYPE_BYTE]); + return { + key, + value: data, + }; } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); } + return { + decode, + encode, + check, + expected, + canAdd, + }; } + witnessScript$1.makeConverter = makeConverter; - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self); + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } - } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this - } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } - } - } - } - - this.format(); + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; } - - toString () { - return this.range + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$2('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$2('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); } - return false + outputKeyVals.push(output); } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$2 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); - - testComparator = remainingComparators.pop(); + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$l.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$2('comp', comp, options); - comp = replaceCarets(comp, options); - debug$2('caret', comp); - comp = replaceTildes(comp, options); - debug$2('tildes', comp); - comp = replaceXRanges(comp, options); - debug$2('xrange', comp); - comp = replaceStars(comp, options); - debug$2('stars', comp); - return comp - }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$2('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; - } - - debug$2('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$2('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$2('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$2('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); } - } else { - debug$2('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); } } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - debug$2('caret return', ret); - return ret - }) - }; + var toBuffer = {}; - const replaceXRanges = (comp, options) => { - debug$2('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$l.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$l.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$l.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); + } + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$2('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); - if (gtlt === '=' && anyX) { - gtlt = ''; + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); + } + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; + } + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; + } - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; + var utils = {}; - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; + } + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; + } + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } + } + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; + } + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); } else { - m = +m + 1; + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; } } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; } + }; + } + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); + } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; + } + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); - debug$2('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$2('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; - - const replaceGTE0 = (comp, options) => { - debug$2('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$l.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer$l.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; } - - return (`${from} ${to}`).trim() - }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$2(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; } } - - // Version has a -pre, but it's not one of the ones we like. - return false + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); } + } + psbt.Psbt = Psbt$1; - return true + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$2; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } - } - - debug$1('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } - - debug$1('comp', this); + static fromBase64(data, opts = {}) { + const buffer = Buffer$l.from(data, 'base64'); + return this.fromBuffer(buffer, opts); } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); + static fromHex(data, opts = {}) { + const buffer = Buffer$l.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; } - - toString () { - return this.value + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; } - - test (version) { - debug$1('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); } - - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); } - - return cmp(version, this.operator, this.semver, this.options) + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); } - } - - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug$1 = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; - - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); } - return range.test(version) - }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); } - }); - return max - }; - var maxSatisfying_1 = maxSatisfying; - - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null + return results.every(res => res === true); } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } } - }); - return min - }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null - }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } } - return true - }; - - var outside_1 = outside$2; - - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; - - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; - - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) - }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } - prev = null; - min = null; } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); } - return true - }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false - } - - return true + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false + return this; + } + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; - - var subset_1 = subset; - - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$i.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$i.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer$i.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - var readable = {exports: {}}; - - var stream = require$$0__default$2["default"]; - - function ownKeys$1(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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$2(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - var _require$2 = require$$0__default$1["default"], - Buffer$e = _require$2.Buffer; - - var _require2 = require$$1__default["default"], - inspect = _require2.inspect; - - var custom = inspect && inspect.custom || 'inspect'; - - function copyBuffer(src, target, offset) { - Buffer$e.prototype.copy.call(src, target, offset); } - - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$e.alloc(0); - var ret = Buffer$e.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$e.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread$1({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); - } else { - nextTick(emitCloseNT, _this); + if (whitelist.indexOf(action) === -1) { + throws = true; } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); - } else { - nextTick(emitCloseNT, _this); + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); } }); - - return this; } - - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); - } - - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); } - - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); } - - 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 checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); } } - - function emitErrorNT(self, err) { - self.emit('error', err); + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); } - - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; } - - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - - var errors = {}; - - const codes = {}; - - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); } else { - return message(arg1, arg2, arg3) + finalScriptWitness = witnessStackToScriptWitness(payment.witness); } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; } } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; + return { + finalScriptSig, + finalScriptWitness, + }; } - - // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; } else { - return `of ${thing} ${String(expected)}`; - } - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; + throw new Error('Need a Utxo input item for signing'); } - - if (start + search.length > str.length) { - return false; + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); } else { - return str.indexOf(search, start) !== -1; + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); } + return { + script: meaningfulScript, + sighashType, + hash, + }; } - - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; } - - msg += `. Received type ${typeof actual}`; - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - - errors.codes = codes; - - var ERR_INVALID_OPT_VALUE = errors.codes.ERR_INVALID_OPT_VALUE; - - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + return payment; } - - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); } - - var state = { - getHighWaterMark: getHighWaterMark$2 - }; - - /** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - - var node = require$$1__default["default"].deprecate; - - var _stream_writable = Writable$1; - // there will be only 2 of these for each stream - - - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; } - /* */ - - /**/ - - - var Duplex$3; - /**/ - - Writable$1.WritableState = WritableState; - /**/ - - var internalUtil = { - deprecate: node - }; - /**/ - - /**/ - - var Stream$1 = stream; - /**/ - - - var Buffer$d = require$$0__default$1["default"].Buffer; - - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$d.from(chunk); - } - - function _isUint8Array$1(obj) { - return Buffer$d.isBuffer(obj) || obj instanceof OurUint8Array$1; - } - - var destroyImpl$1 = destroy_1; - - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; - - var _require$codes$3 = errors.codes, - ERR_INVALID_ARG_TYPE$2 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - - inherits$f.exports(Writable$1, Stream$1); - - function nop() {} - - function WritableState(options, stream, isDuplex) { - Duplex$3 = Duplex$3 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); } - - return out; - }; - - (function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. - - - var realHasInstance; - - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$1, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$1) return false; - return object && object._writableState instanceof WritableState; + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); } + return node; }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; + return signers; } - - function Writable$1(options) { - Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$3; - if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream$1.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. - - - Writable$1.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; - - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. - - - function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$2('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } - - return true; + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); } - - Writable$1.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array$1(chunk); - - if (isBuf && !Buffer$d.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; } - return ret; - }; - - Writable$1.prototype.cork = function () { - this._writableState.corked++; - }; - - Writable$1.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + function readVarSlice() { + return readSlice(readVarInt()); } - }; - - Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - Object.defineProperty(Writable$1.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; } - }); - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$d.from(chunk, encoding); + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; } - - return chunk; + return text; } - - Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$l.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); } - - state.bufferedRequestCount += 1; + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + throw new Error("Can't find pubkey in input without Utxo data"); } - - return ret; } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); } } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; + var transaction_builder = {}; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + var classify$1 = {}; - if (sync) { - nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } + var multisig$1 = {}; + + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); } + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; + }; - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. + var output$e = {}; + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; + }; - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; + var nulldata = {}; - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; + }; + const output$c = { check: check$b }; + nulldata.output = output$c; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; + var pubkey = {}; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } + var input$9 = {}; - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; + }; - state.pendingcb++; - state.lastBufferedRequest = null; + var output$b = {}; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; + }; - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; - if (state.writing) { - break; - } - } + var pubkeyhash = {}; - if (entry === null) state.lastBufferedRequest = null; - } + var input$7 = {}; - state.bufferedRequest = entry; - state.bufferProcessing = false; + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; + }; - Writable$1.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + var output$9 = {}; + + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; }; - Writable$1.prototype._writev = null; + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; - Writable$1.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + var scripthash = {}; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + var input$5 = {}; - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + var output$7 = {}; - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; + var output$6 = {}; - if (!state.ending) endWritable(this, state, cb); - return this; + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); + } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; }; - Object.defineProperty(Writable$1.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); } - }); + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; + } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; - if (err) { - errorOrDestroy$1(stream, err); - } + var witnesscommitment = {}; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); - } + var output$3 = {}; - function prefinish$1(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$l.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); + } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$l.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); } + output$3.decode = decode; - function finishMaybe(stream, state) { - var need = needFinish(state); + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; - if (need) { - prefinish$1(stream, state); + var witnesspubkeyhash = {}; - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + var input$3 = {}; - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; - return need; + var witnessscripthash = {}; + + var input$1 = {}; + + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; + + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$2; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); + } + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); + } + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, + }); + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; + } + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; + } + this.__USE_LOW_R = setting; + return setting; } - - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; - } - - Object.defineProperty(Writable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; + this.__TX.locktime = locktime; } - }); - Writable$1.prototype.destroy = destroyImpl$1.destroy; - Writable$1.prototype._undestroy = destroyImpl$1.undestroy; - - Writable$1.prototype._destroy = function (err, cb) { - cb(err); - }; - - /**/ - - var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; } - - return keys; - }; - /**/ - - - var _stream_duplex = Duplex$2; - - var Readable$1 = _stream_readable; - - var Writable = _stream_writable; - - inherits$f.exports(Duplex$2, Readable$1); - - { - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); } - } - - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$1.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); } + return this.__TX.addOutput(scriptPubKey, value); } - } - - Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; + build() { + return this.__build(false); } - }); - Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + buildIncomplete() { + return this.__build(true); } - }); - Object.defineProperty(Duplex$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); } - }); // the no-half-open enforcer - - function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - nextTick(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - Object.defineProperty(Duplex$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - - var string_decoder = {}; - - /**/ - - var Buffer$c = safeBuffer.exports.Buffer; - /**/ - - var isEncoding = Buffer$c.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; + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } + prevOutType = expanded.type; + } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; } - }; - - 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; + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } } + return tx; } - } - // 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$c.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. - string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(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; + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer$c.allocUnsafe(nb); - } - - StringDecoder$2.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; + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; - }; - - StringDecoder$2.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.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); + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); } - 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; + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; + } + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; } - 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; + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; } - 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'; + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; } } - } - - // 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); - 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); + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; } - 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); - } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); } - return r; + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; } - - // 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; + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); } - - 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]; + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; + } } - 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) : ''; + return { type }; } - - var ERR_STREAM_PREMATURE_CLOSE = errors.codes.ERR_STREAM_PREMATURE_CLOSE; - - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, + }); + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - callback.apply(this, args); - }; - } - - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; - } - - var endOfStream = eos$1; - - var _Object$setPrototypeO; - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var finished = endOfStream; - - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); - - function createIterResult(value, done) { - return { - value: value, - done: done - }; - } - - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - } - - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } - - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], }; } - - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); } - - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty$1(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty$1(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty$1(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty$1(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty$1(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty$1(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); + signatures = signatures.filter(x => x); } - - iterator[kError] = err; - return; + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; - - var async_iterator = createReadableStreamAsyncIterator$1; - - 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); }); }; } - - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else 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; } - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var ERR_INVALID_ARG_TYPE$1 = errors.codes.ERR_INVALID_ARG_TYPE; - - function from$1(Readable, iterable, opts) { - var iterator; - - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE$1('iterable', ['Iterable'], iterable); - - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. - - var reading = false; - - readable._read = function () { - if (!reading) { - reading = true; - next(); + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); } - }; - - function next() { - return _next2.apply(this, arguments); - } - - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; - - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); } - - return readable; - } - - var from_1 = from$1; - - var _stream_readable = Readable; - /**/ - - var Duplex$1; - /**/ - - Readable.ReadableState = ReadableState; - /**/ - - EventEmitter__default["default"].EventEmitter; - - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ - - /**/ - - - var Stream = stream; - /**/ - - - var Buffer$b = require$$0__default$1["default"].Buffer; - - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - - function _uint8ArrayToBuffer(chunk) { - return Buffer$b.from(chunk); - } - - function _isUint8Array(obj) { - return Buffer$b.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ - - - var debugUtil = require$$1__default["default"]; - - var debug; - - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); - } else { - debug = function debug() {}; - } - /**/ - - - var BufferList = buffer_list; - - var destroyImpl = destroy_1; - - var _require = state, - getHighWaterMark = _require.getHighWaterMark; - - var _require$codes$2 = errors.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - - var StringDecoder$1; - var createReadableStreamAsyncIterator; - var from; - - inherits$f.exports(Readable, Stream); - - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - - function ReadableState(options, stream, isDuplex) { - Duplex$1 = Duplex$1 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); } - - function Readable(options) { - Duplex$1 = Duplex$1 || _stream_duplex; - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$1; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); } - - Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; - - Readable.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - - - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer$b.from(chunk, encoding); - encoding = ''; + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() - - - Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$b.prototype) { - chunk = _uint8ArrayToBuffer(chunk); + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; + } + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); } - - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); } - - maybeReadMore(stream, state); - } - - function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + if (keyPair === undefined) { + throw new Error('sign requires keypair'); } - - return er; - } - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. - - - Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB - - - var MAX_HWM = 0x40000000; - - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$2; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough + var re$5 = {exports: {}}; - if (!state.ended) { - state.needReadable = true; - return 0; - } + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; - return state.length; - } // you can override either this method, or the async _read(n) below. + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + var debug_1 = debug$3; - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - if (state.length === 0) state.needReadable = true; // call internal read method + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. - this._read(state.highWaterMark); + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + // ## Main Version + // Three dot-separated numeric identifiers. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); - if (nOrig !== n && state.ended) endReadable(this); - } + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); - if (ret !== null) this.emit('data', ret); - return ret; - }; + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. - function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - if (state.decoder) { - var chunk = state.decoder.end(); + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. - state.ended = true; + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. - function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_, stream); - } - } + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); - function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); + createToken('FULL', `^${src[t.FULLPLAIN]}$`); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. + createToken('GTLT', '((?:<|>)?=?)'); + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } - } + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); - function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); - Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - case 1: - state.pipes = [state.pipes, dest]; - break; + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); - default: - state.pipes.push(dest); - break; - } + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + if (anum && bnum) { + a = +a; + b = +b; } - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; - dest.once('close', onclose); + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } - dest.once('finish', onfinish); + this.raw = version; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } - dest.emit('pipe', src); // start the flow if it hasn't been started already. + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } - return dest; - }; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); + } - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - }; - } + return this.version + } - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + toString () { + return this.version + } - if (state.pipesCount === 0) return this; // just one destination. most common case. + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); + } - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + if (other.version === this.version) { + return 0 + } - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + return this.compareMain(other) || this.comparePre(other) + } + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - return this; - } // try to find the right one. - + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } - Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - nextTick(nReadingNextTick, this); - } + default: + throw new Error(`invalid increment argument: ${release}`) } + this.format(); + this.raw = this.version; + return this } + } - return res; - }; + var semver$1 = SemVer$e; - Readable.prototype.addListener = Readable.prototype.on; + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; - Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); + if (version instanceof SemVer$d) { + return version } - return res; - }; - - Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); + if (typeof version !== 'string') { + return null } - return res; - }; + if (version.length > MAX_LENGTH) { + return null + } - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); + try { + return new SemVer$d(version, options) + } catch (er) { + return null } - } + }; - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + var parse_1 = parse$5; + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; - Readable.prototype.resume = function () { - var state = this._readableState; + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + const SemVer$c = semver$1; - state.flowing = !state.readableListening; - resume(this, state); + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; } - state.paused = false; - return this; + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } }; + var inc_1 = inc; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } - } + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - function resume_(stream, state) { - debug('resume', state.reading); + var compare_1 = compare$a; - if (!state.reading) { - stream.read(0); + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined } + }; + var diff_1 = diff; - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; - this._readableState.paused = true; - return this; + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null }; + var prerelease_1 = prerelease; - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; - Readable.prototype.wrap = function (stream) { - var _this = this; + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; - var ret = _this.push(chunk); + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + case '': + case '=': + case '==': + return eq(a, b, loose) - this._read = function (n) { - debug('wrapped _read', n); + case '!=': + return neq(a, b, loose) - if (paused) { - paused = false; - stream.resume(); - } - }; + case '>': + return gt$2(a, b, loose) - return this; - }; + case '>=': + return gte$1(a, b, loose) - if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } + case '<': + return lt$1(a, b, loose) - return createReadableStreamAsyncIterator(this); - }; - } + case '<=': + return lte$1(a, b, loose) - Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; + default: + throw new TypeError(`Invalid operator: ${op}`) } - }); - Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version } - }); // exposed for testing purposes only. - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; + if (typeof version === 'number') { + version = String(version); } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); + if (typeof version !== 'string') { + return null } - return ret; - } - function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); + options = options || {}; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; } - } - function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + if (match === null) + return null - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; + var yallist = Yallist$1; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); } - } - if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = from_1; + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); } + } - return from(Readable, iterable, opts); - }; + return self } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') } - return -1; - } + var next = node.next; + var prev = node.prev; - var _stream_transform = Transform$3; + if (next) { + next.prev = prev; + } - var _require$codes$1 = errors.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + if (prev) { + prev.next = next; + } - var Duplex = _stream_duplex; + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } - inherits$f.exports(Transform$3, Duplex); + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + return next + }; - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + if (node.list) { + node.list.removeNode(node); + } - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; } - } - function Transform$3(options) { - if (!(this instanceof Transform$3)) return new Transform$3(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } - this._readableState.sync = false; + if (node.list) { + node.list.removeNode(node); + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; - this.on('prefinish', prefinish); - } + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; - function prefinish() { - var _this = this; + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; } else { - done(this, null, null); + this.head = null; } - } + this.length--; + return res + }; - Transform$3.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; - Transform$3.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } }; - Transform$3.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. + if (i === n && walker !== null) { + return walker.value + } + }; + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; - Transform$3.prototype._read = function (n) { - var ts = this._transformState; + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + throw new TypeError('Reduce of empty list with no initial value') } - }; - Transform$3.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc }; - function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } - var _stream_passthrough = PassThrough; + return acc + }; - var Transform$2 = _stream_transform; + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; - inherits$f.exports(PassThrough, Transform$2); + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$2.call(this, options); - } + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret }; - var eos; + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } - var _require$codes = errors.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; - } + self.length++; - function call(fn) { - fn(); + return inserted } - function pipe(from, to) { - return from.pipe(to); + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; } - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + this.list = list; + this.value = value; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; } - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } } - var pipeline_1 = pipeline; - - (function (module, exports) { - var Stream = require$$0__default$2["default"]; - { - exports = module.exports = _stream_readable; - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - } - }(readable, readable.exports)); + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} - var Buffer$a = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$a = inherits$f.exports; + // A linked list to keep track of recently-used-ness + const Yallist = yallist; - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$a.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); - function HashBase$2 (blockSize) { - Transform$1.call(this); + const naiveLength = () => 1; - this._block = Buffer$a.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; - this._finalized = false; - } + if (!options) + options = {}; - inherits$a(HashBase$2, Transform$1); + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); } - callback(error); - }; + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] } - callback(error); - }; + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$a.isBuffer(data)) data = Buffer$a.from(data, encoding); + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } - return this - }; + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } - return digest - }; + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } - var hashBase = HashBase$2; + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } - var Buffer$9 = require$$0__default$1["default"].Buffer; - var inherits$9 = inherits$f.exports; - var HashBase$1 = hashBase; + dumpLru () { + return this[LRU_LIST] + } - var ARRAY16$1 = new Array(16); + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; - var zl = [ - 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 - ]; + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') - var zr = [ - 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 - ]; + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); - var sl = [ - 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 - ]; + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } - var sr = [ - 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 - ]; + const node = this[CACHE].get(key); + const item = node.value; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } - function RIPEMD160$1 () { - HashBase$1.call(this, 64); + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } + const hit = new Entry(key, value, len, now, maxAge); - inherits$9(RIPEMD160$1, HashBase$1); + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); - RIPEMD160$1.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + return false + } - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } + get (key) { + return get$1(this, key, true) + } - al = el; - el = dl; - dl = rotl$1(cl, 10); - cl = bl; - bl = tl; + peek (key) { + return get$1(this, key, false) + } - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value } - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; + del (key) { + del(this, this[CACHE].get(key)); + } - RIPEMD160$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } + } - // produce result - var buffer = Buffer$9.alloc ? Buffer$9.alloc(20) : new Buffer$9(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } } - var ripemd160$1 = RIPEMD160$1; + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; - var sha_js = {exports: {}}; + var lruCache = LRUCache; - var Buffer$8 = safeBuffer.exports.Buffer; + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$8.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$8.from(data, enc); - } + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - accum += remainder; - offset += remainder; - - if ((accum % blockSize) === 0) { - this._update(block); + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } } - } - - this._len += length; - return this - }; - - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - this._block[rem] = 0x80; + this.format(); + } - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); + toString () { + return this.range } - var bits = this._len * 8; + parseRange (range) { + range = range.trim(); - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - this._update(this._block); - var hash = this._hash(); + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - return enc ? hash.toString(enc) : hash - }; + // normalize spaces + range = range.split(/\s+/).join(' '); - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // At this point, the range is completely trimmed and + // ready to be split into comparators. - var hash = Hash$7; + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); - var inherits$8 = inherits$f.exports; - var Hash$6 = hash; - var Buffer$7 = safeBuffer.exports.Buffer; + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } - var W$5 = new Array(80); + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } - function Sha () { - this.init(); - this._w = W$5; + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } - Hash$6.call(this, 64, 56); + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } } + var range = Range$a; - inherits$8(Sha, Hash$6); + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; - return this - }; + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + testComparator = remainingComparators.pop(); + } - Sha.prototype._update = function (M) { - var W = this._w; + return result + }; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp + }; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$1('tilde return', ret); + return ret + }) }; - Sha.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(20); + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; - return H + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } + + debug$1('caret return', ret); + return ret + }) }; - var sha$2 = Sha; + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; - var inherits$7 = inherits$f.exports; - var Hash$5 = hash; - var Buffer$6 = safeBuffer.exports.Buffer; + if (gtlt === '=' && anyX) { + gtlt = ''; + } - var K$2 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; - var W$4 = new Array(80); + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; - function Sha1 () { - this.init(); - this._w = W$4; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } - Hash$5.call(this, 64, 56); - } + if (gtlt === '<') + pr = '-0'; - inherits$7(Sha1, Hash$5); + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + debug$1('xRange return', ret); - return this + return ret + }) }; - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } - Sha1.prototype._update = function (M) { - var W = this._w; + return (`${from} ${to}`).trim() + }; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + // Version has a -pre, but it's not one of the ones we like. + return false } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + return true }; - Sha1.prototype._hash = function () { - var H = Buffer$6.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); - return H - }; + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } + } - var sha1 = Sha1; + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } - var inherits$6 = inherits$f.exports; - var Hash$4 = hash; - var Buffer$5 = safeBuffer.exports.Buffer; + debug('comp', this); + } - var K$1 = [ - 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 - ]; + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); - var W$3 = new Array(64); + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } - function Sha256$1 () { - this.init(); + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; + } - this._w = W$3; // new Array(64) + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } - Hash$4.call(this, 64, 56); - } + toString () { + return this.value + } - inherits$6(Sha256$1, Hash$4); + test (version) { + debug('Comparator.test', version, this.options.loose); - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + if (this.semver === ANY$2 || version === ANY$2) { + return true + } - return this - }; + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + return cmp(version, this.operator, this.semver, this.options) + } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - Sha256$1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + var comparator = Comparator$2; - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; + return range.test(version) }; + var satisfies_1 = satisfies$3; - Sha256$1.prototype._hash = function () { - var H = Buffer$5.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + const Range$7 = range; - return H - }; + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - var sha256$1 = Sha256$1; + var toComparators_1 = toComparators; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + const SemVer$3 = semver$1; + const Range$6 = range; - var inherits$5 = inherits$f.exports; - var Sha256 = sha256$1; - var Hash$3 = hash; - var Buffer$4 = safeBuffer.exports.Buffer; + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; - var W$2 = new Array(64); + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; - function Sha224 () { - this.init(); + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; - this._w = W$2; // new Array(64) + const minVersion = (range, loose) => { + range = new Range$4(range, loose); - Hash$3.call(this, 64, 56); - } + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } - inherits$5(Sha224, Sha256); + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; - return this - }; + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } - Sha224.prototype._hash = function () { - var H = Buffer$4.allocUnsafe(28); + if (minver && range.test(minver)) { + return minver + } - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + return null + }; + var minVersion_1 = minVersion; - return H + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } }; + var valid = validRange; - var sha224 = Sha224; + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; - var inherits$4 = inherits$f.exports; - var Hash$2 = hash; - var Buffer$3 = safeBuffer.exports.Buffer; + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); - 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 - ]; + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } - var W$1 = new Array(160); + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } - function Sha512 () { - this.init(); - this._w = W$1; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - Hash$2.call(this, 128, 112); - } + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; - inherits$4(Sha512, Hash$2); + let high = null; + let low = null; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } - return this + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true }; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } + var outside_1 = outside$2; - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; - Sha512.prototype._update = function (M) { - var W = this._w; + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; - - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + return true + }; - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true - W[i] = Wih; - W[i + 1] = Wil; + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + if (eqSet.size > 1) + return null - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j]; - var Kil = K[j + 1]; + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + if (lt && !satisfies(eq, String(lt), options)) + return null - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; + return true } - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; - - Sha512.prototype._hash = function () { - var H = Buffer$3.allocUnsafe(64); + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; - - var sha512 = Sha512; - - var inherits$3 = inherits$f.exports; - var SHA512 = sha512; - var Hash$1 = hash; - var Buffer$2 = safeBuffer.exports.Buffer; - - var W = new Array(160); - - function Sha384 () { - this.init(); - this._w = W; - - Hash$1.call(this, 128, 112); - } - - inherits$3(Sha384, SHA512); + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false - return this + return true }; - Sha384.prototype._hash = function () { - var H = Buffer$2.allocUnsafe(48); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - var sha384 = Sha384; - - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + var subset_1 = subset; - return new Algorithm() + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, }; - exports$1.sha = sha$2; - exports$1.sha1 = sha1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$1; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$l.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$l.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$l.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); - var sha$1 = sha_js.exports; + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; function hashPublicKey(buffer) { - return new ripemd160$1().update(sha$1("sha256").update(buffer).digest()).digest(); + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } var __extends$4 = (undefined && undefined.__extends) || (function () { @@ -31146,9 +31583,9 @@ window.Buffer = buffer.Buffer; p2pkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG])); + buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); return { scriptPubKey: buf.buffer() }; }; p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { @@ -31175,7 +31612,7 @@ window.Buffer = buffer.Buffer; var xonlyPubkey = pubkey.slice(1); // x-only pubkey var buf = new BufferWriter(); var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$i.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen buf.writeSlice(outputKey); return { scriptPubKey: buf.buffer() }; }; @@ -31198,8 +31635,8 @@ window.Buffer = buffer.Buffer; p2tr.prototype.hashTapTweak = function (x) { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$i.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$i.concat([h, h, x])); + var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$l.concat([h, h, x])); }; /** * Calculates a taproot output key from an internal key. This output key will be @@ -31218,13 +31655,13 @@ window.Buffer = buffer.Buffer; // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$i.concat([ - Buffer$i.from([0x02]), + var evenEcdsaPubkey = Buffer$l.concat([ + Buffer$l.from([0x02]), internalPubkey, ]); var tweak = this.hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$i.from(tinySecp256k1.exports.pointAddScalar(evenEcdsaPubkey, tweak)); + var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. var outputSchnorrKey = outputEcdsaKey.slice(1); // Create address @@ -31241,7 +31678,7 @@ window.Buffer = buffer.Buffer; var buf = new BufferWriter(); var redeemScript = this.createRedeemScript(pubkey); var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$i.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; @@ -31271,7 +31708,7 @@ window.Buffer = buffer.Buffer; }; p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { var pubkeyHash = hashPublicKey(pubkey); - return Buffer$i.concat([Buffer$i.from("0014", "hex"), pubkeyHash]); + return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); }; return p2wpkhWrapped; }(SingleKeyAccount)); @@ -31283,7 +31720,7 @@ window.Buffer = buffer.Buffer; p2wpkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$i.from([0, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); buf.writeSlice(pubkeyHash); return { scriptPubKey: buf.buffer() }; }; @@ -31364,7 +31801,7 @@ window.Buffer = buffer.Buffer; var n = leaves.length; if (n == 0) { return { - root: new Node(undefined, undefined, Buffer$i.alloc(32, 0)), + root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), leaves: [] }; } @@ -31384,16 +31821,16 @@ window.Buffer = buffer.Buffer; return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; }; Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$i.concat([Buffer$i.from([1]), left, right])); + return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); }; return Merkle; }()); function hashLeaf(buf, hashFunction) { if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$i.from([0]), buf, hashFunction); + return hashConcat(Buffer$l.from([0]), buf, hashFunction); } function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$i.concat([bufA, bufB])); + return hashFunction(Buffer$l.concat([bufA, bufB])); } var Node = /** @class */ (function () { function Node(left, right, hash) { @@ -31458,13 +31895,13 @@ window.Buffer = buffer.Buffer; }; WalletPolicy.prototype.serialize = function () { var keyBuffers = this.keys.map(function (k) { - return Buffer$i.from(k, "ascii"); + return Buffer$l.from(k, "ascii"); }); var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); var buf = new BufferWriter(); buf.writeUInt8(0x01); // wallet type (policy map) buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$i.from(this.descriptorTemplate, "ascii")); + buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); return buf.buffer(); }; @@ -31487,7 +31924,7 @@ window.Buffer = buffer.Buffer; tx.writeUInt32(psbt.getGlobalTxVersion()); var isSegwit = !!psbt.getInputWitnessUtxo(0); if (isSegwit) { - tx.writeSlice(Buffer$i.from([0, 1])); + tx.writeSlice(Buffer$l.from([0, 1])); } var inputCount = psbt.getGlobalInputCount(); tx.writeVarInt(inputCount); @@ -31495,7 +31932,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < inputCount; i++) { tx.writeSlice(psbt.getInputPreviousTxid(i)); tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$i.from([])); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); tx.writeUInt32(psbt.getInputSequence(i)); if (isSegwit) { witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); @@ -31571,7 +32008,7 @@ window.Buffer = buffer.Buffer; psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { __extends$3(NoSuchEntry, _super); function NoSuchEntry() { @@ -31797,11 +32234,11 @@ window.Buffer = buffer.Buffer; }); }; PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$i.from(v)); }); + from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); }; PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - buf.writeSlice(Buffer$i.from([0x70, 0x73, 0x62, 0x74, 0xff])); + buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); serializeMap(buf, this.globalMap); this.inputMaps.forEach(function (map) { serializeMap(buf, map); @@ -31845,17 +32282,17 @@ window.Buffer = buffer.Buffer; var result = []; map.forEach(function (_v, k) { if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$i.from(k.substring(2), "hex")); + result.push(Buffer$l.from(k.substring(2), "hex")); } }); return result; }; PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$i.from(hexKey.substring(0, 2), "hex").readUInt8(0); + var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); return keyTypes.some(function (k) { return k == keyType; }); }; PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$i.from([])); + var key = new Key(keyType, Buffer$l.from([])); this.globalMap.set(key.toString(), value); }; PsbtV2.prototype.getGlobal = function (keyType) { @@ -31941,7 +32378,7 @@ window.Buffer = buffer.Buffer; throw new NoSuchEntry(key.toString()); } // Make sure to return a copy, to protect the underlying data. - return Buffer$i.from(value); + return Buffer$l.from(value); } var Key = /** @class */ (function () { function Key(keyType, keyData) { @@ -31980,25 +32417,25 @@ window.Buffer = buffer.Buffer; function serializeMap(buf, map) { for (var k in map.keys) { var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$i.from(k, "hex")), value); + var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); keyPair.serialize(buf); } buf.writeUInt8(0); } function b() { - return Buffer$i.from([]); + return Buffer$l.from([]); } function set(map, keyType, keyData, value) { var key = new Key(keyType, keyData); map.set(key.toString(), value); } function uint32LE(n) { - var b = Buffer$i.alloc(4); + var b = Buffer$l.alloc(4); b.writeUInt32LE(n, 0); return b; } function uint64LE(n) { - var b = Buffer$i.alloc(8); + var b = Buffer$l.alloc(8); b.writeBigUInt64LE(BigInt(n), 0); return b; } @@ -32133,7 +32570,7 @@ window.Buffer = buffer.Buffer; } else if (data.length <= 256 * 256) { buf.writeUInt8(77); - var b = Buffer$i.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16LE(data.length, 0); buf.writeSlice(b); } @@ -32160,18 +32597,18 @@ window.Buffer = buffer.Buffer; } function createVarint(value) { if (value < 0xfd) { - var buffer_1 = Buffer$i.alloc(1); + var buffer_1 = Buffer$l.alloc(1); buffer_1[0] = value; return buffer_1; } if (value <= 0xffff) { - var buffer_2 = Buffer$i.alloc(3); + var buffer_2 = Buffer$l.alloc(3); buffer_2[0] = 0xfd; buffer_2[1] = value & 0xff; buffer_2[2] = (value >> 8) & 0xff; return buffer_2; } - var buffer = Buffer$i.alloc(5); + var buffer = Buffer$l.alloc(5); buffer[0] = 0xfe; buffer[1] = value & 0xff; buffer[2] = (value >> 8) & 0xff; @@ -32187,11 +32624,11 @@ window.Buffer = buffer.Buffer; */ function serializeTransactionOutputs(_a) { var outputs = _a.outputs; - var outputBuffer = Buffer$i.alloc(0); + var outputBuffer = Buffer$l.alloc(0); if (typeof outputs !== "undefined") { - outputBuffer = Buffer$i.concat([outputBuffer, createVarint(outputs.length)]); + outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); outputs.forEach(function (output) { - outputBuffer = Buffer$i.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, output.amount, createVarint(output.script.length), @@ -32205,18 +32642,18 @@ window.Buffer = buffer.Buffer; if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$i.alloc(0); + var inputBuffer = Buffer$l.alloc(0); var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; transaction.inputs.forEach(function (input) { inputBuffer = isDecred || isBech32 - ? Buffer$i.concat([ + ? Buffer$l.concat([ inputBuffer, input.prevout, - Buffer$i.from([0x00]), + Buffer$l.from([0x00]), input.sequence, ]) - : Buffer$i.concat([ + : Buffer$l.concat([ inputBuffer, input.prevout, createVarint(input.script.length), @@ -32227,19 +32664,19 @@ window.Buffer = buffer.Buffer; var outputBuffer = serializeTransactionOutputs(transaction); if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$i.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, - (useWitness && transaction.witness) || Buffer$i.alloc(0), + (useWitness && transaction.witness) || Buffer$l.alloc(0), transaction.locktime, - transaction.nExpiryHeight || Buffer$i.alloc(0), - transaction.extraData || Buffer$i.alloc(0), + transaction.nExpiryHeight || Buffer$l.alloc(0), + transaction.extraData || Buffer$l.alloc(0), ]); } - return Buffer$i.concat([ + return Buffer$l.concat([ transaction.version, - timestamp ? timestamp : Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), - useWitness ? Buffer$i.from("0001", "hex") : Buffer$i.alloc(0), + timestamp ? timestamp : Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), createVarint(transaction.inputs.length), inputBuffer, outputBuffer, @@ -32377,7 +32814,7 @@ window.Buffer = buffer.Buffer; case 2: address = _c.sent(); components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$i.from(tinySecp256k1.exports.pointCompress(components.pubkey, false)); + uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); return [2 /*return*/, { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, @@ -32420,7 +32857,7 @@ window.Buffer = buffer.Buffer; masterFingerprint = _a.sent(); policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$i.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; } }); }); @@ -32489,7 +32926,7 @@ window.Buffer = buffer.Buffer; i++; return [3 /*break*/, 2]; case 7: - outputsConcat = Buffer$i.from(arg.outputScriptHex, "hex"); + outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); outputsBufferReader = new BufferReader(outputsConcat); outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); @@ -32585,7 +33022,7 @@ window.Buffer = buffer.Buffer; case 0: inputTx = input[0]; spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$i.from(input[2], "hex") : undefined; + redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; sequence = input[3]; if (sequence) { psbt.setInputSequence(i, sequence); @@ -32629,7 +33066,7 @@ window.Buffer = buffer.Buffer; var sigs; return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$i.alloc(32, 0), progressCallback)]; + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; case 1: sigs = _a.sent(); sigs.forEach(function (v, k) { @@ -32821,6 +33258,17 @@ window.Buffer = buffer.Buffer; }); } + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + var invariant = function(condition, format, a, b, c, d, e, f) { { if (format === undefined) { @@ -32849,7 +33297,7 @@ window.Buffer = buffer.Buffer; } }; - var invariant_1 = invariant; + var browser = invariant; var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -32907,9 +33355,9 @@ window.Buffer = buffer.Buffer; firstRound = false; if (typeof indexLookup === "number") { firstRound = true; - prefix = Buffer$i.alloc(4); + prefix = Buffer$l.alloc(4); prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$i.concat([prefix, transactionData], transactionData.length + 4); + data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); } else { data = transactionData; @@ -32944,7 +33392,7 @@ window.Buffer = buffer.Buffer; return __generator$c(this, function (_b) { switch (_b.label) { case 0: - seq = sequence || Buffer$i.alloc(0); + seq = sequence || Buffer$l.alloc(0); scriptBlocks = []; offset = 0; while (offset !== script.length) { @@ -32955,7 +33403,7 @@ window.Buffer = buffer.Buffer; scriptBlocks.push(script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$i.concat([script.slice(offset, offset + blockSize), seq])); + scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); } offset += blockSize; } @@ -32997,10 +33445,10 @@ window.Buffer = buffer.Buffer; processWholeScriptBlock = function (block) { return getTrustedInputRaw(transport, block); }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$i.concat([ + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ transaction.version, - transaction.timestamp || Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), createVarint(inputs.length), ]), indexLookup)]; case 1: @@ -33014,14 +33462,14 @@ window.Buffer = buffer.Buffer; if (!!inputs_1_1.done) return [3 /*break*/, 7]; input = inputs_1_1.value; isXSTV2 = isXST && - Buffer$i.compare(version, Buffer$i.from([0x02, 0x00, 0x00, 0x00])) === 0; + Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; treeField = isDecred - ? input.tree || Buffer$i.from([0x00]) - : Buffer$i.alloc(0); - data = Buffer$i.concat([ + ? input.tree || Buffer$l.from([0x00]) + : Buffer$l.alloc(0); + data = Buffer$l.concat([ input.prevout, treeField, - isXSTV2 ? Buffer$i.from([0x00]) : createVarint(input.script.length), + isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), ]); return [4 /*yield*/, getTrustedInputRaw(transport, data)]; case 4: @@ -33031,7 +33479,7 @@ window.Buffer = buffer.Buffer; // deferred.notify("input"); // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$i.concat([input.script, input.sequence])) + ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) : isXSTV2 ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence))]; @@ -33067,9 +33515,9 @@ window.Buffer = buffer.Buffer; case 13: if (!!outputs_1_1.done) return [3 /*break*/, 16]; output = outputs_1_1.value; - data = Buffer$i.concat([ + data = Buffer$l.concat([ output.amount, - isDecred ? Buffer$i.from([0x00, 0x00]) : Buffer$i.alloc(0), + isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), createVarint(output.script.length), output.script, ]); @@ -33100,15 +33548,15 @@ window.Buffer = buffer.Buffer; endData.push(extraData); } if (endData.length) { - data = Buffer$i.concat(endData); + data = Buffer$l.concat(endData); extraPart = isDecred ? data - : Buffer$i.concat([createVarint(data.length), data]); + : Buffer$l.concat([createVarint(data.length), data]); } - return [4 /*yield*/, processScriptBlocks(Buffer$i.concat([locktime, extraPart || Buffer$i.alloc(0)]))]; + return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; case 20: res = _c.sent(); - invariant_1(res, "missing result in processScriptBlocks"); + browser(res, "missing result in processScriptBlocks"); return [2 /*return*/, res]; } }); @@ -33188,10 +33636,10 @@ window.Buffer = buffer.Buffer; return __generator$b(this, function (_e) { switch (_e.label) { case 0: - data = Buffer$i.concat([ + data = Buffer$l.concat([ transaction.version, - transaction.timestamp || Buffer$i.alloc(0), - transaction.nVersionGroupId || Buffer$i.alloc(0), + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), createVarint(transaction.inputs.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; @@ -33211,24 +33659,24 @@ window.Buffer = buffer.Buffer; inputValue = inputs[i].value; if (bip143) { if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$i.from([0x01, inputValue.length]); + prefix = Buffer$l.from([0x01, inputValue.length]); } else { - prefix = Buffer$i.from([0x02]); + prefix = Buffer$l.from([0x02]); } } else { if (inputs[i].trustedInput) { - prefix = Buffer$i.from([0x01, inputs[i].value.length]); + prefix = Buffer$l.from([0x01, inputs[i].value.length]); } else { - prefix = Buffer$i.from([0x00]); + prefix = Buffer$l.from([0x00]); } } - data = Buffer$i.concat([ + data = Buffer$l.concat([ prefix, inputValue, - isDecred ? Buffer$i.from([0x00]) : Buffer$i.alloc(0), + isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), createVarint(input.script.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; @@ -33248,7 +33696,7 @@ window.Buffer = buffer.Buffer; scriptBlocks.push(input.script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$i.concat([ + scriptBlocks.push(Buffer$l.concat([ input.script.slice(offset, offset + blockSize), input.sequence, ])); @@ -33314,10 +33762,10 @@ window.Buffer = buffer.Buffer; if (isDecred) { throw new Error("Decred does not implement BIP143"); } - var hash = sha$1("sha256") - .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) .digest(); - var data = Buffer$i.alloc(4); + var data = Buffer$l.alloc(4); data.writeUInt32LE(indexLookup, 0); var outputs = transaction.outputs, locktime = transaction.locktime; if (!outputs || !locktime) { @@ -33326,38 +33774,38 @@ window.Buffer = buffer.Buffer; if (!outputs[indexLookup]) { throw new Error("getTrustedInputBIP143: wrong index"); } - hash = Buffer$i.concat([hash, data, outputs[indexLookup].amount]); + hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); return hash.toString("hex"); } function compressPublicKey(publicKey) { var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$i.alloc(1); + var prefixBuffer = Buffer$l.alloc(1); prefixBuffer[0] = prefix; - return Buffer$i.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$i.alloc(4); + var lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32BE(lockTime, 0); var buffer = isDecred - ? Buffer$i.concat([ + ? Buffer$l.concat([ pathsBuffer, lockTimeBuffer, - expiryHeight || Buffer$i.from([0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([sigHashType]), + expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([sigHashType]), ]) - : Buffer$i.concat([ + : Buffer$l.concat([ pathsBuffer, - Buffer$i.from([0x00]), + Buffer$l.from([0x00]), lockTimeBuffer, - Buffer$i.from([sigHashType]), + Buffer$l.from([sigHashType]), ]); if (expiryHeight && !isDecred) { - buffer = Buffer$i.concat([buffer, expiryHeight]); + buffer = Buffer$l.concat([buffer, expiryHeight]); } return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { if (result.length > 0) { @@ -33487,7 +33935,7 @@ window.Buffer = buffer.Buffer; r = _a.sent(); i = 0; format = r[i++]; - invariant_1(format === 1, "getAppAndVersion: format not supported"); + browser(format === 1, "getAppAndVersion: format not supported"); nameLength = r[i++]; name = r.slice(i, (i += nameLength)).toString("ascii"); versionLength = r[i++]; @@ -33632,9 +34080,9 @@ window.Buffer = buffer.Buffer; additionals.includes("gold") || additionals.includes("bip143"))) || (!!expiryHeight && !isDecred); - nullScript = Buffer$i.alloc(0); - nullPrevout = Buffer$i.alloc(0); - defaultVersion = Buffer$i.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST @@ -33649,12 +34097,12 @@ window.Buffer = buffer.Buffer; targetTransaction = { inputs: [], version: defaultVersion, - timestamp: Buffer$i.alloc(0) + timestamp: Buffer$l.alloc(0) }; getTrustedInputCall = useBip143 && !useTrustedInputForSegwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$i.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); notify(0, 0); _b.label = 5; case 5: @@ -33669,13 +34117,13 @@ window.Buffer = buffer.Buffer; case 7: trustedInput = _b.sent(); log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$i.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: true, - value: Buffer$i.from(trustedInput, "hex"), + value: Buffer$l.from(trustedInput, "hex"), sequence: sequence }); _b.label = 8; @@ -33686,11 +34134,11 @@ window.Buffer = buffer.Buffer; regularOutputs.push(outputs[index]); } if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$i.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); targetTransaction.nExpiryHeight = expiryHeight; // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$i.from(sapling + targetTransaction.extraData = Buffer$l.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); } @@ -33714,7 +34162,7 @@ window.Buffer = buffer.Buffer; return [7 /*endfinally*/]; case 13: targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$i.alloc(4); + var sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); @@ -33743,12 +34191,12 @@ window.Buffer = buffer.Buffer; return [3 /*break*/, 14]; case 17: for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$i.from(result_1[i].publicKey, "hex"))); + publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); } _b.label = 18; case 18: if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$i.alloc(4); + targetTransaction.timestamp = Buffer$l.alloc(4); targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); } onDeviceSignatureRequested(); @@ -33780,13 +34228,13 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 34]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$i.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : !segwit ? regularOutputs[i].script - : Buffer$i.concat([ - Buffer$i.from([OP_DUP, OP_HASH160, HASH_SIZE]), + : Buffer$l.concat([ + Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), hashPublicKey(publicKeys[i]), - Buffer$i.from([OP_EQUALVERIFY, OP_CHECKSIG]), + Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), ]); pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; @@ -33831,20 +34279,20 @@ window.Buffer = buffer.Buffer; // Populate the final input scripts for (i = 0; i < inputs.length; i++) { if (segwit) { - targetTransaction.witness = Buffer$i.alloc(0); + targetTransaction.witness = Buffer$l.alloc(0); if (!bech32) { - targetTransaction.inputs[i].script = Buffer$i.concat([ - Buffer$i.from("160014", "hex"), + targetTransaction.inputs[i].script = Buffer$l.concat([ + Buffer$l.from("160014", "hex"), hashPublicKey(publicKeys[i]), ]); } } else { - signatureSize = Buffer$i.alloc(1); - keySize = Buffer$i.alloc(1); + signatureSize = Buffer$l.alloc(1); + keySize = Buffer$l.alloc(1); signatureSize[0] = signatures[i].length; keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$i.concat([ + targetTransaction.inputs[i].script = Buffer$l.concat([ signatureSize, signatures[i], keySize, @@ -33854,51 +34302,51 @@ window.Buffer = buffer.Buffer; offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); } - lockTimeBuffer = Buffer$i.alloc(4); + lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$i.concat([ + result = Buffer$l.concat([ serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript, ]); if (segwit && !isDecred) { - witness = Buffer$i.alloc(0); + witness = Buffer$l.alloc(0); for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$i.concat([ - Buffer$i.from("02", "hex"), - Buffer$i.from([signatures[i].length]), + tmpScriptData = Buffer$l.concat([ + Buffer$l.from("02", "hex"), + Buffer$l.from([signatures[i].length]), signatures[i], - Buffer$i.from([publicKeys[i].length]), + Buffer$l.from([publicKeys[i].length]), publicKeys[i], ]); - witness = Buffer$i.concat([witness, tmpScriptData]); + witness = Buffer$l.concat([witness, tmpScriptData]); } - result = Buffer$i.concat([result, witness]); + result = Buffer$l.concat([result, witness]); } // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here // and it should not break other coins because expiryHeight is false for them. // Don't know about Decred though. - result = Buffer$i.concat([result, lockTimeBuffer]); + result = Buffer$l.concat([result, lockTimeBuffer]); if (expiryHeight) { - result = Buffer$i.concat([ + result = Buffer$l.concat([ result, - targetTransaction.nExpiryHeight || Buffer$i.alloc(0), - targetTransaction.extraData || Buffer$i.alloc(0), + targetTransaction.nExpiryHeight || Buffer$l.alloc(0), + targetTransaction.extraData || Buffer$l.alloc(0), ]); } if (isDecred) { - decredWitness_1 = Buffer$i.from([targetTransaction.inputs.length]); + decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$i.concat([ + decredWitness_1 = Buffer$l.concat([ decredWitness_1, - Buffer$i.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([0x00, 0x00, 0x00, 0x00]), - Buffer$i.from([0xff, 0xff, 0xff, 0xff]), - Buffer$i.from([targetTransaction.inputs[inputIndex].script.length]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0xff, 0xff, 0xff, 0xff]), + Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script, ]); }); - result = Buffer$i.concat([result, decredWitness_1]); + result = Buffer$l.concat([result, decredWitness_1]); } return [2 /*return*/, result.toString("hex")]; } @@ -33950,7 +34398,7 @@ window.Buffer = buffer.Buffer; switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$i.from(messageHex, "hex"); + message = Buffer$l.from(messageHex, "hex"); offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; @@ -33963,7 +34411,7 @@ window.Buffer = buffer.Buffer; chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - buffer = Buffer$i.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach(function (element, index) { @@ -33990,7 +34438,7 @@ window.Buffer = buffer.Buffer; case 2: _b.sent(); return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$i.from([0x00]))]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; case 4: res = _b.sent(); v = res[0] - 0x30; @@ -34087,9 +34535,9 @@ window.Buffer = buffer.Buffer; switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$i.alloc(0); - nullPrevout = Buffer$i.alloc(0); - defaultVersion = Buffer$i.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); defaultVersion.writeUInt32LE(transactionVersion, 0); trustedInputs = []; regularOutputs = []; @@ -34101,7 +34549,7 @@ window.Buffer = buffer.Buffer; version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$i.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); @@ -34114,15 +34562,15 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; case 3: trustedInput = _c.sent(); - sequence = Buffer$i.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: false, value: segwit - ? Buffer$i.from(trustedInput, "hex") - : Buffer$i.from(trustedInput, "hex").slice(4, 4 + 0x24), + ? Buffer$l.from(trustedInput, "hex") + : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), sequence: sequence }); _c.label = 4; @@ -34150,7 +34598,7 @@ window.Buffer = buffer.Buffer; case 9: // Pre-build the target transaction for (i = 0; i < inputs.length; i++) { - sequence = Buffer$i.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); @@ -34175,7 +34623,7 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 19]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$i.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; @@ -34306,8 +34754,8 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.derivatePath(path)]; case 2: accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$i.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$i.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$i.from(accountDerivation.publicKey, "hex"))); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); return [2 /*return*/, xpub]; } }); @@ -34425,38 +34873,38 @@ window.Buffer = buffer.Buffer; return hash160(compressedPubKey).slice(0, 4); } function asBufferUInt32BE(n) { - var buf = Buffer$i.allocUnsafe(4); + var buf = Buffer$l.allocUnsafe(4); buf.writeUInt32BE(n, 0); return buf; } var compressPublicKeySECP256 = function (publicKey) { - return Buffer$i.concat([ - Buffer$i.from([0x02 + (publicKey[64] & 0x01)]), + return Buffer$l.concat([ + Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), publicKey.slice(1, 33), ]); }; function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { var indexBuffer = asBufferUInt32BE(index); indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$i.concat([ + var extendedKeyBytes = Buffer$l.concat([ asBufferUInt32BE(version), - Buffer$i.from([depth]), + Buffer$l.from([depth]), parentFingerprint, indexBuffer, chainCode, pubKey, ]); var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$i.concat([extendedKeyBytes, checksum])); + return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); } function sha256(buffer) { - return sha$1("sha256").update(buffer).digest(); + return sha$3("sha256").update(buffer).digest(); } function hash256(buffer) { return sha256(sha256(buffer)); } function ripemd160(buffer) { - return new ripemd160$1().update(buffer).digest(); + return new ripemd160$2().update(buffer).digest(); } function hash160(buffer) { return ripemd160(sha256(buffer)); @@ -34494,7 +34942,7 @@ window.Buffer = buffer.Buffer; } MerkleMap.prototype.commitment = function () { // returns a buffer between 65 and 73 (included) bytes long - return Buffer$i.concat([ + return Buffer$l.concat([ createVarint(this.keys.length), this.keysTree.getRoot(), this.valuesTree.getRoot(), @@ -34592,7 +35040,7 @@ window.Buffer = buffer.Buffer; } return v; }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$i.from(k, "hex"); }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); var merkleMap = new MerkleMap(sortedKeys, values); return merkleMap; }; @@ -34673,9 +35121,9 @@ window.Buffer = buffer.Buffer; return _this; } YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$i.from(request.subarray(1))); + this.results.push(Buffer$l.from(request.subarray(1))); this.progressCallback(); - return Buffer$i.from(""); + return Buffer$l.from(""); }; return YieldCommand; }(ClientCommand)); @@ -34698,7 +35146,7 @@ window.Buffer = buffer.Buffer; throw new Error("Unsupported request, the first byte should be 0"); } // read the hash - var hash = Buffer$i.alloc(32); + var hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { hash[i] = req[1 + i]; } @@ -34712,12 +35160,12 @@ window.Buffer = buffer.Buffer; var payload_size = Math.min(max_payload_size, known_preimage.length); if (payload_size < known_preimage.length) { for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$i.from([known_preimage[i]])); + this.queue.push(Buffer$l.from([known_preimage[i]])); } } - return Buffer$i.concat([ + return Buffer$l.concat([ preimage_len_varint, - Buffer$i.from([payload_size]), + Buffer$l.from([payload_size]), known_preimage.subarray(0, payload_size), ]); } @@ -34769,10 +35217,10 @@ window.Buffer = buffer.Buffer; if (n_leftover_elements > 0) { (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); } - return Buffer$i.concat(__spreadArray$1([ + return Buffer$l.concat(__spreadArray$1([ mt.getLeafHash(leaf_index), - Buffer$i.from([proof.length]), - Buffer$i.from([n_response_elements]) + Buffer$l.from([proof.length]), + Buffer$l.from([n_response_elements]) ], __read$1(proof.slice(0, n_response_elements)), false)); }; return GetMerkleLeafProofCommand; @@ -34791,13 +35239,13 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid request, unexpected trailing data"); } // read the root hash - var root_hash = Buffer$i.alloc(32); + var root_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { root_hash[i] = req.readUInt8(i); } var root_hash_hex = root_hash.toString("hex"); // read the leaf hash - var leef_hash = Buffer$i.alloc(32); + var leef_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { leef_hash[i] = req.readUInt8(32 + i); } @@ -34815,7 +35263,7 @@ window.Buffer = buffer.Buffer; break; } } - return Buffer$i.concat([Buffer$i.from([found]), createVarint(leaf_index)]); + return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); }; return GetMerkleLeafIndexCommand; }(ClientCommand)); @@ -34842,9 +35290,9 @@ window.Buffer = buffer.Buffer; var max_elements = Math.floor(253 / element_len); var n_returned_elements = Math.min(max_elements, this.queue.length); var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$i.concat(__spreadArray$1([ - Buffer$i.from([n_returned_elements]), - Buffer$i.from([element_len]) + return Buffer$l.concat(__spreadArray$1([ + Buffer$l.from([n_returned_elements]), + Buffer$l.from([element_len]) ], __read$1(returned_elements), false)); }; return GetMoreElementsCommand; @@ -34907,7 +35355,7 @@ window.Buffer = buffer.Buffer; try { for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { var el = elements_1_1.value; - var preimage = Buffer$i.concat([Buffer$i.from([0]), el]); + var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); this.addKnownPreimage(preimage); } } @@ -35046,8 +35494,8 @@ window.Buffer = buffer.Buffer; if (pathElements.length > 6) { throw new Error("Path too long. At most 6 levels allowed."); } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$i.concat([ - Buffer$i.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), pathElementsToBuffer(pathElements), ]))]; case 1: @@ -35071,15 +35519,15 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid HMAC length"); } clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$i.alloc(4); + addressIndexBuffer = Buffer$l.alloc(4); addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$i.concat([ - Buffer$i.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), walletPolicy.getWalletId(), - walletHMAC || Buffer$i.alloc(32, 0), - Buffer$i.from([change]), + walletHMAC || Buffer$l.alloc(32, 0), + Buffer$l.from([change]), addressIndexBuffer, ]), clientInterpreter)]; case 1: @@ -35102,7 +35550,7 @@ window.Buffer = buffer.Buffer; } clientInterpreter = new ClientCommandInterpreter(progressCallback); // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$i.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); try { @@ -35135,14 +35583,14 @@ window.Buffer = buffer.Buffer; inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$i.concat([ + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ merkelizedPsbt.getGlobalKeysValuesRoot(), createVarint(merkelizedPsbt.getGlobalInputCount()), inputMapsRoot, createVarint(merkelizedPsbt.getGlobalOutputCount()), outputMapsRoot, walletPolicy.getWalletId(), - walletHMAC || Buffer$i.alloc(32, 0), + walletHMAC || Buffer$l.alloc(32, 0), ]), clientInterpreter)]; case 1: _h.sent(); @@ -35169,7 +35617,7 @@ window.Buffer = buffer.Buffer; AppClient.prototype.getMasterFingerprint = function () { return __awaiter$4(this, void 0, void 0, function () { return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$i.from([]))]; + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; }); }); }; @@ -35222,18 +35670,18 @@ window.Buffer = buffer.Buffer; var outputs = []; var witness = false; var offset = 0; - var timestamp = Buffer$i.alloc(0); - var nExpiryHeight = Buffer$i.alloc(0); - var nVersionGroupId = Buffer$i.alloc(0); - var extraData = Buffer$i.alloc(0); + var timestamp = Buffer$l.alloc(0); + var nExpiryHeight = Buffer$l.alloc(0); + var nVersionGroupId = Buffer$l.alloc(0); + var extraData = Buffer$l.alloc(0); var isDecred = additionals.includes("decred"); var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$i.from(transactionHex, "hex"); + var transaction = Buffer$l.from(transactionHex, "hex"); var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$i.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$i.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$i.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$i.from([0x02, 0x00, 0x00, 0x00])); + var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); offset += 4; if (!hasTimestamp && isSegwitSupported && @@ -35259,8 +35707,8 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < numberInputs; i++) { var prevout = transaction.slice(offset, offset + 36); offset += 36; - var script = Buffer$i.alloc(0); - var tree = Buffer$i.alloc(0); + var script = Buffer$l.alloc(0); + var tree = Buffer$l.alloc(0); //No script for decred, it has a witness if (!isDecred) { varint = getVarint(transaction, offset); @@ -36178,7 +36626,7 @@ window.Buffer = buffer.Buffer; this.exchangeTimeout = 30000; this.unresponsiveTimeout = 15000; this.deviceModel = null; - this._events = new EventEmitter__default["default"](); + this._events = new require$$0__default$1["default"](); /** * wrapper on top of exchange to simplify work of the implementation. * @param cla @@ -36190,7 +36638,7 @@ window.Buffer = buffer.Buffer; * @return a Promise of response buffer */ this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$i.alloc(0); } + if (data === void 0) { data = Buffer$l.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } return __awaiter$2(_this, void 0, void 0, function () { var response, sw; @@ -36200,9 +36648,9 @@ window.Buffer = buffer.Buffer; if (data.length >= 256) { throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - return [4 /*yield*/, this.exchange(Buffer$i.concat([ - Buffer$i.from([cla, ins, p1, p2]), - Buffer$i.from([data.length]), + return [4 /*yield*/, this.exchange(Buffer$l.concat([ + Buffer$l.from([cla, ins, p1, p2]), + Buffer$l.from([data.length]), data, ]))]; case 1: @@ -36423,12 +36871,12 @@ window.Buffer = buffer.Buffer; var errors_1 = require$$0; var Tag = 0x05; function asUInt16BE(value) { - var b = Buffer$i.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16BE(value, 0); return b; } var initialAcc = { - data: Buffer$i.alloc(0), + data: Buffer$l.alloc(0), dataLength: 0, sequence: 0 }; @@ -36438,21 +36886,21 @@ window.Buffer = buffer.Buffer; var createHIDframing = function (channel, packetSize) { return { makeBlocks: function (apdu) { - var data = Buffer$i.concat([asUInt16BE(apdu.length), apdu]); + var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); var blockSize = packetSize - 5; var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$i.concat([ + data = Buffer$l.concat([ data, - Buffer$i.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), ]); var blocks = []; for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$i.alloc(5); + var head = Buffer$l.alloc(5); head.writeUInt16BE(channel, 0); head.writeUInt8(Tag, 2); head.writeUInt16BE(i, 3); var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$i.concat([head, chunk])); + blocks.push(Buffer$l.concat([head, chunk])); } return blocks; }, @@ -36472,7 +36920,7 @@ window.Buffer = buffer.Buffer; } sequence++; var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$i.concat([data, chunkData]); + data = Buffer$l.concat([data, chunkData]); if (data.length > dataLength) { data = data.slice(0, dataLength); } @@ -36929,7 +37377,7 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$i.from(r.data.buffer); + buffer = Buffer$l.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -37931,14 +38379,14 @@ window.Buffer = buffer.Buffer; this.exchangeTimeout = 30000; this.unresponsiveTimeout = 15000; this.deviceModel = null; - this._events = new EventEmitter__default["default"](); + this._events = new require$$0__default$1["default"](); - this.send = async (cla, ins, p1, p2, data = Buffer$i.alloc(0), statusList = [StatusCodes.OK]) => { + this.send = async (cla, ins, p1, p2, data = Buffer$l.alloc(0), statusList = [StatusCodes.OK]) => { if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - const response = await this.exchange(Buffer$i.concat([Buffer$i.from([cla, ins, p1, p2]), Buffer$i.from([data.length]), data])); + const response = await this.exchange(Buffer$l.concat([Buffer$l.from([cla, ins, p1, p2]), Buffer$l.from([data.length]), data])); const sw = response.readUInt16BE(response.length - 2); if (!statusList.some(s => s === sw)) { @@ -38201,7 +38649,7 @@ window.Buffer = buffer.Buffer; } function wrapApdu(apdu, key) { - const result = Buffer$i.alloc(apdu.length); + const result = Buffer$l.alloc(apdu.length); for (let i = 0; i < apdu.length; i++) { result[i] = apdu[i] ^ key[i % key.length]; @@ -38218,7 +38666,7 @@ window.Buffer = buffer.Buffer; function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$i.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const challenge = Buffer$l.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); const signRequest = { version: "U2F_V2", keyHandle: webSafe64(keyHandle.toString("base64")), @@ -38232,7 +38680,7 @@ window.Buffer = buffer.Buffer; } = response; if (typeof signatureData === "string") { - const data = Buffer$i.from(normal64(signatureData), "base64"); + const data = Buffer$l.from(normal64(signatureData), "base64"); let result; if (!unwrap) { @@ -38318,7 +38766,7 @@ window.Buffer = buffer.Buffer; setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$i.from(scrambleKey, "ascii"); + this.scrambleKey = Buffer$l.from(scrambleKey, "ascii"); } /** */ @@ -38366,292 +38814,11 @@ window.Buffer = buffer.Buffer; 'default': TransportU2F }); - var inherits$2 = inherits$f.exports; - var HashBase = hashBase; - var Buffer$1 = safeBuffer.exports.Buffer; - - var ARRAY16 = new Array(16); - - function MD5$1 () { - HashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } - - inherits$2(MD5$1, HashBase); - - MD5$1.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; - - MD5$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } - - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); - - // produce result - var buffer = Buffer$1.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; - - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } - - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } - - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } - - function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } - - var md5_js = MD5$1; - - var Buffer = safeBuffer.exports.Buffer; - var Transform = require$$0__default$2["default"].Transform; - var StringDecoder = require$$2__default["default"].StringDecoder; - var inherits$1 = inherits$f.exports; - - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$1(CipherBase, Transform); - - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer.from(data, inputEnc); - } - - var outData = this._update(data); - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - - return outData - }; - - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; - - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; - - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; - - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; - - var cipherBase = CipherBase; - - var inherits = inherits$f.exports; - var MD5 = md5_js; - var RIPEMD160 = ripemd160$1; - var sha = sha_js.exports; - var Base = cipherBase; - - function Hash (hash) { - Base.call(this, 'digest'); - - this._hash = hash; - } - - inherits(Hash, Base); - - Hash.prototype._update = function (data) { - this._hash.update(data); - }; - - Hash.prototype._final = function () { - return this._hash.digest() - }; - - var browser = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() - - return new Hash(sha(alg)) - }; - - var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser - }, [browser])); - exports.Btc = Btc$1; exports.Log = index; exports.TransportU2F = TransportU2F$1; exports.TransportWebUSB = TransportWebUSB$1; - exports.createHash = browser$1; + exports.createHash = browser$4; Object.defineProperty(exports, '__esModule', { value: true }); From bcca757ab8b619ce4cb3d5ca482c68367ab3a676 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 11:15:04 +1100 Subject: [PATCH 21/78] ? --- js/ledger.js | 12297 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 8518 insertions(+), 3779 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index df2ab024..ad61cb7f 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -3,12 +3,10 @@ window.global = window; window.Buffer = buffer.Buffer; (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('buffer'), require('events'), require('stream'), require('string_decoder')) : - typeof define === 'function' && define.amd ? define(['exports', 'buffer', 'events', 'stream', 'string_decoder'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {}, global.require$$0$2, global.require$$0$3, global.require$$1, global.require$$2)); -})(this, (function (exports, require$$0$2, require$$0$3, require$$1, require$$2) { 'use strict'; - - function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.NewLedger = {})); +})(this, (function (exports) { 'use strict'; function _mergeNamespaces(n, m) { m.forEach(function (e) { @@ -25,11 +23,6 @@ window.Buffer = buffer.Buffer; return Object.freeze(n); } - var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2); - var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3); - var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); - var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { @@ -813,23 +806,23 @@ window.Buffer = buffer.Buffer; typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var lookup$1 = []; + var revLookup$1 = []; + var Arr$1 = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var inited = false; function init () { inited = true; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + lookup$1[i] = code[i]; + revLookup$1[code.charCodeAt(i)] = i; } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + revLookup$1['-'.charCodeAt(0)] = 62; + revLookup$1['_'.charCodeAt(0)] = 63; } - function toByteArray (b64) { + function toByteArray$1 (b64) { if (!inited) { init(); } @@ -848,7 +841,7 @@ window.Buffer = buffer.Buffer; placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + arr = new Arr$1(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; @@ -856,17 +849,17 @@ window.Buffer = buffer.Buffer; var L = 0; for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + tmp = (revLookup$1[b64.charCodeAt(i)] << 18) | (revLookup$1[b64.charCodeAt(i + 1)] << 12) | (revLookup$1[b64.charCodeAt(i + 2)] << 6) | revLookup$1[b64.charCodeAt(i + 3)]; arr[L++] = (tmp >> 16) & 0xFF; arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + tmp = (revLookup$1[b64.charCodeAt(i)] << 2) | (revLookup$1[b64.charCodeAt(i + 1)] >> 4); arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + tmp = (revLookup$1[b64.charCodeAt(i)] << 10) | (revLookup$1[b64.charCodeAt(i + 1)] << 4) | (revLookup$1[b64.charCodeAt(i + 2)] >> 2); arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = tmp & 0xFF; } @@ -874,21 +867,21 @@ window.Buffer = buffer.Buffer; return arr } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + function tripletToBase64$1 (num) { + return lookup$1[num >> 18 & 0x3F] + lookup$1[num >> 12 & 0x3F] + lookup$1[num >> 6 & 0x3F] + lookup$1[num & 0x3F] } - function encodeChunk (uint8, start, end) { + function encodeChunk$1 (uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); + output.push(tripletToBase64$1(tmp)); } return output.join('') } - function fromByteArray (uint8) { + function fromByteArray$1 (uint8) { if (!inited) { init(); } @@ -901,20 +894,20 @@ window.Buffer = buffer.Buffer; // 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))); + parts.push(encodeChunk$1(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]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; + output += lookup$1[tmp >> 2]; + output += lookup$1[(tmp << 4) & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; + output += lookup$1[tmp >> 10]; + output += lookup$1[(tmp >> 4) & 0x3F]; + output += lookup$1[(tmp << 2) & 0x3F]; output += '='; } @@ -1010,7 +1003,7 @@ window.Buffer = buffer.Buffer; var toString = {}.toString; - var isArray = Array.isArray || function (arr) { + var isArray$1 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1202,7 +1195,7 @@ window.Buffer = buffer.Buffer; throw new TypeError('"encoding" must be a valid string encoding') } - var length = byteLength(string, encoding) | 0; + var length = byteLength$1(string, encoding) | 0; that = createBuffer(that, length); var actual = that.write(string, encoding); @@ -1278,7 +1271,7 @@ window.Buffer = buffer.Buffer; return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1343,7 +1336,7 @@ window.Buffer = buffer.Buffer; }; Buffer$l.concat = function concat (list, length) { - if (!isArray(list)) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -1372,7 +1365,7 @@ window.Buffer = buffer.Buffer; return buffer }; - function byteLength (string, encoding) { + function byteLength$1 (string, encoding) { if (internalIsBuffer(string)) { return string.length } @@ -1415,7 +1408,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$l.byteLength = byteLength; + Buffer$l.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1878,9 +1871,9 @@ window.Buffer = buffer.Buffer; function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { - return fromByteArray(buf) + return fromByteArray$1(buf) } else { - return fromByteArray(buf.slice(start, end)) + return fromByteArray$1(buf.slice(start, end)) } } @@ -2742,7 +2735,7 @@ window.Buffer = buffer.Buffer; function base64ToBytes (str) { - return toByteArray(base64clean(str)) + return toByteArray$1(base64clean(str)) } function blitBuffer (src, dst, offset, length) { @@ -2903,4785 +2896,9531 @@ window.Buffer = buffer.Buffer; var safeBuffer = {exports: {}}; - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + var buffer = {}; - (function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - var buffer = require$$0__default["default"]; - var Buffer = buffer.Buffer; + var base64Js = {}; - // alternative to using Object.keys for old browsers - function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key]; + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + + var code$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i$1 = 0, len = code$1.length; i$1 < len; ++i$1) { + lookup[i$1] = code$1[i$1]; + revLookup[code$1.charCodeAt(i$1)] = i$1; + } + + // 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] } - if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer; - } else { - // Copy properties from require('buffer') - copyProps(buffer, exports); - exports.Buffer = SafeBuffer; + + // 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 SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } - SafeBuffer.prototype = Object.create(Buffer.prototype); + function toByteArray (b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; - // Copy static methods from Buffer - copyProps(Buffer, SafeBuffer); + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) - }; + var curByte = 0; - 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 - }; + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen; - SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + 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; } - return Buffer(size) - }; - SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[curByte++] = tmp & 0xFF; } - return buffer.SlowBuffer(size) - }; - }(safeBuffer, safeBuffer.exports)); - - var readableBrowser = {exports: {}}; - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + 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; + } - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + return arr } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; + + 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 runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + 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('') } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + var ieee754 = {}; + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; + ieee754.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]; - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; + 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) + }; + + ieee754.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; } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); + if (e + eBias >= 1) { + value += rt / c; } else { - queueIndex = -1; + value += rt * Math.pow(2, 1 - eBias); } - if (queue.length) { - drainQueue(); + if (value * c >= 2) { + e++; + c /= 2; } - } - function drainQueue() { - if (draining) { - return; + 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; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + } - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); + 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; }; - var title = 'browser'; - var platform = 'browser'; - var browser$6 = true; - var env = {}; - var argv = []; - var version$1 = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config$1 = {}; - function noop$2() {} + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - var on = noop$2; - var addListener = noop$2; - var once$2 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; + (function (exports) { - function binding(name) { - throw new Error('process.binding is not supported'); + var base64 = base64Js; + var ieee754$1 = ieee754; + var 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; + + var 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 cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { foo: function () { return 42 } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42 + } catch (e) { + return false + } + } - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } + }); - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset } - return [seconds,nanoseconds] + }); + + function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf } - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; + /** + * 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) } - var process = { - nextTick: nextTick, - title: title, - browser: browser$6, - env: env, - argv: argv, - version: version$1, - versions: versions, - on: on, - addListener: addListener, - once: once$2, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config$1, - uptime: uptime - }; + Buffer.poolSize = 8192; // not used by this implementation - var streamBrowser = require$$0__default$1["default"].EventEmitter; + function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - var _nodeResolve_empty = {}; + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } - var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': _nodeResolve_empty - }); + 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) + ) + } - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - 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; } + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var b = fromObject(value); + if (b) return b - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } - var _require$2 = require$$0__default["default"], - Buffer$k = _require$2.Buffer; + /** + * 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) + }; - var _require2 = require$$3, - inspect = _require2.inspect; + // 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); - var custom = inspect && inspect.custom || 'inspect'; + 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 copyBuffer(src, target, offset) { - Buffer$k.prototype.copy.call(src, target, offset); + 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) } - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + }; - this.head = null; - this.tail = null; - this.length = 0; + 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'; } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$k.alloc(0); - var ret = Buffer$k.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } + var actual = buf.write(string, encoding); - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. + 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); + } - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; + return buf + } - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } + function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf + } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. + function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) + } - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } + var 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); + } - break; - } + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); - ++c; - } + return buf + } - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$k.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; + if (buf.length === 0) { + return buf + } - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; + obj.copy(buf, 0, 0, len); + return buf + } - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - break; - } + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } - ++c; - } + 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 + } - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) + } - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false + }; - return BufferList; - }(); + 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' + ) + } - function destroy(err, cb) { - var _this = this; + if (a === b) return 0 - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + var x = a.length; + var y = b.length; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break } + } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + 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 + } + }; - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well + 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) + } - if (this._writableState) { - this._writableState.destroyed = true; + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(buf).copy(buffer, pos); } else { - nextTick(emitCloseNT, _this); + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') } else { - nextTick(emitCloseNT, _this); + buf.copy(buffer, pos); } - }); - - return this; - } - - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); - } - - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); - } - - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; + pos += buf.length; } + return buffer + }; - 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 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 + ) } - } - function emitErrorNT(self, err) { - self.emit('error', err); - } + var len = string.length; + var mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + // Use a for loop to avoid recursion + var 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; - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; + function slowToString (encoding, start, end) { + var loweredCase = false; - var errorsBrowser = {}; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + // 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 '' + } - var codes = {}; + if (end === undefined || end > this.length) { + end = this.length; + } - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; + if (end <= 0) { + return '' } - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' } - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); + if (!encoding) encoding = 'utf8'; - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - return NodeError; - }(Base); + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + case 'ascii': + return asciiSlice(this, start, end) + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); + case 'base64': + return base64Slice(this, start, end) - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); + 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; } - } else { - return "of ".concat(thing, " ").concat(String(expected)); } - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - + } - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + // 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) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; - return str.substring(this_len - search.length, this_len) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this + }; - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') } - } + for (var 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 + }; - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; + Buffer.prototype.toString = function toString () { + var length = this.length; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } + Buffer.prototype.toLocaleString = Buffer.prototype.toString; - var msg; + 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 + }; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + Buffer.prototype.inspect = function inspect () { + var str = ''; + var 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) + ) } - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg; - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - errorsBrowser.codes = codes; + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } + if (this === target) return 0 - return Math.floor(hwm); - } // Default value + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - return state.objectMode ? 16 : 16 * 1024; - } + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } - var state = { - getHighWaterMark: getHighWaterMark$2 + if (x < y) return -1 + if (y < x) return 1 + return 0 }; - /** - * Module exports. - */ + // 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 - var browser$5 = deprecate; + // 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); + } - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ + // 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 + } - function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); } - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); + // 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 { - console.warn(msg); + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } - warned = true; } - return fn.apply(this, arguments); + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) } - return deprecated; + throw new TypeError('val must be string, number or Buffer') } - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!commonjsGlobal.localStorage) return false; - } catch (_) { - return false; + 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; + } } - var val = commonjsGlobal.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; - } - - var _stream_writable = Writable$1; - // there will be only 2 of these for each stream - - function CorkedRequest(state) { - var _this = this; + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - this.next = null; - this.entry = null; + var i; + if (dir) { + var 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--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } - this.finish = function () { - onCorkedFinish(_this, state); - }; + return -1 } - /* */ - - /**/ - - var Duplex$3; - /**/ - - Writable$1.WritableState = WritableState; - /**/ + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; - var internalUtil = { - deprecate: browser$5 + 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) + }; - var Stream$1 = streamBrowser; - /**/ + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + var strLen = string.length; - var Buffer$j = require$$0__default["default"].Buffer; + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$j.from(chunk); + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } - function _isUint8Array$1(obj) { - return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } - var destroyImpl$1 = destroy_1; + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; + 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' + ) + } - var _require$codes$3 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - inherits_browser.exports(Writable$1, Stream$1); + if (!encoding) encoding = 'utf8'; - function nop() {} + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - function WritableState(options, stream, isDuplex) { - Duplex$3 = Duplex$3 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$3; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - this.finalCalled = false; // drain event flag. + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; - this.needDrain = false; // at the start of calling end() + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; - this.ending = false; // when end() has been called, and returned + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } - this.ended = false; // when 'finish' is emitted + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - this.finished = false; // has it been destroyed + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1; - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + 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; + } + } + } + } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + 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; + } - this.length = 0; // a flag to see when we're in the middle of a write. + res.push(codePoint); + i += bytesPerSequence; + } - this.writing = false; // when true all writes will be buffered until .uncork() call + return decodeCodePointsArray(res) + } - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + // 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 + var MAX_ARGUMENTS_LENGTH = 0x1000; - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + function hexSlice (buf, start, end) { + var len = buf.length; - this.autoDestroy = !!options.autoDestroy; // count buffered requests + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + var out = ''; + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out + } - this.corkedRequestsFree = new CorkedRequest(this); + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); + } + return res } - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - while (current) { - out.push(current); - current = current.next; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; } - return out; - }; + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } - (function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. + if (end < start) end = start; + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); - var realHasInstance; + return newBuf + }; - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$1, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$1) return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; + /* + * 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') } - function Writable$1(options) { - Duplex$3 = Duplex$3 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 + Buffer.prototype.readUintLE = + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var isDuplex = this instanceof Duplex$3; - if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - this.writable = true; + return val + }; - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; + Buffer.prototype.readUintBE = + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - Stream$1.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + return val + }; - Writable$1.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + Buffer.prototype.readUint8 = + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] }; - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + 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) + }; - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. + 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); - function validChunk(stream, state, chunk, cb) { - var er; + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); - } + Buffer.prototype.readUint32BE = + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } + mul *= 0x80; - return true; - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - Writable$1.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + return val + }; - var isBuf = !state.objectMode && _isUint8Array$1(chunk); + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - if (isBuf && !Buffer$j.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; } + mul *= 0x80; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; + return val }; - Writable$1.prototype.cork = function () { - this._writableState.corked++; + 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) }; - Writable$1.prototype.uncork = function () { - var state = this._writableState; + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; + 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) }; - Object.defineProperty(Writable$1.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$j.from(chunk, encoding); - } + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - return chunk; - } + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, true, 23, 4) + }; - Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, false, 23, 4) + }; - function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, true, 52, 8) + }; - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, false, 52, 8) + }; - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + 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') + } - if (!ret) state.needDrain = true; + Buffer.prototype.writeUintLE = + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } + return offset + byteLength + }; - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + Buffer.prototype.writeUintBE = + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - return ret; - } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + return offset + byteLength + }; - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; + 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 + }; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error + 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 + }; - nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error + 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 + }; - finishMaybe(stream, state); - } - } + 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 + }; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + 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 onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - if (sync) { - nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); + var i = 0; + var mul = 1; + var 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; } - } - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. + return offset + byteLength + }; + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - } // if there's something in the buffer waiting, then process it - - - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; + var i = byteLength - 1; + var mul = 1; + var 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; + } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + return offset + byteLength + }; - state.pendingcb++; - state.lastBufferedRequest = null; + 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 + }; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } + 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 + }; - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + 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 + }; - if (state.writing) { - break; - } - } + 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 + }; - if (entry === null) state.lastBufferedRequest = null; - } + 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 + }; - state.bufferedRequest = entry; - state.bufferProcessing = false; + 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') } - Writable$1.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; - - Writable$1.prototype._writev = null; - - Writable$1.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); } + ieee754$1.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - if (!state.ending) endWritable(this, state, cb); - return this; + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) }; - Object.defineProperty(Writable$1.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); } - }); - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + ieee754$1.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 } - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - if (err) { - errorOrDestroy$1(stream, err); - } + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); - } + // 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; - function prefinish$1(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } + // 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') - function finishMaybe(stream, state) { - var need = needFinish(state); + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - if (need) { - prefinish$1(stream, state); + var len = end - start; - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + 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 + ); + } - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + return len + }; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } + // 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) { + var 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); } - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + // 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') } - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. + if (end <= start) { + return this + } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - state.corkedRequestsFree.next = corkReq; - } + if (!val) val = 0; - Object.defineProperty(Writable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding); + var 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._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; } - }); - Writable$1.prototype.destroy = destroyImpl$1.destroy; - Writable$1.prototype._undestroy = destroyImpl$1.undestroy; - Writable$1.prototype._destroy = function (err, cb) { - cb(err); + return this }; - /**/ + // HELPER FUNCTIONS + // ================ - var objectKeys = Object.keys || function (obj) { - var keys = []; + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - for (var key in obj) { - keys.push(key); + 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 + } - return keys; - }; - /**/ - - - var _stream_duplex = Duplex$2; + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - var Readable$1 = _stream_readable; + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - var Writable = _stream_writable; + // 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 + } - inherits_browser.exports(Duplex$2, Readable$1); + // valid lead + leadSurrogate = codePoint; - { - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); + continue + } - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable.prototype[method]; - } - } + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$1.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; + // 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); + } - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + leadSurrogate = null; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); + // 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 } - Object.defineProperty(Duplex$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); } - }); - Object.defineProperty(Duplex$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var 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); } - }); // the no-half-open enforcer - function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + return byteArray + } - nextTick(onEndNT, this); + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) } - function onEndNT(self) { - self.end(); + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i } - Object.defineProperty(Duplex$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; + // 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 + var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; } + } + return table + })(); + }(buffer)); - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer$1 = buffer; + var Buffer = buffer$1.Buffer; - this._readableState.destroyed = value; - this._writableState.destroyed = value; + // 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$1; + } else { + // Copy properties from require('buffer') + copyProps(buffer$1, exports); + exports.Buffer = SafeBuffer; + } - var string_decoder = {}; + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } - /**/ + SafeBuffer.prototype = Object.create(Buffer.prototype); - var Buffer$i = safeBuffer.exports.Buffer; - /**/ + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); - var isEncoding = Buffer$i.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; + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } + return Buffer(arg, encodingOrOffset, length) }; - 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; + 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); } - } - // 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$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; - } + return buf + }; - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. - string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(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; + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer$i.allocUnsafe(nb); - } + return Buffer(size) + }; - StringDecoder$2.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; + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; + return buffer$1.SlowBuffer(size) }; + }(safeBuffer, safeBuffer.exports)); - StringDecoder$2.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; + var readableBrowser = {exports: {}}; - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.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; - }; + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - // 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; + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } - - // 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; + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; } - // 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'; + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } } - } - } - // 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); - 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); } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + - // 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; } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; - // 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); - } + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } - 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 drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - 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); + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } - - 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; + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } } - - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$6 = true; + var env = {}; + var argv = []; + var version$1 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config$1 = {}; - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; + function noop$2() {} + + var on = noop$2; + var addListener = noop$2; + var once$3 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; + + function binding(name) { + throw new Error('process.binding is not supported'); } - var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; } - - callback.apply(this, args); - }; + } + return [seconds,nanoseconds] } - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; } - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + var process = { + nextTick: nextTick, + title: title, + browser: browser$6, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once$3, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config$1, + uptime: uptime + }; - var writableEnded = stream._writableState && stream._writableState.finished; + var events = {exports: {}}; - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); + 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 readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); + 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)); }; - - var onerror = function onerror(err) { - callback.call(stream, err); + } else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); }; + } - var onclose = function onclose() { - var err; + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); + } - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; + }; - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; + function EventEmitter() { + EventEmitter.init.call(this); + } + events.exports = EventEmitter; + events.exports.once = once$2; - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._eventsCount = 0; + EventEmitter.prototype._maxListeners = undefined; - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + // 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); + } } - var endOfStream = eos$1; + 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; + } + }); - var _Object$setPrototypeO; + EventEmitter.init = function() { - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } - var finished = endOfStream; + this._maxListeners = this._maxListeners || undefined; + }; - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); + // 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 createIterResult(value, done) { - return { - value: value, - done: done - }; + function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' + EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + 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 } - } - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } + var handler = events[type]; - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } + if (handler === undefined) + return false; - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } + 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); + } - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, + return true; + }; - next: function next() { - var _this = this; + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; + checkListener(listener); - if (error !== null) { - return Promise.reject(error); + 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 (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); + 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); } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - + // 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); + } + } - var lastPromise = this[kLastPromise]; - var promise; + return target; + } - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + EventEmitter.prototype.on = EventEmitter.prototype.addListener; - promise = new Promise(this[kHandlePromise]); - } + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; - this[kLastPromise] = promise; - return promise; + 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); } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; + } - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); + 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; + } - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error + EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; - iterator[kError] = err; - return; - } + // 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; - var resolve = iterator[kLastResolve]; + checkListener(listener); - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + events = this._events; + if (events === undefined) + return this; - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; + list = events[type]; + if (list === undefined) + return this; - var async_iterator = createReadableStreamAsyncIterator$1; + 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; + } + } - var fromBrowser = function () { - throw new Error('Readable.from is not available in the browser') - }; + if (position < 0) + return this; - var _stream_readable = Readable; - /**/ + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } - var Duplex$1; - /**/ + if (list.length === 1) + events[type] = list[0]; - Readable.ReadableState = ReadableState; - /**/ + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } - require$$0__default$1["default"].EventEmitter; + return this; + }; - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - /**/ + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + events = this._events; + if (events === undefined) + return this; - var Stream = streamBrowser; - /**/ + // 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; + } - var Buffer$h = require$$0__default["default"].Buffer; + listeners = events[type]; - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + 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]); + } + } - function _uint8ArrayToBuffer(chunk) { - return Buffer$h.from(chunk); - } + return this; + }; - function _isUint8Array(obj) { - return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ + function _listeners(target, type, unwrap) { + var events = target._events; + if (events === undefined) + return []; - var debugUtil = require$$3; + var evlistener = events[type]; + if (evlistener === undefined) + return []; - var debug$4; + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - if (debugUtil && debugUtil.debuglog) { - debug$4 = debugUtil.debuglog('stream'); - } else { - debug$4 = function debug() {}; + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } - /**/ + EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; - var BufferList = buffer_list; + EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; - var destroyImpl = destroy_1; + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; - var _require = state, - getHighWaterMark = _require.getHighWaterMark; + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; - var _require$codes$2 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + if (events !== undefined) { + var evlistener = events[type]; + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } - var StringDecoder$1; - var createReadableStreamAsyncIterator; - var from; + return 0; + } - inherits_browser.exports(Readable, Stream); + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; + } - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + 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 ReadableState(options, stream, isDuplex) { - Duplex$1 = Duplex$1 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + function once$2(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$1; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + 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 }); + } + }); + } - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } + } - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() + 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); + } + } - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + var EventEmitter$1 = events.exports; - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + var streamBrowser = events.exports.EventEmitter; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + var _nodeResolve_empty = {}; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + 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; } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - this.readingMore = false; - this.decoder = null; - this.encoding = null; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function Readable(options) { - Duplex$1 = Duplex$1 || _stream_duplex; - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - var isDuplex = this instanceof Duplex$1; - this._readableState = new ReadableState(options, this, isDuplex); // legacy + var _require$2 = buffer, + Buffer$k = _require$2.Buffer; - this.readable = true; + var _require2 = require$$3, + inspect$1 = _require2.inspect; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + var custom = inspect$1 && inspect$1.custom || 'inspect'; - Stream.call(this); + function copyBuffer(src, target, offset) { + Buffer$k.prototype.copy.call(src, target, offset); } - Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; - this._readableState.destroyed = value; - } - }); - Readable.prototype.destroy = destroyImpl.destroy; - Readable.prototype._undestroy = destroyImpl.undestroy; + while (p = p.next) { + ret += s + p.data; + } - Readable.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$k.alloc(0); + var ret = Buffer$k.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; - if (encoding !== state.encoding) { - chunk = Buffer$h.from(chunk, encoding); - encoding = ''; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); } - skipChunkCheck = true; + return ret; } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; - Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$4('readableAddChunk', chunk); - var state = stream._readableState; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); + break; + } - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { - chunk = _uint8ArrayToBuffer(chunk); + ++c; } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$k.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } + break; + } - maybeReadMore(stream, state); - } + ++c; + } - function chunkInvalid(state, chunk) { - var er; + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } + }, { + key: custom, + value: function value(_, options) { + return inspect$1(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); - return er; - } + return BufferList; + }(); - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); + } + } - Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - var p = this._readableState.buffer.head; - var content = ''; + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well - while (p !== null) { - content += decoder.write(p.data); - p = p.next; + + if (this._writableState) { + this._writableState.destroyed = true; } - this._readableState.buffer.clear(); + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); + } else { + nextTick(emitCloseNT, _this); + } + }); - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; return this; - }; // Don't raise the hwm > 1GB + } + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } - var MAX_HWM = 0x40000000; + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); + } - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. + 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(self, err) { + self.emit('error', err); + } + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + } - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + var errorsBrowser = {}; + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough + var codes = {}; - if (!state.ended) { - state.needReadable = true; - return 0; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - return state.length; - } // you can override either this method, or the async _read(n) below. + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - Readable.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + return NodeError; + }(Base); - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); - var doRead = state.needReadable; - debug$4('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; // call internal read method + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } - this._read(state.highWaterMark); + return str.substring(this_len - search.length, this_len) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; + if (start + search.length > str.length) { + return false; } else { - state.length -= n; - state.awaitDrain = 0; + return str.indexOf(search, start) !== -1; } + } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; - if (nOrig !== n && state.ended) endReadable(this); + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; } - if (ret !== null) this.emit('data', ret); - return ret; - }; + var msg; - function onEofChunk(stream, state) { - debug$4('onEofChunk'); - if (state.ended) return; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } - if (state.decoder) { - var chunk = state.decoder.end(); + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + errorsBrowser.codes = codes; - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } + var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; - state.ended = true; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + return Math.floor(hwm); + } // Default value - function emitReadable(stream) { - var state = stream._readableState; - debug$4('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_, stream); - } + return state.objectMode ? 16 : 16 * 1024; } - function emitReadable_(stream) { - var state = stream._readableState; - debug$4('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + var state = { + getHighWaterMark: getHighWaterMark$2 + }; + /** + * Module exports. + */ - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. + var browser$5 = deprecate$1; + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); + function deprecate$1 (fn, msg) { + if (config('noDeprecation')) { + return fn; } - } - function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); } - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. + return deprecated; + } + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; + } + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; + } - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + var _stream_writable = Writable$2; + // there will be only 2 of these for each stream - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; + function CorkedRequest$1(state) { + var _this = this; - default: - state.pipes.push(dest); - break; - } + this.next = null; + this.entry = null; - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ - function onunpipe(readable, unpipeInfo) { - debug$4('onunpipe'); + /**/ - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + + var Duplex$4; + /**/ + + Writable$2.WritableState = WritableState$1; + /**/ + + var internalUtil = { + deprecate: browser$5 + }; + /**/ + + /**/ + + var Stream$2 = streamBrowser; + /**/ + + + var Buffer$j = buffer.Buffer; + + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$j.from(chunk); + } + + function _isUint8Array$1(obj) { + return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + } + + var destroyImpl$1 = destroy_1; + + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; + + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + + inherits_browser.exports(Writable$2, Stream$2); + + function nop$1() {} + + function WritableState$1(options, stream, isDuplex) { + Duplex$4 = Duplex$4 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest$1(this); + } + + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState$1.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + + + var realHasInstance; + + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$2, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$2) return false; + return object && object._writableState instanceof WritableState$1; } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } + + function Writable$2(options) { + Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$4; + if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); + this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - function onend() { - debug$4('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. + Stream$2.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; + Writable$2.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; - function cleanup() { - debug$4('cleanup'); // cleanup event handlers once the pipe is broken + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + + function validChunk$1(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); } - src.on('data', ondata); + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } - function ondata(chunk) { - debug$4('ondata'); - var ret = dest.write(chunk); - debug$4('dest.write', ret); + return true; + } - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', state.awaitDrain); - state.awaitDrain++; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$j.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop$1; + if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + + Writable$2.prototype.cork = function () { + this._writableState.corked++; + }; + + Writable$2.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; + + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$j.from(chunk, encoding); + } + + return chunk; + } + + Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk$1(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe$1, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe$1(stream, state); + } + } + + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate$1(state); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } + + if (sync) { + nextTick(afterWrite$1, stream, state, finished, cb); + } else { + afterWrite$1(stream, state, finished, cb); + } + } + } + + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + + + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } // if there's something in the buffer waiting, then process it + + + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + + buffer.allBuffers = allBuffers; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; + + Writable$2.prototype._writev = null; + + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable$1(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); + } + + function prefinish$2(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); + + if (need) { + prefinish$2(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + + return need; + } + + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; + } + + Object.defineProperty(Writable$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } + }); + Writable$2.prototype.destroy = destroyImpl$1.destroy; + Writable$2.prototype._undestroy = destroyImpl$1.undestroy; + + Writable$2.prototype._destroy = function (err, cb) { + cb(err); + }; + + /**/ + + var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; + }; + /**/ + + + var _stream_duplex = Duplex$3; + + var Readable$2 = _stream_readable; + + var Writable$1 = _stream_writable; + + inherits_browser.exports(Duplex$3, Readable$2); + + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Writable$1.prototype); + + for (var v$1 = 0; v$1 < keys$1.length; v$1++) { + var method$1 = keys$1[v$1]; + if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; + } + } + + function Duplex$3(options) { + if (!(this instanceof Duplex$3)) return new Duplex$3(options); + Readable$2.call(this, options); + Writable$1.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend$1); + } + } + } + + Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer + + function onend$1() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + nextTick(onEndNT$1, this); + } + + function onEndNT$1(self) { + self.end(); + } + + Object.defineProperty(Duplex$3.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + var string_decoder = {}; + + /**/ + + var Buffer$i = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$i.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$i.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. + var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$i.allocUnsafe(nb); + } + + StringDecoder$2.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$2.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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); + 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) : ''; + } + + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; + + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; + } + + function noop$1() {} + + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } + + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } + + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; + + var async_iterator = createReadableStreamAsyncIterator$1; + + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') + }; + + var _stream_readable = Readable$1; + /**/ + + var Duplex$2; + /**/ + + Readable$1.ReadableState = ReadableState$1; + /**/ + + events.exports.EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ + + /**/ + + + var Stream$1 = streamBrowser; + /**/ + + + var Buffer$h = buffer.Buffer; + + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); + } + + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ + + + var debugUtil = require$$3; + + var debug$5; + + if (debugUtil && debugUtil.debuglog) { + debug$5 = debugUtil.debuglog('stream'); + } else { + debug$5 = function debug() {}; + } + /**/ + + + var BufferList$1 = buffer_list; + + var destroyImpl = destroy_1; + + var _require = state, + getHighWaterMark = _require.getHighWaterMark; + + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + + + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; + + inherits_browser.exports(Readable$1, Stream$1); + + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener$1(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState$1(options, stream, isDuplex) { + Duplex$2 = Duplex$2 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + + this.buffer = new BufferList$1(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + + this.autoDestroy = !!options.autoDestroy; // has it been destroyed + + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable$1(options) { + Duplex$2 = Duplex$2 || _stream_duplex; + if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$2; + this._readableState = new ReadableState$1(options, this, isDuplex); // legacy + + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream$1.call(this); + } + + Object.defineProperty(Readable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } + }); + Readable$1.prototype.destroy = destroyImpl.destroy; + Readable$1.prototype._undestroy = destroyImpl.undestroy; + + Readable$1.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + + + Readable$1.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer$h.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() + + + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); + }; + + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$5('readableAddChunk', chunk); + var state = stream._readableState; + + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); + + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore$1(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable$1(stream); + } + + maybeReadMore$1(stream, state); + } + + function chunkInvalid$1(state, chunk) { + var er; + + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; + } + + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. + + + Readable$1.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + + this._readableState.buffer.clear(); + + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB + + + var MAX_HWM$1 = 0x40000000; + + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; + } // you can override either this method, or the async _read(n) below. + + + Readable$1.prototype.read = function (n) { + debug$5('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$5('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } + + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$5('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug$5('reading or ended', doRead); + } else if (doRead) { + debug$5('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; + + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + + if (nOrig !== n && state.ended) endReadable$1(this); + } + + if (ret !== null) this.emit('data', ret); + return ret; + }; + + function onEofChunk$1(stream, state) { + debug$5('onEofChunk'); + if (state.ended) return; + + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable$1(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_$1(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + + + function emitReadable$1(stream) { + var state = stream._readableState; + debug$5('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + + if (!state.emittedReadable) { + debug$5('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); + } + } + + function emitReadable_$1(stream) { + var state = stream._readableState; + debug$5('emitReadable_', state.destroyed, state.length, state.ended); + + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow$1(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + + + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } + } + + function maybeReadMore_$1(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$5('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable$1.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + }; + + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + state.pipesCount += 1; + debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug$5('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug$5('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug$5('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug$5('ondata'); + var ret = dest.write(chunk); + debug$5('dest.write', ret); + + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$5('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug$5('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug$5('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug$5('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug$5('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain$1(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$5('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow$1(src); + } + }; + } + + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } + + return this; + } // try to find the right one. + + + var index = indexOf$1(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something + + + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$5('on readable', state.length, state.reading); + + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } + } + + return res; + }; + + Readable$1.prototype.addListener = Readable$1.prototype.on; + + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$1.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } + + function nReadingNextTick$1(self) { + debug$5('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + + + Readable$1.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug$5('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume$1(this, state); + } + + state.paused = false; + return this; + }; + + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); + } + } + + function resume_$1(stream, state) { + debug$5('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable$1.prototype.pause = function () { + debug$5('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug$5('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + + this._readableState.paused = true; + return this; + }; + + function flow$1(stream) { + var state = stream._readableState; + debug$5('flow', state.flowing); + + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + + + Readable$1.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$5('wrapped end'); + + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$5('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug$5('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } + + return createReadableStreamAsyncIterator(this); + }; + } + + Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + + Readable$1._fromList = fromList$1; + Object.defineProperty(Readable$1.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + + function endReadable$1(stream) { + var state = stream._readableState; + debug$5('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); + } + } + + function endReadableNT$1(state, stream) { + debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } + + return from(Readable$1, iterable, opts); + }; + } + + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + + return -1; + } + + var _stream_transform = Transform$4; + + var _require$codes$1 = errorsBrowser.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + + var Duplex$1 = _stream_duplex; + + inherits_browser.exports(Transform$4, Duplex$1); + + function afterTransform$1(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); + Duplex$1.call(this, options); + this._transformState = { + afterTransform: afterTransform$1.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. + + + this.on('prefinish', prefinish$1); + } + + function prefinish$1() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done$1(_this, er, data); + }); + } else { + done$1(this, null, null); + } + } + + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$1.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + + + Transform$4.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; + + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + + + Transform$4.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform$4.prototype._destroy = function (err, cb) { + Duplex$1.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done$1(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + + var _stream_passthrough = PassThrough$1; + + var Transform$3 = _stream_transform; + + inherits_browser.exports(PassThrough$1, Transform$3); + + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform$3.call(this, options); + } + + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + var eos; + + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + + var _require$codes = errorsBrowser.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } + + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } + + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } + + function call(fn) { + fn(); + } + + function pipe(from, to) { + return from.pipe(to); + } + + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } + + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } + + var pipeline_1 = pipeline; + + (function (module, exports) { + exports = module.exports = _stream_readable; + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + }(readableBrowser, readableBrowser.exports)); + + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$2 = readableBrowser.exports.Transform; + var inherits$i = inherits_browser.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } + + function HashBase$2 (blockSize) { + Transform$2.call(this); + + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + + this._finalized = false; + } + + inherits$i(HashBase$2, Transform$2); + + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } + + callback(error); + }; + + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } + + return this + }; + + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; + + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; + + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); + + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; + + return digest + }; + + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; + + var hashBase = HashBase$2; + + var inherits$h = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; + + var ARRAY16$1 = new Array(16); + + function MD5$2 () { + HashBase$1.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } + + inherits$h(MD5$2, HashBase$1); + + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; + + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; + + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } + + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } + + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } + + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } + + var md5_js = MD5$2; + + var Buffer$e = buffer.Buffer; + var inherits$g = inherits_browser.exports; + var HashBase = hashBase; + + var ARRAY16 = new Array(16); + + var zl = [ + 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 zr = [ + 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 sl = [ + 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 sr = [ + 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 + ]; + + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + + function RIPEMD160$3 () { + HashBase.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } + + inherits$g(RIPEMD160$3, HashBase); + + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; + + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } + + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; + + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } + + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; + + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + var ripemd160$2 = RIPEMD160$3; + + var sha_js = {exports: {}}; + + var Buffer$d = safeBuffer.exports.Buffer; + + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } + + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } + + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } + } + + this._len += length; + return this + }; + + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; + + this._block[rem] = 0x80; + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } + + var bits = this._len * 8; + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; + + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } + + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash + }; + + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; + + var hash$3 = Hash$7; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits$f = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; + + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; + + Hash$6.call(this, 64, 56); + } + + inherits$f(Sha, Hash$6); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } + + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha$4 = Sha; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits$e = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; + + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); + } + + inherits$e(Sha1, Hash$5); + + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H + }; + + var sha1$1 = Sha1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$d = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; + + var K$2 = [ + 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 W$3 = new Array(64); + + function Sha256$1 () { + this.init(); + + this._w = W$3; // new Array(64) + + Hash$4.call(this, 64, 56); + } + + inherits$d(Sha256$1, Hash$4); + + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; + + return this + }; + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256$1.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; + + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); + + return H + }; + + var sha256$2 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$c = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; + + var W$2 = new Array(64); + + function Sha224 () { + this.init(); + + this._w = W$2; // new Array(64) + + Hash$3.call(this, 64, 56); + } + + inherits$c(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this + }; + + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); + + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H + }; + + var sha224 = Sha224; + + var inherits$b = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; + + var K$1 = [ + 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 W$1 = new Array(160); + + function Sha512 () { + this.init(); + this._w = W$1; + + Hash$2.call(this, 128, 112); + } + + inherits$b(Sha512, Hash$2); + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this + }; + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - dest.once('close', onclose); + Sha512.prototype._update = function (M) { + var W = this._w; - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; + + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - dest.once('finish', onfinish); + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - dest.emit('pipe', src); // start the flow if it hasn't been started already. + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); + W[i] = Wih; + W[i + 1] = Wil; } - return dest; - }; + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; - } + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - if (state.pipesCount === 0) return this; // just one destination. most common case. + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; - return this; - } // try to find the right one. + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + return H + }; - Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + var sha512 = Sha512; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + var inherits$a = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug$4('on readable', state.length, state.reading); + var W = new Array(160); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - nextTick(nReadingNextTick, this); - } - } - } + function Sha384 () { + this.init(); + this._w = W; - return res; - }; + Hash$1.call(this, 128, 112); + } - Readable.prototype.addListener = Readable.prototype.on; + inherits$a(Sha384, SHA512$2); - Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - return res; + return this }; - Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - return res; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H }; - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + var sha384 = Sha384; - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } - } + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + return new Algorithm() + }; - Readable.prototype.resume = function () { - var state = this._readableState; + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - if (!state.flowing) { - debug$4('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + var sha$3 = sha_js.exports; - state.flowing = !state.readableListening; - resume(this, state); - } + var inherits$8; + if (typeof Object.create === 'function'){ + inherits$8 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$8 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$9 = inherits$8; - state.paused = false; - return this; - }; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + 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; } - function resume_(stream, state) { - debug$4('resume', state.reading); + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } - if (!state.reading) { - stream.read(0); + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); } - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); + return deprecated; } - Readable.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } } + return debugs[set]; + } - this._readableState.paused = true; - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { + /** + * 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 + _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); + } + + // 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; } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. + } - Readable.prototype.wrap = function (stream) { - var _this = this; + function stylizeNoColor(str, styleType) { + return str; + } - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + function arrayToHash(array) { + var hash = {}; - _this.push(null); + array.forEach(function(val, idx) { + hash[val] = true; }); - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); + return hash; + } - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); + 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 !== 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); } - } // proxy certain important events. + return ret; + } + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - this._read = function (n) { - debug$4('wrapped _read', n); + // 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); + } - if (paused) { - paused = false; - stream.resume(); + // 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'); } - }; - - return this; - }; - - if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; + 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); + } + } - return createReadableStreamAsyncIterator(this); - }; - } + var base = '', array = false, braces = ['{', '}']; - Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; } - }); - Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; } - }); - Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); } - }); // exposed for testing purposes only. - Readable._fromList = fromList; - Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; + // 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]; } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); + 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 { - // read part of list - ret = state.buffer.consume(n, state.decoder); + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); } - return ret; + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); } - function endReadable(stream) { - var state = stream._readableState; - debug$4('endReadable', state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); + 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 endReadableNT(state, stream) { - debug$4('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } + 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; } - if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = fromBrowser; + + 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 from(Readable, iterable, opts); - }; + return name + ': ' + str; } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + 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 -1; + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } - var _stream_transform = Transform$3; - - var _require$codes$1 = errorsBrowser.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex = _stream_duplex; + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } - inherits_browser.exports(Transform$3, Duplex); + function isBoolean(arg) { + return typeof arg === 'boolean'; + } - function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + function isNull(arg) { + return arg === null; + } - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } + function isNumber(arg) { + return typeof arg === 'number'; + } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + function isString(arg) { + return typeof arg === 'string'; + } - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } + function isUndefined(arg) { + return arg === void 0; } - function Transform$3(options) { - if (!(this instanceof Transform$3)) return new Transform$3(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } - this._readableState.sync = false; + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + function isFunction(arg) { + return typeof arg === 'function'; + } - this.on('prefinish', prefinish); + function objectToString(o) { + return Object.prototype.toString.call(o); } - function prefinish() { - var _this = this; + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); + 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); } - Transform$3.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - Transform$3.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; }; - Transform$3.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - Transform$3.prototype._read = function (n) { - var ts = this._transformState; + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; + Readable.ReadableState = ReadableState; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + var debug$4 = debuglog('stream'); + inherits$9(Readable, EventEmitter$1); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; } - }; + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { - Transform$3.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; + options = options || {}; - function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; + } } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); - var _stream_passthrough = PassThrough; + this._readableState = new ReadableState(options, this); - var Transform$2 = _stream_transform; + // legacy + this.readable = true; - inherits_browser.exports(PassThrough, Transform$2); + if (options && typeof options.read === 'function') this._read = options.read; - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$2.call(this, options); + EventEmitter$1.call(this); } - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$l.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); }; - var eos; + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; - var _require$codes = errorsBrowser.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } + if (!addToFront) state.reading = false; - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want + if (state.needReadable) emitReadable(stream); + } + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); } - function call(fn) { - fn(); + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } - function pipe(from, to) { - return from.pipe(to); + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; } - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + n = howMuchToRead(n, state); - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } - var pipeline_1 = pipeline; + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - (function (module, exports) { - exports = module.exports = _stream_readable; - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - }(readableBrowser, readableBrowser.exports)); + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } - var Buffer$g = safeBuffer.exports.Buffer; - var Transform$1 = readableBrowser.exports.Transform; - var inherits$g = inherits_browser.exports; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + function emitReadable_(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } + state.readingMore = false; } - function HashBase$2 (blockSize) { - Transform$1.call(this); + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; - this._block = Buffer$g.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - this._finalized = false; - } + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - inherits$g(HashBase$2, Transform$1); + var doEnd = (!pipeOpts || pipeOpts.end !== false); - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - callback(error); - }; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + function onend() { + debug$4('onend'); + dest.end(); } - callback(error); - }; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } } - return this - }; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + // tell the dest that it's being piped to + dest.emit('pipe', src); - return digest - }; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') + return dest; }; - var hashBase = HashBase$2; + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } - var inherits$f = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - var ARRAY16$1 = new Array(16); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - function MD5$2 () { - HashBase$1.call(this, 64); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } + if (!dest) dest = state.pipes; - inherits$f(MD5$2, HashBase$1); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + // slow case. multiple pipe destinations. - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + dest.emit('unpipe', this); - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; + return this; }; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } - // produce result - var buffer = Buffer$f.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + return res; }; + Readable.prototype.addListener = Readable.prototype.on; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } } - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); + } - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } - var md5_js = MD5$2; - - var Buffer$e = require$$0__default["default"].Buffer; - var inherits$e = inherits_browser.exports; - var HashBase = hashBase; - - var ARRAY16 = new Array(16); - - var zl = [ - 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 zr = [ - 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 sl = [ - 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 sr = [ - 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 - ]; + Readable.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + function flow(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } - function RIPEMD160$3 () { - HashBase.call(this, 64); + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - inherits$e(RIPEMD160$3, HashBase); + self.push(null); + }); - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } + } - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; - } + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; + return self; }; - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + // exposed for testing purposes only. + Readable._fromList = fromList; - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer - }; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) + return ret; } - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$l.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } } - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } } - var ripemd160$2 = RIPEMD160$3; + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - var sha_js = {exports: {}}; + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - var Buffer$d = safeBuffer.exports.Buffer; + // A bit simpler than readable streams. + Writable.WritableState = WritableState; + inherits$9(Writable, events.exports.EventEmitter); - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); - } + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - accum += remainder; - offset += remainder; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - if ((accum % blockSize) === 0) { - this._update(block); - } - } + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - this._len += length; - return this - }; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - this._block[rem] = 0x80; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + // a flag to see when we're in the middle of a write. + this.writing = false; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } + // when true all writes will be buffered until .uncork() call + this.corked = 0; - var bits = this._len * 8; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - this._update(this._block); - var hash = this._hash(); + // the amount that is being written when _write is called. + this.writelen = 0; - return enc ? hash.toString(enc) : hash - }; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - var hash$3 = Hash$7; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - var inherits$d = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + // count buffered requests + this.bufferedRequestCount = 0; - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - var W$5 = new Array(80); + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { - function Sha () { - this.init(); - this._w = W$5; + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - Hash$6.call(this, 64, 56); - } + this._writableState = new WritableState(options, this); - inherits$d(Sha, Hash$6); + // legacy. + this.writable = true; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - return this - }; + if (typeof options.writev === 'function') this._writev = options.writev; + } - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) + events.exports.EventEmitter.call(this); } - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); } - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; } - Sha.prototype._update = function (M) { - var W = this._w; + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + if (typeof cb !== 'function') cb = nop; - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + return ret; }; - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + Writable.prototype.cork = function () { + var state = this._writableState; - return H + state.corked++; }; - var sha$4 = Sha; + Writable.prototype.uncork = function () { + var state = this._writableState; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + if (state.corked) { + state.corked--; - var inherits$c = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - var W$4 = new Array(80); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; + } - function Sha1 () { - this.init(); - this._w = W$4; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); - Hash$5.call(this, 64, 56); - } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - inherits$c(Sha1, Hash$5); + state.length += len; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - return this - }; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - function rotl1 (num) { - return (num << 1) | (num >>> 31) + return ret; } - function rotl5 (num) { - return (num << 5) | (num >>> 27) + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - function rotl30 (num) { - return (num << 30) | (num >>> 2) + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - Sha1.prototype._update = function (M) { - var W = this._w; + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + onwriteStateUpdate(state); - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } } + } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; - - var sha1$1 = Sha1; - - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - - var inherits$b = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; - - var K$2 = [ - 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 W$3 = new Array(64); - - function Sha256$1 () { - this.init(); - - this._w = W$3; // new Array(64) + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } - Hash$4.call(this, 64, 56); + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } } - inherits$b(Sha256$1, Hash$4); + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - return this - }; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } + if (entry === null) state.lastBufferedRequest = null; + } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - Sha256$1.prototype._update = function (M) { - var W = this._w; + Writable.prototype._writev = null; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); }; - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } - return H - }; + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } - var sha256$2 = Sha256$1; + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } - var inherits$a = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - var W$2 = new Array(64); + this.next = null; + this.entry = null; - function Sha224 () { - this.init(); + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } - this._w = W$2; // new Array(64) + inherits$9(Duplex, Readable); - Hash$3.call(this, 64, 56); + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - inherits$a(Sha224, Sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + Readable.call(this, options); + Writable.call(this, options); - return this - }; + if (options && options.readable === false) this.readable = false; - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + if (options && options.writable === false) this.writable = false; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - return H - }; + this.once('end', onend); + } - var sha224 = Sha224; + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - var inherits$9 = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } - var K$1 = [ - 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 onEndNT(self) { + self.end(); + } - var W$1 = new Array(160); + // a transform stream is a readable/writable stream where you do + inherits$9(Transform$1, Duplex); - function Sha512 () { - this.init(); - this._w = W$1; + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; - Hash$2.call(this, 128, 112); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; } - inherits$9(Sha512, Hash$2); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + var cb = ts.writecb; - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - return this - }; + ts.writechunk = null; + ts.writecb = null; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + if (data !== null && data !== undefined) stream.push(data); - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + cb(er); - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } + function Transform$1(options) { + if (!(this instanceof Transform$1)) return new Transform$1(options); - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + Duplex.call(this, options); - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + this._transformState = new TransformState(this); - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); } - Sha512.prototype._update = function (M) { - var W = this._w; + Transform$1.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$1.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + Transform$1.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$1.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + }; - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + function done(stream, er) { + if (er) return stream.emit('error', er); - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - W[i] = Wih; - W[i + 1] = Wil; - } + return stream.push(null); + } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + inherits$9(PassThrough, Transform$1); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + Transform$1.call(this, options); + } - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + inherits$9(Stream, EventEmitter$1); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform$1; + Stream.PassThrough = PassThrough; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + function Stream() { + EventEmitter$1.call(this); + } - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } } - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + source.on('data', ondata); - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + dest.on('drain', ondrain); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - var sha512 = Sha512; + dest.end(); + } - var inherits$8 = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; - var W = new Array(160); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - function Sha384 () { - this.init(); - this._w = W; + if (typeof dest.destroy === 'function') dest.destroy(); + } - Hash$1.call(this, 128, 112); - } + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - inherits$8(Sha384, SHA512$2); + source.on('error', onerror); + dest.on('error', onerror); - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + source.removeListener('end', onend); + source.removeListener('close', onclose); - return this - }; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + dest.removeListener('close', cleanup); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; + source.on('end', cleanup); + source.on('close', cleanup); - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + dest.on('close', cleanup); - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + dest.emit('pipe', source); - return new Algorithm() + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform$1, + PassThrough: PassThrough, + Stream: Stream + }); - var sha$3 = sha_js.exports; + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); var Buffer$6 = safeBuffer.exports.Buffer; - var Transform = require$$1__default["default"].Transform; - var StringDecoder = require$$2__default["default"].StringDecoder; + var Transform = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; var inherits$7 = inherits_browser.exports; function CipherBase (hashMode) { @@ -36626,7 +41365,7 @@ window.Buffer = buffer.Buffer; this.exchangeTimeout = 30000; this.unresponsiveTimeout = 15000; this.deviceModel = null; - this._events = new require$$0__default$1["default"](); + this._events = new EventEmitter$1(); /** * wrapper on top of exchange to simplify work of the implementation. * @param cla @@ -38379,7 +43118,7 @@ window.Buffer = buffer.Buffer; this.exchangeTimeout = 30000; this.unresponsiveTimeout = 15000; this.deviceModel = null; - this._events = new require$$0__default$1["default"](); + this._events = new EventEmitter$1(); this.send = async (cla, ins, p1, p2, data = Buffer$l.alloc(0), statusList = [StatusCodes.OK]) => { if (data.length >= 256) { From 9670f7252080f5c8006dd8abbb066d131551bf0e Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 11:38:43 +1100 Subject: [PATCH 22/78] update to named parameters --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index ca271e12..1025d0b7 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -767,7 +767,7 @@ $(document).ready(function() { } } else { - result = await appBtc.createPaymentTransactionNew(inputs, paths, undefined, outputsBuffer, undefined, undefined, undefined, timeStamp); + result = await appBtc.createPaymentTransactionNew(inputs=inputs, associatedKeysets=paths, outputScriptHex=outputsBuffer, initialTimestamp=timeStamp); callback(result); } } From 75d27829e959355ad593fc3d0fa427fcf36ccdeb Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 11:59:36 +1100 Subject: [PATCH 23/78] finish it --- js/cointoolkit.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 1025d0b7..d31d1ca5 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -767,7 +767,8 @@ $(document).ready(function() { } } else { - result = await appBtc.createPaymentTransactionNew(inputs=inputs, associatedKeysets=paths, outputScriptHex=outputsBuffer, initialTimestamp=timeStamp); + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp} + result = await appBtc.createPaymentTransactionNew(params); callback(result); } } From 3cc81a8ff2fc1387c8529e6b7e5af364baa328ca Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 12:07:57 +1100 Subject: [PATCH 24/78] extra additionals --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index d31d1ca5..dbdf29a2 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -767,7 +767,7 @@ $(document).ready(function() { } } else { - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp} + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, additionals: ["peercoin"]} result = await appBtc.createPaymentTransactionNew(params); callback(result); } From 7a83f8906f309ec4073f64355625f39e0bfa3543 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 17:20:11 +1100 Subject: [PATCH 25/78] no --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index dbdf29a2..c91883eb 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -729,7 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],!isPeercoin,!isPeercoin),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],!isPeercoin,isPeercoin),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From 8f2e956b5a5ac95798c49aaba80645052bf113e0 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 20 Jan 2022 17:35:06 +1100 Subject: [PATCH 26/78] fixups --- js/cointoolkit.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index c91883eb..69b6474a 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -748,7 +748,8 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - result = await appBtc.signP2SHTransaction(inputs, paths, outputsBuffer, undefined, hashType, false, undefined, timeStamp); + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, sigHashType: hashType, additionals: ["peercoin"]}; + result = await appBtc.signP2SHTransaction(params); var success=false; @@ -767,7 +768,7 @@ $(document).ready(function() { } } else { - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, additionals: ["peercoin"]} + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, additionals: ["peercoin"]}; result = await appBtc.createPaymentTransactionNew(params); callback(result); } From 1c7b054230056643cb6654b8b4f390deefa21c05 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 09:34:12 +1100 Subject: [PATCH 27/78] append hashType to signature to make it valid --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 69b6474a..c7d67c09 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -755,7 +755,7 @@ $(document).ready(function() { console.log("signature result",result); $.each(result, function(idx,itm) { - var signature = Crypto.util.hexToBytes(itm); + var signature = Crypto.util.hexToBytes(itm+hashType.toString(16)); if (currenttransaction.signmultisig(idx,undefined,signature.slice(-1)[0]*1,signature)) { success=true; } From e30c3e39bc07a3f69e3cac8824ecc4d19c752bc3 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 10:09:41 +1100 Subject: [PATCH 28/78] hmm --- js/cointoolkit.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index c7d67c09..57a7f3bc 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -755,8 +755,8 @@ $(document).ready(function() { console.log("signature result",result); $.each(result, function(idx,itm) { - var signature = Crypto.util.hexToBytes(itm+hashType.toString(16)); - if (currenttransaction.signmultisig(idx,undefined,signature.slice(-1)[0]*1,signature)) { + var signature = Crypto.util.hexToBytes(itm); + if (currenttransaction.signmultisig(idx,undefined,Crypto.util.hexToBytes(hashType.toString(16)),signature)) { success=true; } }); From 40d5573da38d1d11f613bace8d0bfb516241708f Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 10:42:23 +1100 Subject: [PATCH 29/78] maybe not --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 57a7f3bc..614fe8ae 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -755,7 +755,7 @@ $(document).ready(function() { console.log("signature result",result); $.each(result, function(idx,itm) { - var signature = Crypto.util.hexToBytes(itm); + var signature = Crypto.util.hexToBytes(itm+hashType.toString(16)); if (currenttransaction.signmultisig(idx,undefined,Crypto.util.hexToBytes(hashType.toString(16)),signature)) { success=true; } From e608a75aed243b01e7fa5d84050805f91d244f7e Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 13:58:54 +1100 Subject: [PATCH 30/78] new style for split --- js/cointoolkit.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 614fe8ae..0252c645 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -711,7 +711,8 @@ $(document).ready(function() { var path = coinjs.ledgerPath; console.log("path",path,"address",result.bitcoinAddress,"pubkey",result.publicKey); - var txn = appBtc.splitTransaction(currenttransaction.serialize(),false,isPeercoin); + var paramsSplit = {transactionHex=currenttransaction.serialize(), isSegwitSupported=false, hasTimestamp=isPeercoin, false, additionals=["peercoin"]} + var txn = appBtc.splitTransaction(paramsSplit); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); var inputs = []; @@ -729,7 +730,8 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],!isPeercoin,isPeercoin),currenttransaction.ins[result[1]].outpoint.index,script]); + var paramsSplit = {transactionHex=result[0], isSegwitSupported=false, hasTimestamp=isPeercoin, false, additionals=["peercoin"]} + inputs.push([result[1],appBtc.splitTransaction(paramsSplit),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From 02e8a2a61a9c0aa53e826c5050f007b3dd3ac5dd Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 15:01:47 +1100 Subject: [PATCH 31/78] oops --- js/cointoolkit.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 0252c645..e1f990f6 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -711,7 +711,7 @@ $(document).ready(function() { var path = coinjs.ledgerPath; console.log("path",path,"address",result.bitcoinAddress,"pubkey",result.publicKey); - var paramsSplit = {transactionHex=currenttransaction.serialize(), isSegwitSupported=false, hasTimestamp=isPeercoin, false, additionals=["peercoin"]} + var paramsSplit = {transactionHex=currenttransaction.serialize(), isSegwitSupported=false, hasTimestamp=isPeercoin, additionals=["peercoin"]} var txn = appBtc.splitTransaction(paramsSplit); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); @@ -730,7 +730,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - var paramsSplit = {transactionHex=result[0], isSegwitSupported=false, hasTimestamp=isPeercoin, false, additionals=["peercoin"]} + var paramsSplit = {transactionHex=result[0], isSegwitSupported=false, hasTimestamp=isPeercoin, additionals=["peercoin"]} inputs.push([result[1],appBtc.splitTransaction(paramsSplit),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { From 557c2bb48f129a563f8127598d2acd51d84eb55d Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 15:08:15 +1100 Subject: [PATCH 32/78] oops --- js/cointoolkit.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index e1f990f6..d6ca6426 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -711,7 +711,7 @@ $(document).ready(function() { var path = coinjs.ledgerPath; console.log("path",path,"address",result.bitcoinAddress,"pubkey",result.publicKey); - var paramsSplit = {transactionHex=currenttransaction.serialize(), isSegwitSupported=false, hasTimestamp=isPeercoin, additionals=["peercoin"]} + var paramsSplit = {transactionHex:currenttransaction.serialize(), isSegwitSupported:false, hasTimestamp:isPeercoin, additionals:["peercoin"]} var txn = appBtc.splitTransaction(paramsSplit); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); @@ -730,7 +730,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - var paramsSplit = {transactionHex=result[0], isSegwitSupported=false, hasTimestamp=isPeercoin, additionals=["peercoin"]} + var paramsSplit = {transactionHex:result[0], isSegwitSupported:false, hasTimestamp:isPeercoin, additionals:["peercoin"]} inputs.push([result[1],appBtc.splitTransaction(paramsSplit),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { From dc5e2bebe6a554871abaaa844fdef1ec74264740 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 16:55:54 +1100 Subject: [PATCH 33/78] no params --- js/cointoolkit.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index d6ca6426..5b3ed0ba 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -711,8 +711,7 @@ $(document).ready(function() { var path = coinjs.ledgerPath; console.log("path",path,"address",result.bitcoinAddress,"pubkey",result.publicKey); - var paramsSplit = {transactionHex:currenttransaction.serialize(), isSegwitSupported:false, hasTimestamp:isPeercoin, additionals:["peercoin"]} - var txn = appBtc.splitTransaction(paramsSplit); + var txn = appBtc.splitTransaction(currenttransaction.serialize(),false,isPeercoin,false,["peercoin"]); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); var inputs = []; @@ -730,8 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - var paramsSplit = {transactionHex:result[0], isSegwitSupported:false, hasTimestamp:isPeercoin, additionals:["peercoin"]} - inputs.push([result[1],appBtc.splitTransaction(paramsSplit),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From b7f9ba7a9ada39ae1e67b39180e3b926980490b1 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 21 Jan 2022 17:05:30 +1100 Subject: [PATCH 34/78] extra parm --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 5b3ed0ba..dfa74386 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -729,7 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From 6915410af03da4e0d2fac7d569b1f7b98ab2d25d Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 24 Jan 2022 14:01:13 +1100 Subject: [PATCH 35/78] trying original hw-app-btc app --- js/ledger.js | 19754 ++++++++++++++++++++++++------------------------- 1 file changed, 9491 insertions(+), 10263 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index ad61cb7f..e87d1215 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1033,12 +1033,12 @@ window.Buffer = buffer.Buffer; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$l.TYPED_ARRAY_SUPPORT + return Buffer$m.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1047,14 +1047,14 @@ window.Buffer = buffer.Buffer; if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$l(length); + that = new Buffer$m(length); } that.length = length; } @@ -1072,9 +1072,9 @@ window.Buffer = buffer.Buffer; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$l (arg, encodingOrOffset, length) { - if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { - return new Buffer$l(arg, encodingOrOffset, length) + function Buffer$m (arg, encodingOrOffset, length) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { + return new Buffer$m(arg, encodingOrOffset, length) } // Common case. @@ -1089,11 +1089,11 @@ window.Buffer = buffer.Buffer; return from$1(this, arg, encodingOrOffset, length) } - Buffer$l.poolSize = 8192; // not used by this implementation + Buffer$m.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$l._augment = function (arr) { - arr.__proto__ = Buffer$l.prototype; + Buffer$m._augment = function (arr) { + arr.__proto__ = Buffer$m.prototype; return arr }; @@ -1121,13 +1121,13 @@ window.Buffer = buffer.Buffer; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$l.from = function (value, encodingOrOffset, length) { + Buffer$m.from = function (value, encodingOrOffset, length) { return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { - Buffer$l.prototype.__proto__ = Uint8Array.prototype; - Buffer$l.__proto__ = Uint8Array; + if (Buffer$m.TYPED_ARRAY_SUPPORT) { + Buffer$m.prototype.__proto__ = Uint8Array.prototype; + Buffer$m.__proto__ = Uint8Array; } function assertSize (size) { @@ -1158,14 +1158,14 @@ window.Buffer = buffer.Buffer; * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$l.alloc = function (size, fill, encoding) { + Buffer$m.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1176,13 +1176,13 @@ window.Buffer = buffer.Buffer; /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$l.allocUnsafe = function (size) { + Buffer$m.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$l.allocUnsafeSlow = function (size) { + Buffer$m.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1191,7 +1191,7 @@ window.Buffer = buffer.Buffer; encoding = 'utf8'; } - if (!Buffer$l.isEncoding(encoding)) { + if (!Buffer$m.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1238,10 +1238,10 @@ window.Buffer = buffer.Buffer; array = new Uint8Array(array, byteOffset, length); } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1288,12 +1288,12 @@ window.Buffer = buffer.Buffer; } return length | 0 } - Buffer$l.isBuffer = isBuffer; + Buffer$m.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$l.compare = function compare (a, b) { + Buffer$m.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1316,7 +1316,7 @@ window.Buffer = buffer.Buffer; return 0 }; - Buffer$l.isEncoding = function isEncoding (encoding) { + Buffer$m.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1335,13 +1335,13 @@ window.Buffer = buffer.Buffer; } }; - Buffer$l.concat = function concat (list, length) { + Buffer$m.concat = function concat (list, length) { if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$l.alloc(0) + return Buffer$m.alloc(0) } var i; @@ -1352,7 +1352,7 @@ window.Buffer = buffer.Buffer; } } - var buffer = Buffer$l.allocUnsafe(length); + var buffer = Buffer$m.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1408,7 +1408,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$l.byteLength = byteLength$1; + Buffer$m.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1482,7 +1482,7 @@ window.Buffer = buffer.Buffer; // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$l.prototype._isBuffer = true; + Buffer$m.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1490,7 +1490,7 @@ window.Buffer = buffer.Buffer; b[m] = i; } - Buffer$l.prototype.swap16 = function swap16 () { + Buffer$m.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1501,7 +1501,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.swap32 = function swap32 () { + Buffer$m.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1513,7 +1513,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.swap64 = function swap64 () { + Buffer$m.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1527,20 +1527,20 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.toString = function toString () { + Buffer$m.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$l.prototype.equals = function equals (b) { + Buffer$m.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$l.compare(this, b) === 0 + return Buffer$m.compare(this, b) === 0 }; - Buffer$l.prototype.inspect = function inspect () { + Buffer$m.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1550,7 +1550,7 @@ window.Buffer = buffer.Buffer; return '' }; - Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1649,7 +1649,7 @@ window.Buffer = buffer.Buffer; // Normalize val if (typeof val === 'string') { - val = Buffer$l.from(val, encoding); + val = Buffer$m.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1661,7 +1661,7 @@ window.Buffer = buffer.Buffer; return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$l.TYPED_ARRAY_SUPPORT && + if (Buffer$m.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1731,15 +1731,15 @@ window.Buffer = buffer.Buffer; return -1 } - Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1790,7 +1790,7 @@ window.Buffer = buffer.Buffer; return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$l.prototype.write = function write (string, offset, length, encoding) { + Buffer$m.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1862,7 +1862,7 @@ window.Buffer = buffer.Buffer; } }; - Buffer$l.prototype.toJSON = function toJSON () { + Buffer$m.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2015,7 +2015,7 @@ window.Buffer = buffer.Buffer; return res } - Buffer$l.prototype.slice = function slice (start, end) { + Buffer$m.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2037,12 +2037,12 @@ window.Buffer = buffer.Buffer; if (end < start) end = start; var newBuf; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$l.prototype; + newBuf.__proto__ = Buffer$m.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$l(sliceLen, undefined); + newBuf = new Buffer$m(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2059,7 +2059,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2074,7 +2074,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2090,22 +2090,22 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2114,7 +2114,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] * 0x1000000) }; - Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2123,7 +2123,7 @@ window.Buffer = buffer.Buffer; this[offset + 3]) }; - Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2141,7 +2141,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2159,25 +2159,25 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2186,7 +2186,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] << 24) }; - Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2195,22 +2195,22 @@ window.Buffer = buffer.Buffer; (this[offset + 3]) }; - Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2221,7 +2221,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2240,7 +2240,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2259,11 +2259,11 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2276,11 +2276,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2289,11 +2289,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2309,11 +2309,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2324,11 +2324,11 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2339,7 +2339,7 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2362,7 +2362,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2385,21 +2385,21 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2408,11 +2408,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2421,11 +2421,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2436,12 +2436,12 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$m.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; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2465,11 +2465,11 @@ window.Buffer = buffer.Buffer; return offset + 4 } - Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2481,16 +2481,16 @@ window.Buffer = buffer.Buffer; return offset + 8 } - Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2522,7 +2522,7 @@ window.Buffer = buffer.Buffer; for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2542,7 +2542,7 @@ window.Buffer = buffer.Buffer; // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$l.prototype.fill = function fill (val, start, end, encoding) { + Buffer$m.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2562,7 +2562,7 @@ window.Buffer = buffer.Buffer; if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2591,7 +2591,7 @@ window.Buffer = buffer.Buffer; } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$l(val, encoding).toString()); + : utf8ToBytes(new Buffer$m(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5751,7 +5751,7 @@ window.Buffer = buffer.Buffer; function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require$2 = buffer, - Buffer$k = _require$2.Buffer; + Buffer$l = _require$2.Buffer; var _require2 = require$$3, inspect$1 = _require2.inspect; @@ -5759,7 +5759,7 @@ window.Buffer = buffer.Buffer; var custom = inspect$1 && inspect$1.custom || 'inspect'; function copyBuffer(src, target, offset) { - Buffer$k.prototype.copy.call(src, target, offset); + Buffer$l.prototype.copy.call(src, target, offset); } var buffer_list = @@ -5826,8 +5826,8 @@ window.Buffer = buffer.Buffer; }, { key: "concat", value: function concat(n) { - if (this.length === 0) return Buffer$k.alloc(0); - var ret = Buffer$k.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer$l.alloc(0); + var ret = Buffer$l.allocUnsafe(n >>> 0); var p = this.head; var i = 0; @@ -5901,7 +5901,7 @@ window.Buffer = buffer.Buffer; }, { key: "_getBuffer", value: function _getBuffer(n) { - var ret = Buffer$k.allocUnsafe(n); + var ret = Buffer$l.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); @@ -6308,16 +6308,16 @@ window.Buffer = buffer.Buffer; /**/ - var Buffer$j = buffer.Buffer; + var Buffer$k = buffer.Buffer; var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer$1(chunk) { - return Buffer$j.from(chunk); + return Buffer$k.from(chunk); } function _isUint8Array$1(obj) { - return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; } var destroyImpl$1 = destroy_1; @@ -6532,7 +6532,7 @@ window.Buffer = buffer.Buffer; var isBuf = !state.objectMode && _isUint8Array$1(chunk); - if (isBuf && !Buffer$j.isBuffer(chunk)) { + if (isBuf && !Buffer$k.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer$1(chunk); } @@ -6583,7 +6583,7 @@ window.Buffer = buffer.Buffer; function decodeChunk$1(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$j.from(chunk, encoding); + chunk = Buffer$k.from(chunk, encoding); } return chunk; @@ -7052,14 +7052,14 @@ window.Buffer = buffer.Buffer; } }); - var string_decoder = {}; + var string_decoder$1 = {}; /**/ - var Buffer$i = safeBuffer.exports.Buffer; + var Buffer$j = safeBuffer.exports.Buffer; /**/ - var isEncoding = Buffer$i.isEncoding || function (encoding) { + var isEncoding = Buffer$j.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': @@ -7100,15 +7100,15 @@ window.Buffer = buffer.Buffer; // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + if (typeof nenc !== 'string' && (Buffer$j.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. - var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(encoding) { + string_decoder$1.StringDecoder = StringDecoder$3; + function StringDecoder$3(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { @@ -7133,10 +7133,10 @@ window.Buffer = buffer.Buffer; } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer$i.allocUnsafe(nb); + this.lastChar = Buffer$j.allocUnsafe(nb); } - StringDecoder$2.prototype.write = function (buf) { + StringDecoder$3.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; @@ -7152,13 +7152,13 @@ window.Buffer = buffer.Buffer; return r || ''; }; - StringDecoder$2.prototype.end = utf8End; + StringDecoder$3.prototype.end = utf8End; // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; + StringDecoder$3.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.prototype.fillLast = function (buf) { + StringDecoder$3.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); @@ -7661,28 +7661,28 @@ window.Buffer = buffer.Buffer; /**/ - var Buffer$h = buffer.Buffer; + var Buffer$i = buffer.Buffer; var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { - return Buffer$h.from(chunk); + return Buffer$i.from(chunk); } function _isUint8Array(obj) { - return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = require$$3; - var debug$5; + var debug$9; if (debugUtil && debugUtil.debuglog) { - debug$5 = debugUtil.debuglog('stream'); + debug$9 = debugUtil.debuglog('stream'); } else { - debug$5 = function debug() {}; + debug$9 = function debug() {}; } /**/ @@ -7701,7 +7701,7 @@ window.Buffer = buffer.Buffer; ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - var StringDecoder$1; + var StringDecoder$2; var createReadableStreamAsyncIterator; var from; @@ -7778,8 +7778,8 @@ window.Buffer = buffer.Buffer; this.encoding = null; if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + this.decoder = new StringDecoder$2(options.encoding); this.encoding = options.encoding; } } @@ -7846,7 +7846,7 @@ window.Buffer = buffer.Buffer; encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$h.from(chunk, encoding); + chunk = Buffer$i.from(chunk, encoding); encoding = ''; } @@ -7865,7 +7865,7 @@ window.Buffer = buffer.Buffer; }; function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$5('readableAddChunk', chunk); + debug$9('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { @@ -7878,7 +7878,7 @@ window.Buffer = buffer.Buffer; if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { chunk = _uint8ArrayToBuffer(chunk); } @@ -7940,8 +7940,8 @@ window.Buffer = buffer.Buffer; Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + var decoder = new StringDecoder$2(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: @@ -8008,7 +8008,7 @@ window.Buffer = buffer.Buffer; Readable$1.prototype.read = function (n) { - debug$5('read', n); + debug$9('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -8017,7 +8017,7 @@ window.Buffer = buffer.Buffer; // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$5('read: emitReadable', state.length, state.ended); + debug$9('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); return null; } @@ -8052,20 +8052,20 @@ window.Buffer = buffer.Buffer; var doRead = state.needReadable; - debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$5('length less than watermark', doRead); + debug$9('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$5('reading or ended', doRead); + debug$9('reading or ended', doRead); } else if (doRead) { - debug$5('do read'); + debug$9('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -8103,7 +8103,7 @@ window.Buffer = buffer.Buffer; }; function onEofChunk$1(stream, state) { - debug$5('onEofChunk'); + debug$9('onEofChunk'); if (state.ended) return; if (state.decoder) { @@ -8138,11 +8138,11 @@ window.Buffer = buffer.Buffer; function emitReadable$1(stream) { var state = stream._readableState; - debug$5('emitReadable', state.needReadable, state.emittedReadable); + debug$9('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { - debug$5('emitReadable', state.flowing); + debug$9('emitReadable', state.flowing); state.emittedReadable = true; nextTick(emitReadable_$1, stream); } @@ -8150,7 +8150,7 @@ window.Buffer = buffer.Buffer; function emitReadable_$1(stream) { var state = stream._readableState; - debug$5('emitReadable_', state.destroyed, state.length, state.ended); + debug$9('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); @@ -8206,7 +8206,7 @@ window.Buffer = buffer.Buffer; // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; - debug$5('maybeReadMore read 0'); + debug$9('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; @@ -8242,14 +8242,14 @@ window.Buffer = buffer.Buffer; } state.pipesCount += 1; - debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { - debug$5('onunpipe'); + debug$9('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { @@ -8260,7 +8260,7 @@ window.Buffer = buffer.Buffer; } function onend() { - debug$5('onend'); + debug$9('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() @@ -8273,7 +8273,7 @@ window.Buffer = buffer.Buffer; var cleanedUp = false; function cleanup() { - debug$5('cleanup'); // cleanup event handlers once the pipe is broken + debug$9('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -8295,9 +8295,9 @@ window.Buffer = buffer.Buffer; src.on('data', ondata); function ondata(chunk) { - debug$5('ondata'); + debug$9('ondata'); var ret = dest.write(chunk); - debug$5('dest.write', ret); + debug$9('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible @@ -8305,7 +8305,7 @@ window.Buffer = buffer.Buffer; // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$5('false write response, pause', state.awaitDrain); + debug$9('false write response, pause', state.awaitDrain); state.awaitDrain++; } @@ -8316,7 +8316,7 @@ window.Buffer = buffer.Buffer; function onerror(er) { - debug$5('onerror', er); + debug$9('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); @@ -8333,7 +8333,7 @@ window.Buffer = buffer.Buffer; dest.once('close', onclose); function onfinish() { - debug$5('onfinish'); + debug$9('onfinish'); dest.removeListener('close', onclose); unpipe(); } @@ -8341,7 +8341,7 @@ window.Buffer = buffer.Buffer; dest.once('finish', onfinish); function unpipe() { - debug$5('unpipe'); + debug$9('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to @@ -8349,7 +8349,7 @@ window.Buffer = buffer.Buffer; dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { - debug$5('pipe resume'); + debug$9('pipe resume'); src.resume(); } @@ -8359,7 +8359,7 @@ window.Buffer = buffer.Buffer; function pipeOnDrain$1(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; - debug$5('pipeOnDrain', state.awaitDrain); + debug$9('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { @@ -8434,7 +8434,7 @@ window.Buffer = buffer.Buffer; state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; - debug$5('on readable', state.length, state.reading); + debug$9('on readable', state.length, state.reading); if (state.length) { emitReadable$1(this); @@ -8495,7 +8495,7 @@ window.Buffer = buffer.Buffer; } function nReadingNextTick$1(self) { - debug$5('readable nexttick read 0'); + debug$9('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. @@ -8505,7 +8505,7 @@ window.Buffer = buffer.Buffer; var state = this._readableState; if (!state.flowing) { - debug$5('resume'); // we flow only if there is no one listening + debug$9('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() @@ -8525,7 +8525,7 @@ window.Buffer = buffer.Buffer; } function resume_$1(stream, state) { - debug$5('resume', state.reading); + debug$9('resume', state.reading); if (!state.reading) { stream.read(0); @@ -8538,10 +8538,10 @@ window.Buffer = buffer.Buffer; } Readable$1.prototype.pause = function () { - debug$5('call pause flowing=%j', this._readableState.flowing); + debug$9('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { - debug$5('pause'); + debug$9('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -8552,7 +8552,7 @@ window.Buffer = buffer.Buffer; function flow$1(stream) { var state = stream._readableState; - debug$5('flow', state.flowing); + debug$9('flow', state.flowing); while (state.flowing && stream.read() !== null) { } @@ -8567,7 +8567,7 @@ window.Buffer = buffer.Buffer; var state = this._readableState; var paused = false; stream.on('end', function () { - debug$5('wrapped end'); + debug$9('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); @@ -8577,7 +8577,7 @@ window.Buffer = buffer.Buffer; _this.push(null); }); stream.on('data', function (chunk) { - debug$5('wrapped data'); + debug$9('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; @@ -8609,7 +8609,7 @@ window.Buffer = buffer.Buffer; this._read = function (n) { - debug$5('wrapped _read', n); + debug$9('wrapped _read', n); if (paused) { paused = false; @@ -8694,7 +8694,7 @@ window.Buffer = buffer.Buffer; function endReadable$1(stream) { var state = stream._readableState; - debug$5('endReadable', state.endEmitted); + debug$9('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; @@ -8703,7 +8703,7 @@ window.Buffer = buffer.Buffer; } function endReadableNT$1(state, stream) { - debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; @@ -9000,12 +9000,12 @@ window.Buffer = buffer.Buffer; exports.pipeline = pipeline_1; }(readableBrowser, readableBrowser.exports)); - var Buffer$g = safeBuffer.exports.Buffer; + var Buffer$h = safeBuffer.exports.Buffer; var Transform$2 = readableBrowser.exports.Transform; var inherits$i = inherits_browser.exports; function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer') } } @@ -9013,7 +9013,7 @@ window.Buffer = buffer.Buffer; function HashBase$2 (blockSize) { Transform$2.call(this); - this._block = Buffer$g.allocUnsafe(blockSize); + this._block = Buffer$h.allocUnsafe(blockSize); this._blockSize = blockSize; this._blockOffset = 0; this._length = [0, 0, 0, 0]; @@ -9048,7 +9048,7 @@ window.Buffer = buffer.Buffer; HashBase$2.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data'); if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); // consume data var block = this._block; @@ -9097,7 +9097,7 @@ window.Buffer = buffer.Buffer; var inherits$h = inherits_browser.exports; var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + var Buffer$g = safeBuffer.exports.Buffer; var ARRAY16$1 = new Array(16); @@ -9211,7 +9211,7 @@ window.Buffer = buffer.Buffer; this._update(); // produce result - var buffer = Buffer$f.allocUnsafe(16); + var buffer = Buffer$g.allocUnsafe(16); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9241,7 +9241,7 @@ window.Buffer = buffer.Buffer; var md5_js = MD5$2; - var Buffer$e = buffer.Buffer; + var Buffer$f = buffer.Buffer; var inherits$g = inherits_browser.exports; var HashBase = hashBase; @@ -9369,7 +9369,7 @@ window.Buffer = buffer.Buffer; this._update(); // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9406,11 +9406,11 @@ window.Buffer = buffer.Buffer; var sha_js = {exports: {}}; - var Buffer$d = safeBuffer.exports.Buffer; + var Buffer$e = safeBuffer.exports.Buffer; // prototype class for hash functions function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); + this._block = Buffer$e.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; @@ -9419,7 +9419,7 @@ window.Buffer = buffer.Buffer; Hash$7.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); + data = Buffer$e.from(data, enc); } var block = this._block; @@ -9498,7 +9498,7 @@ window.Buffer = buffer.Buffer; var inherits$f = inherits_browser.exports; var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + var Buffer$d = safeBuffer.exports.Buffer; var K$4 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9570,7 +9570,7 @@ window.Buffer = buffer.Buffer; }; Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + var H = Buffer$d.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9594,7 +9594,7 @@ window.Buffer = buffer.Buffer; var inherits$e = inherits_browser.exports; var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + var Buffer$c = safeBuffer.exports.Buffer; var K$3 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9670,7 +9670,7 @@ window.Buffer = buffer.Buffer; }; Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + var H = Buffer$c.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9693,7 +9693,7 @@ window.Buffer = buffer.Buffer; var inherits$d = inherits_browser.exports; var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + var Buffer$b = safeBuffer.exports.Buffer; var K$2 = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, @@ -9803,7 +9803,7 @@ window.Buffer = buffer.Buffer; }; Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); + var H = Buffer$b.allocUnsafe(32); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9830,7 +9830,7 @@ window.Buffer = buffer.Buffer; var inherits$c = inherits_browser.exports; var Sha256 = sha256$2; var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + var Buffer$a = safeBuffer.exports.Buffer; var W$2 = new Array(64); @@ -9858,7 +9858,7 @@ window.Buffer = buffer.Buffer; }; Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + var H = Buffer$a.allocUnsafe(28); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9875,7 +9875,7 @@ window.Buffer = buffer.Buffer; var inherits$b = inherits_browser.exports; var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + var Buffer$9 = safeBuffer.exports.Buffer; var K$1 = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, @@ -10113,7 +10113,7 @@ window.Buffer = buffer.Buffer; }; Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + var H = Buffer$9.allocUnsafe(64); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10137,7 +10137,7 @@ window.Buffer = buffer.Buffer; var inherits$a = inherits_browser.exports; var SHA512$2 = sha512; var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; + var Buffer$8 = safeBuffer.exports.Buffer; var W = new Array(160); @@ -10173,7 +10173,7 @@ window.Buffer = buffer.Buffer; }; Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + var H = Buffer$8.allocUnsafe(48); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10768,9 +10768,234 @@ window.Buffer = buffer.Buffer; return ret; }; + var string_decoder = {}; + + var StringDecoder_1; + // 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$7 = buffer.Buffer; + + var isBufferEncoding = Buffer$7.isEncoding + || function(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 assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$7(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; + + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$1.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder$1.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + Readable.ReadableState = ReadableState; - var debug$4 = debuglog('stream'); + var debug$8 = debuglog('stream'); inherits$9(Readable, EventEmitter$1); function prependListener(emitter, event, fn) { @@ -10884,7 +11109,7 @@ window.Buffer = buffer.Buffer; if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$l.from(chunk, encoding); + chunk = Buffer$m.from(chunk, encoding); encoding = ''; } } @@ -11009,7 +11234,7 @@ window.Buffer = buffer.Buffer; // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { - debug$4('read', n); + debug$8('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -11020,7 +11245,7 @@ window.Buffer = buffer.Buffer; // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); + debug$8('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } @@ -11057,21 +11282,21 @@ window.Buffer = buffer.Buffer; // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; - debug$4('need readable', doRead); + debug$8('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$4('length less than watermark', doRead); + debug$8('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$4('reading or ended', doRead); + debug$8('reading or ended', doRead); } else if (doRead) { - debug$4('do read'); + debug$8('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -11138,14 +11363,14 @@ window.Buffer = buffer.Buffer; var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); + debug$8('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { - debug$4('emit readable'); + debug$8('emit readable'); stream.emit('readable'); flow(stream); } @@ -11166,7 +11391,7 @@ window.Buffer = buffer.Buffer; function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); + debug$8('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. @@ -11199,7 +11424,7 @@ window.Buffer = buffer.Buffer; break; } state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false); @@ -11208,14 +11433,14 @@ window.Buffer = buffer.Buffer; dest.on('unpipe', onunpipe); function onunpipe(readable) { - debug$4('onunpipe'); + debug$8('onunpipe'); if (readable === src) { cleanup(); } } function onend() { - debug$4('onend'); + debug$8('onend'); dest.end(); } @@ -11228,7 +11453,7 @@ window.Buffer = buffer.Buffer; var cleanedUp = false; function cleanup() { - debug$4('cleanup'); + debug$8('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -11256,7 +11481,7 @@ window.Buffer = buffer.Buffer; var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { - debug$4('ondata'); + debug$8('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { @@ -11265,7 +11490,7 @@ window.Buffer = buffer.Buffer; // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); + debug$8('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } @@ -11276,7 +11501,7 @@ window.Buffer = buffer.Buffer; // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { - debug$4('onerror', er); + debug$8('onerror', er); unpipe(); dest.removeListener('error', onerror); if (listenerCount(dest, 'error') === 0) dest.emit('error', er); @@ -11292,14 +11517,14 @@ window.Buffer = buffer.Buffer; } dest.once('close', onclose); function onfinish() { - debug$4('onfinish'); + debug$8('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { - debug$4('unpipe'); + debug$8('unpipe'); src.unpipe(dest); } @@ -11308,7 +11533,7 @@ window.Buffer = buffer.Buffer; // start the flow if it hasn't been started already. if (!state.flowing) { - debug$4('pipe resume'); + debug$8('pipe resume'); src.resume(); } @@ -11318,7 +11543,7 @@ window.Buffer = buffer.Buffer; function pipeOnDrain(src) { return function () { var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); + debug$8('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && src.listeners('data').length) { state.flowing = true; @@ -11402,7 +11627,7 @@ window.Buffer = buffer.Buffer; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); + debug$8('readable nexttick read 0'); self.read(0); } @@ -11411,7 +11636,7 @@ window.Buffer = buffer.Buffer; Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { - debug$4('resume'); + debug$8('resume'); state.flowing = true; resume(this, state); } @@ -11427,7 +11652,7 @@ window.Buffer = buffer.Buffer; function resume_(stream, state) { if (!state.reading) { - debug$4('resume read 0'); + debug$8('resume read 0'); stream.read(0); } @@ -11439,9 +11664,9 @@ window.Buffer = buffer.Buffer; } Readable.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); + debug$8('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { - debug$4('pause'); + debug$8('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -11450,7 +11675,7 @@ window.Buffer = buffer.Buffer; function flow(stream) { var state = stream._readableState; - debug$4('flow', state.flowing); + debug$8('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } @@ -11463,7 +11688,7 @@ window.Buffer = buffer.Buffer; var self = this; stream.on('end', function () { - debug$4('wrapped end'); + debug$8('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); @@ -11473,7 +11698,7 @@ window.Buffer = buffer.Buffer; }); stream.on('data', function (chunk) { - debug$4('wrapped data'); + debug$8('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode @@ -11507,7 +11732,7 @@ window.Buffer = buffer.Buffer; // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function (n) { - debug$4('wrapped _read', n); + debug$8('wrapped _read', n); if (paused) { paused = false; stream.resume(); @@ -11594,7 +11819,7 @@ window.Buffer = buffer.Buffer; // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { - var ret = Buffer$l.allocUnsafe(n); + var ret = Buffer$m.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -12738,7 +12963,7 @@ window.Buffer = buffer.Buffer; var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$l.alloc(1 + paths.length * 4); + var buffer = Buffer$m.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -12927,7 +13152,7 @@ window.Buffer = buffer.Buffer; } crypto$5.hmacSHA512 = hmacSHA512; - var bn$1 = {exports: {}}; + var bn = {exports: {}}; (function (module) { (function (module, exports) { @@ -16373,7 +16598,7 @@ window.Buffer = buffer.Buffer; return res._forceRed(this); }; })(module, commonjsGlobal); - }(bn$1)); + }(bn)); var elliptic = {}; @@ -16450,4579 +16675,1131 @@ window.Buffer = buffer.Buffer; var utils$n = {}; - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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; - } + var minimalisticAssert = assert$f; - // BN + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; - this.negative = 0; - this.words = null; - this.length = 0; + var utils$m = {}; - // Reduction context - this.red = null; + (function (exports) { - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + var utils = exports; - this._init(number || 0, base || 10, endian || 'be'); - } + 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 (typeof module === 'object') { - module.exports = BN; + 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 { - 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 = require('buffer').Buffer; + 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); } - } catch (e) { } + return res; + } + utils.toArray = toArray; - 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); - }; + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils.zero2 = zero2; - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + }(utils$m)); - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + (function (exports) { - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } + // 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); - 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); - } - } - } - }; + var ws = 1 << (w + 1); + var k = num.clone(); - 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; + 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 { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; + z = 0; } - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + naf[i] = z; + k.iushrn(1); + } - 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; - } + return naf; + } + utils.getNAF = getNAF; - 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; - } + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; - 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++; - } - } + 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; } - return this.strip(); - }; + jsf[0].push(u1); - 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' + var u2; + if ((m24 & 1) === 0) { + u2 = 0; } else { - return (c - 48) & 0xf; + m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; } - } + jsf[1].push(u2); - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); } - 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; - } - } - } + return jsf; + } + utils.getJSF = getJSF; - this.strip(); + 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 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; + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; + } + utils.parseBytes = parseBytes; - r *= mul; + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); + } + utils.intFromLE = intFromLE; + }(utils$n)); - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + var brorand = {exports: {}}; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + var r$1; - // '0' - '9' - } else { - r += c; - } - } - return r; - } + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + return r$1.generate(len); + }; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + function Rand(rand) { + this.rand = rand; + } + brorand.exports.Rand = Rand; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + Rand.prototype.generate = function generate(len) { + return this._rand(len); + }; - 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); - } - } + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; - for (i = 0; i < mod; i++) { - pow *= base; - } + 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; + }; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + // 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$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); - this.strip(); - }; + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { + } + } - 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; - }; + var curve = {}; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); - // 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(); - }; + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + // Curve configuration, optional + this.n = conf.n && new BN$8(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); - var zeros = []; - var groupSizes = []; - var groupBases = []; + this._bitLength = this.n ? this.n.bitLength() : 0; - 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; + // 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); } + } + var base = BaseCurve; - */ + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); + }; - 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' - ]; + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); + }; - 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 - ]; + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$e(p.precomputed); + var doubles = p._getDoubles(); - 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 - ]; + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + // 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 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; + 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(); + }; - 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); + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; - 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; - } + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; - assert(false, 'Base should be between 2 and 36'); - }; + // Get NAF form + var naf = getNAF(k, w, this._bitLength); - 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'); + // 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$e(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 (this.negative !== 0) ? -ret : ret; - }; + } + return p.type === 'affine' ? acc.toP() : acc; + }; - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; + // 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; + } - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + // 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; + } - 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'); + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + // 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 b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + 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 */ + ]; - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + 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; - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } - res[i] = b; - } + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; - for (; i < reqLength; i++) { - res[i] = 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; - return res; - }; + for (j = 0; j < len; j++) { + var z = tmp[j]; + 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 (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; - }; + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } } + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + if (jacobianResult) + return acc; + else + return acc.toP(); + }; - 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; - }; + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; + } + BaseCurve.BasePoint = BasePoint; - // 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; - }; + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; - function toBitArray (num) { - var w = new Array(num.bitLength()); + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils$l.toArray(bytes, enc); - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + var len = this.p.byteLength(); - return w; + // 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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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'); + }; - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; - 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; - }; + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); + }; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + BasePoint.prototype.encode = function encode(enc, compact) { + return utils$l.encode(this._encode(compact), enc); + }; - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); + 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; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + return this; + }; - return this; - }; + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + var doubles = this.precomputed.doubles; + if (!doubles) + return false; - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + }; - return this.strip(); - }; + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); + 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, }; + }; - // 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); - }; + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); + 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, }; + }; - // 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; - } + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; - this.length = b.length; + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; - return this.strip(); - }; + var assert$d = utils$k.assert; - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); - // 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); - }; + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - // 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; - } + // 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$3(ShortCurve, Base$2); + var short = ShortCurve; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } + } - this.length = a.length; + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN$7(vec.a, 16), + b: new BN$7(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } - return this.strip(); + return { + beta: beta, + lambda: lambda, + basis: basis, }; + }; - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; + 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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); - // 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); - }; + var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; + }; - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(1); - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + // 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; - if (bitsLeft > 0) { - bytesNeeded--; - } + 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)); - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; } + prevR = r; - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; - // And remove leading zeroes - return this.strip(); - }; + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; + }; - var off = (bit / 26) | 0; - var wbit = bit % 26; + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; - this._expand(off + 1); + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); - return this.strip(); - }; + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$7(x, 16); + if (!x.red) + x = x.toRed(this.red); - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + 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'); - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + // 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(); - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return this.point(x, y); + }; - 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; - } + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; - 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]; - } - } + var x = point.x; + var y = point.y; - return this; - }; + 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; + }; - // 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; + 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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - if (this.length > num.length) return this.clone().iadd(num); + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; - return num.clone().iadd(this); + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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; + }; - // 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(); + Point$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; - // At this point both numbers are positive - var cmp = this.cmp(num); + Point$2.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + // P + O = P + if (p.inf) + return this; - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + // P + P = 2P + if (this.eq(p)) + return this.dbl(); - 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; - } + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); - this.length = Math.max(this.length, i); + 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); + }; - if (a !== this) { - this.negative = 1; - } + Point$2.prototype.dbl = function dbl() { + if (this.inf) + return this; - return this.strip(); - }; + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + var a = this.curve.a; - 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; + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - // 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 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); + }; - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + Point$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; - 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--; - } + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; - return out.strip(); + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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; + }; - // 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) ; 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); - }; - })(module, commonjsGlobal); - }(bn)); - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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; - }; - }(utils$m)); - - (function (exports) { - - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; - - 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; - }(utils$n)); - - var brorand = {exports: {}}; - - var r$1; - - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); - }; - - function Rand(rand) { - this.rand = rand; - } - brorand.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$4 = require('crypto'); - if (typeof crypto$4.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto$4.randomBytes(n); - }; - } catch (e) { - } - } - - var curve = {}; - - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; - - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN$8(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); - } - } - var base = 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$e(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$e(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]; - 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(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$l.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; - }; - - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$3 = inherits_browser.exports; - var Base$2 = base; - - var assert$d = utils$k.assert; - - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); - - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(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$3(ShortCurve, Base$2); - var short = 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$7(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$7(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$d(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$7(vec.a, 16), - b: new BN$7(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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN$7(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$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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$2.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$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + Point$2.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; @@ -24451,16 +21228,16 @@ window.Buffer = buffer.Buffer; const createHmac = browser$2; - const ONE1 = Buffer$l.alloc(1, 1); - const ZERO1 = Buffer$l.alloc(1, 0); + const ONE1 = Buffer$m.alloc(1, 1); + const ZERO1 = Buffer$m.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$l.alloc(32, 0); - let v = Buffer$l.alloc(32, 1); + let k = Buffer$m.alloc(32, 0); + let v = Buffer$m.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -24512,14 +21289,14 @@ window.Buffer = buffer.Buffer; var rfc6979 = deterministicGenerateK$1; - const BN = bn$1.exports; + const BN = bn.exports; const EC = elliptic.ec; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$l.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$m.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -24591,9 +21368,9 @@ window.Buffer = buffer.Buffer; } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -24725,7 +21502,7 @@ window.Buffer = buffer.Buffer; s = n.sub(s); } - const buffer = Buffer$l.allocUnsafe(64); + const buffer = Buffer$m.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -24958,7 +21735,7 @@ window.Buffer = buffer.Buffer; var _HexN = _LengthN.bind(null, Hex); var _StringN = _LengthN.bind(null, NATIVE$1.String); - function Range$b (a, b, f) { + function Range$m (a, b, f) { f = f || NATIVE$1.Number; function _range (value, strict) { return f(value, strict) && (value > a) && (value < b) @@ -25004,7 +21781,7 @@ window.Buffer = buffer.Buffer; Int16: Int16, Int32: Int32, Int53: Int53, - Range: Range$b, + Range: Range$m, StringN: _StringN, UInt8: UInt8, UInt16: UInt16, @@ -25310,7 +22087,7 @@ window.Buffer = buffer.Buffer; } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$l(compressed ? 34 : 33); + var result = new Buffer$m(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -25429,7 +22206,7 @@ window.Buffer = buffer.Buffer; const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$l.allocUnsafe(78); + const buffer = Buffer$m.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -25463,7 +22240,7 @@ window.Buffer = buffer.Buffer; derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$l.allocUnsafe(37); + const data = Buffer$m.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -25543,7 +22320,7 @@ window.Buffer = buffer.Buffer; } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -25635,7 +22412,7 @@ window.Buffer = buffer.Buffer; if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -25742,7 +22519,7 @@ window.Buffer = buffer.Buffer; function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$l.allocUnsafe(size); + const buffer = Buffer$m.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -25937,18 +22714,18 @@ window.Buffer = buffer.Buffer; const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$l.alloc(1, 0); + const ZERO$1 = Buffer$m.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$l.alloc(32, 0); + const buffer = Buffer$m.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -25962,7 +22739,7 @@ window.Buffer = buffer.Buffer; const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$l.concat([r, s], 64); + const signature = Buffer$m.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -25977,11 +22754,11 @@ window.Buffer = buffer.Buffer; const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$l.allocUnsafe(1); + const hashTypeBuffer = Buffer$m.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -26370,7 +23147,7 @@ window.Buffer = buffer.Buffer; // opcode return accum + 1; }, 0.0); - const buffer = Buffer$l.allocUnsafe(bufferSize); + const buffer = Buffer$m.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -26455,7 +23232,7 @@ window.Buffer = buffer.Buffer; if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$l.from(chunkStr, 'hex'); + return Buffer$m.from(chunkStr, 'hex'); }), ); } @@ -26465,7 +23242,7 @@ window.Buffer = buffer.Buffer; typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -26873,7 +23650,7 @@ window.Buffer = buffer.Buffer; const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -26912,7 +23689,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27031,7 +23808,7 @@ window.Buffer = buffer.Buffer; // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -27067,7 +23844,7 @@ window.Buffer = buffer.Buffer; return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27343,7 +24120,7 @@ window.Buffer = buffer.Buffer; const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$l.alloc(0); + const EMPTY_BUFFER$1 = Buffer$m.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -27371,7 +24148,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -27411,7 +24188,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27475,7 +24252,7 @@ window.Buffer = buffer.Buffer; const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$l.alloc(0); + const EMPTY_BUFFER = Buffer$m.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -27525,7 +24302,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; }); const _rchunks = lazy.value(() => { @@ -27590,7 +24367,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27713,13 +24490,13 @@ window.Buffer = buffer.Buffer; return { version: result.words[0], prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -27875,7 +24652,7 @@ window.Buffer = buffer.Buffer; return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -27947,10 +24724,10 @@ window.Buffer = buffer.Buffer; var Buffer = safeBuffer.exports.Buffer; // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; + var MAX_SAFE_INTEGER$5 = 9007199254740991; function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') } function encode$b (number, buffer, offset) { @@ -28077,7 +24854,7 @@ window.Buffer = buffer.Buffer; } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$l.allocUnsafe(buffer.length); + const clone = Buffer$m.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -28200,17 +24977,17 @@ window.Buffer = buffer.Buffer; }, 0) ); } - const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$l.from( + const ZERO = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$l.from( + const ONE = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -28272,7 +25049,7 @@ window.Buffer = buffer.Buffer; return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -28432,7 +25209,7 @@ window.Buffer = buffer.Buffer; txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -28442,13 +25219,13 @@ window.Buffer = buffer.Buffer; types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$l.from([]); + let tbuffer = Buffer$m.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -28461,7 +25238,7 @@ window.Buffer = buffer.Buffer; (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -28475,7 +25252,7 @@ window.Buffer = buffer.Buffer; const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$l.allocUnsafe(txOutsSize); + tbuffer = Buffer$m.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -28487,13 +25264,13 @@ window.Buffer = buffer.Buffer; inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -28511,7 +25288,7 @@ window.Buffer = buffer.Buffer; } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -28533,7 +25310,7 @@ window.Buffer = buffer.Buffer; this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -28595,7 +25372,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$l.concat([left, right]); + var data = Buffer$m.concat([left, right]); results[j] = digestFn(data); } @@ -28662,12 +25439,12 @@ window.Buffer = buffer.Buffer; return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$l.from(hex, 'hex')); + return Block.fromBuffer(Buffer$m.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$l.alloc(32, 0); + const target = Buffer$m.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -28682,7 +25459,7 @@ window.Buffer = buffer.Buffer; const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -28694,18 +25471,18 @@ window.Buffer = buffer.Buffer; // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$l && result.length === 32)) return null; + if (!(result instanceof Buffer$m && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$l && + this.witnessCommit instanceof Buffer$m && this.witnessCommit.length === 32 ) return true; @@ -28741,7 +25518,7 @@ window.Buffer = buffer.Buffer; } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -28883,7 +25660,7 @@ window.Buffer = buffer.Buffer; Object.defineProperty(globalXpub$1, '__esModule', { value: true }); const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; + const range$4 = n => [...Array(n).keys()]; function decode$9(keyVal) { if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { throw new Error( @@ -28908,7 +25685,7 @@ window.Buffer = buffer.Buffer; extendedPubkey, path: 'm', }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { + for (const i of range$4(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -28918,10 +25695,10 @@ window.Buffer = buffer.Buffer; } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$l.concat([head, data.extendedPubkey]); + const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$m.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28970,7 +25747,7 @@ window.Buffer = buffer.Buffer; const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -28991,7 +25768,7 @@ window.Buffer = buffer.Buffer; } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -29023,7 +25800,7 @@ window.Buffer = buffer.Buffer; } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -29058,7 +25835,7 @@ window.Buffer = buffer.Buffer; nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -29101,9 +25878,9 @@ window.Buffer = buffer.Buffer; } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$l.concat([head, pSig.pubkey]), + key: Buffer$m.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -29155,10 +25932,10 @@ window.Buffer = buffer.Buffer; } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$l.from(data, 'utf8'), + value: Buffer$m.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -29187,8 +25964,8 @@ window.Buffer = buffer.Buffer; } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$l.allocUnsafe(4); + const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$m.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -29214,14 +25991,14 @@ window.Buffer = buffer.Buffer; Object.defineProperty(varint$1, '__esModule', { value: true }); // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; + const MAX_SAFE_INTEGER$4 = 9007199254740991; function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) throw new RangeError('value out of range'); } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -29307,8 +26084,8 @@ window.Buffer = buffer.Buffer; tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$l.from([0])); - return Buffer$l.concat(buffers); + buffers.push(Buffer$m.from([0])); + return Buffer$m.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -29316,7 +26093,7 @@ window.Buffer = buffer.Buffer; const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$l.allocUnsafe( + const buffer = Buffer$m.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -29380,12 +26157,12 @@ window.Buffer = buffer.Buffer; function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -29403,7 +26180,7 @@ window.Buffer = buffer.Buffer; var bip32Derivation$1 = {}; Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; + const range$3 = n => [...Array(n).keys()]; function makeConverter$2(TYPE_BYTE) { function decode(keyVal) { if (keyVal.key[0] !== TYPE_BYTE) { @@ -29432,7 +26209,7 @@ window.Buffer = buffer.Buffer; pubkey, path: 'm', }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { + for (const i of range$3(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -29441,10 +26218,10 @@ window.Buffer = buffer.Buffer; return data; } function encode(data) { - const head = Buffer$l.from([TYPE_BYTE]); - const key = Buffer$l.concat([head, data.pubkey]); + const head = Buffer$m.from([TYPE_BYTE]); + const key = Buffer$m.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -29524,7 +26301,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -29561,7 +26338,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -29770,7 +26547,7 @@ window.Buffer = buffer.Buffer; } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$l.from([keyNum]))) { + if (!keyBuf.equals(Buffer$m.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -29989,13 +26766,13 @@ window.Buffer = buffer.Buffer; const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$l.from([0])] + ? [Buffer$m.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$l.allocUnsafe(5); + const header = Buffer$m.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$l.concat( + return Buffer$m.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -30289,11 +27066,11 @@ window.Buffer = buffer.Buffer; }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -30513,11 +27290,11 @@ window.Buffer = buffer.Buffer; dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -30688,7 +27465,7 @@ window.Buffer = buffer.Buffer; } finalizeAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); return this; } finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { @@ -30755,7 +27532,7 @@ window.Buffer = buffer.Buffer; } validateSignaturesOfAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => + const results = range$2(this.data.inputs.length).map(idx => this.validateSignaturesOfInput(idx), ); return results.reduce((final, res) => res === true && final, true); @@ -30801,7 +27578,7 @@ window.Buffer = buffer.Buffer; throw new Error('Need HDSigner to sign input'); } const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInputHD(i, hdKeyPair, sighashTypes); results.push(true); @@ -30824,7 +27601,7 @@ window.Buffer = buffer.Buffer; } const results = []; const promises = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { promises.push( this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( () => { @@ -30886,7 +27663,7 @@ window.Buffer = buffer.Buffer; // as input information is added, then eventually // optimize this method. const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInput(i, keyPair, sighashTypes); results.push(true); @@ -31041,7 +27818,7 @@ window.Buffer = buffer.Buffer; * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -31066,7 +27843,7 @@ window.Buffer = buffer.Buffer; } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -31241,7 +28018,7 @@ window.Buffer = buffer.Buffer; } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -31605,14 +28382,14 @@ window.Buffer = buffer.Buffer; return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$l.allocUnsafe(0); + let buffer = Buffer$m.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); + buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); + buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -31817,7 +28594,7 @@ window.Buffer = buffer.Buffer; if (isP2PK(script)) return 'pubkey'; return 'nonstandard'; } - function range$1(n) { + function range$2(n) { return [...Array(n).keys()]; } @@ -32121,7 +28898,7 @@ window.Buffer = buffer.Buffer; const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$l.from('aa21a9ed', 'hex'); + const HEADER = Buffer$m.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -32137,7 +28914,7 @@ window.Buffer = buffer.Buffer; }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$l.allocUnsafe(36); + const buffer = Buffer$m.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -32413,7 +29190,7 @@ window.Buffer = buffer.Buffer; // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -33381,27 +30158,27 @@ window.Buffer = buffer.Buffer; var transaction_builder_1 = transaction_builder; src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - var re$5 = {exports: {}}; + var re$b = {exports: {}}; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; + const SEMVER_SPEC_VERSION$1 = '2.0.0'; - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + const MAX_LENGTH$5 = 256; + const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; + const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH + var constants$1 = { + SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, + MAX_LENGTH: MAX_LENGTH$5, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, + MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 }; - const debug$3 = ( + const debug$7 = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && @@ -33409,11 +30186,11 @@ window.Buffer = buffer.Buffer; ) ? (...args) => console.error('SEMVER', ...args) : () => {}; - var debug_1 = debug$3; + var debug_1$1 = debug$7; (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; + const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; + const debug = debug_1$1; exports = module.exports = {}; // The actual regexps go on exports.re @@ -33594,24 +30371,24 @@ window.Buffer = buffer.Buffer; // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + }(re$b, re$b.exports)); // parse out just the options we care about so we always get a consistent // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => + const opts$1 = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$9 = options => !options ? {} : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { + : opts$1.filter(k => options[k]).reduce((options, k) => { options[k] = true; return options }, {}); - var parseOptions_1 = parseOptions$4; + var parseOptions_1$1 = parseOptions$9; - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + const numeric$1 = /^[0-9]+$/; + const compareIdentifiers$3 = (a, b) => { + const anum = numeric$1.test(a); + const bnum = numeric$1.test(b); if (anum && bnum) { a = +a; @@ -33625,24 +30402,24 @@ window.Buffer = buffer.Buffer; : 1 }; - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers + var identifiers$1 = { + compareIdentifiers: compareIdentifiers$3, + rcompareIdentifiers: rcompareIdentifiers$1 }; - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; + const debug$6 = debug_1$1; + const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; + const { re: re$a, t: t$9 } = re$b.exports; - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { + const parseOptions$8 = parseOptions_1$1; + const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; + class SemVer$t { constructor (version, options) { - options = parseOptions$3(options); + options = parseOptions$8(options); - if (version instanceof SemVer$e) { + if (version instanceof SemVer$t) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version @@ -33653,20 +30430,20 @@ window.Buffer = buffer.Buffer; throw new TypeError(`Invalid Version: ${version}`) } - if (version.length > MAX_LENGTH$1) { + if (version.length > MAX_LENGTH$4) { throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` + `version is longer than ${MAX_LENGTH$4} characters` ) } - debug$2('SemVer', version, options); + debug$6('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); if (!m) { throw new TypeError(`Invalid Version: ${version}`) @@ -33679,15 +30456,15 @@ window.Buffer = buffer.Buffer; this.minor = +m[2]; this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { throw new TypeError('Invalid major version') } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { throw new TypeError('Invalid minor version') } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { throw new TypeError('Invalid patch version') } @@ -33698,7 +30475,7 @@ window.Buffer = buffer.Buffer; this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { + if (num >= 0 && num < MAX_SAFE_INTEGER$2) { return num } } @@ -33723,12 +30500,12 @@ window.Buffer = buffer.Buffer; } compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { + debug$6('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$t)) { if (typeof other === 'string' && other === this.version) { return 0 } - other = new SemVer$e(other, this.options); + other = new SemVer$t(other, this.options); } if (other.version === this.version) { @@ -33739,20 +30516,20 @@ window.Buffer = buffer.Buffer; } compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) + compareIdentifiers$2(this.major, other.major) || + compareIdentifiers$2(this.minor, other.minor) || + compareIdentifiers$2(this.patch, other.patch) ) } comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } // NOT having a prerelease is > having one @@ -33768,7 +30545,7 @@ window.Buffer = buffer.Buffer; do { const a = this.prerelease[i]; const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -33778,21 +30555,21 @@ window.Buffer = buffer.Buffer; } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -33802,7 +30579,7 @@ window.Buffer = buffer.Buffer; } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } @@ -33918,17 +30695,17 @@ window.Buffer = buffer.Buffer; } } - var semver$1 = SemVer$e; + var semver$3 = SemVer$t; - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; + const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; + const { re: re$9, t: t$8 } = re$b.exports; + const SemVer$s = semver$3; - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); + const parseOptions$7 = parseOptions_1$1; + const parse$b = (version, options) => { + options = parseOptions$7(options); - if (version instanceof SemVer$d) { + if (version instanceof SemVer$s) { return version } @@ -33936,73 +30713,73 @@ window.Buffer = buffer.Buffer; return null } - if (version.length > MAX_LENGTH) { + if (version.length > MAX_LENGTH$3) { return null } - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; if (!r.test(version)) { return null } try { - return new SemVer$d(version, options) + return new SemVer$s(version, options) } catch (er) { return null } }; - var parse_1 = parse$5; + var parse_1$1 = parse$b; - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); + const parse$a = parse_1$1; + const valid$3 = (version, options) => { + const v = parse$a(version, options); return v ? v.version : null }; - var valid_1 = valid$1; + var valid_1$1 = valid$3; - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + const parse$9 = parse_1$1; + const clean$1 = (version, options) => { + const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); return s ? s.version : null }; - var clean_1 = clean; + var clean_1$1 = clean$1; - const SemVer$c = semver$1; + const SemVer$r = semver$3; - const inc = (version, release, options, identifier) => { + const inc$1 = (version, release, options, identifier) => { if (typeof (options) === 'string') { identifier = options; options = undefined; } try { - return new SemVer$c(version, options).inc(release, identifier).version + return new SemVer$r(version, options).inc(release, identifier).version } catch (er) { return null } }; - var inc_1 = inc; + var inc_1$1 = inc$1; - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + const SemVer$q = semver$3; + const compare$l = (a, b, loose) => + new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - var compare_1 = compare$a; + var compare_1$1 = compare$l; - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; + const compare$k = compare_1$1; + const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; + var eq_1$1 = eq$5; - const parse$2 = parse_1; - const eq$1 = eq_1; + const parse$8 = parse_1$1; + const eq$4 = eq_1$1; - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { + const diff$1 = (version1, version2) => { + if (eq$4(version1, version2)) { return null } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); + const v1 = parse$8(version1); + const v2 = parse$8(version2); const hasPre = v1.prerelease.length || v2.prerelease.length; const prefix = hasPre ? 'pre' : ''; const defaultResult = hasPre ? 'prerelease' : ''; @@ -34016,79 +30793,79 @@ window.Buffer = buffer.Buffer; return defaultResult // may be undefined } }; - var diff_1 = diff; + var diff_1$1 = diff$1; - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; + const SemVer$p = semver$3; + const major$1 = (a, loose) => new SemVer$p(a, loose).major; + var major_1$1 = major$1; - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; + const SemVer$o = semver$3; + const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; + var minor_1$1 = minor$1; - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; + const SemVer$n = semver$3; + const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; + var patch_1$1 = patch$1; - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); + const parse$7 = parse_1$1; + const prerelease$1 = (version, options) => { + const parsed = parse$7(version, options); return (parsed && parsed.prerelease.length) ? parsed.prerelease : null }; - var prerelease_1 = prerelease; + var prerelease_1$1 = prerelease$1; - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; + const compare$j = compare_1$1; + const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); + var rcompare_1$1 = rcompare$1; - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; + const compare$i = compare_1$1; + const compareLoose$1 = (a, b) => compare$i(a, b, true); + var compareLoose_1$1 = compareLoose$1; - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); + const SemVer$m = semver$3; + const compareBuild$5 = (a, b, loose) => { + const versionA = new SemVer$m(a, loose); + const versionB = new SemVer$m(b, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB) }; - var compareBuild_1 = compareBuild$2; + var compareBuild_1$1 = compareBuild$5; - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; + const compareBuild$4 = compareBuild_1$1; + const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); + var sort_1$1 = sort$1; - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; + const compareBuild$3 = compareBuild_1$1; + const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); + var rsort_1$1 = rsort$1; - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; + const compare$h = compare_1$1; + const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; + var gt_1$1 = gt$7; - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; + const compare$g = compare_1$1; + const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; + var lt_1$1 = lt$5; - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; + const compare$f = compare_1$1; + const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; + var neq_1$1 = neq$3; - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; + const compare$e = compare_1$1; + const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; + var gte_1$1 = gte$5; - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; + const compare$d = compare_1$1; + const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; + var lte_1$1 = lte$5; - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; + const eq$3 = eq_1$1; + const neq$2 = neq_1$1; + const gt$6 = gt_1$1; + const gte$4 = gte_1$1; + const lt$4 = lt_1$1; + const lte$4 = lte_1$1; - const cmp$1 = (a, op, b, loose) => { + const cmp$3 = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') @@ -34107,35 +30884,35 @@ window.Buffer = buffer.Buffer; case '': case '=': case '==': - return eq(a, b, loose) + return eq$3(a, b, loose) case '!=': - return neq(a, b, loose) + return neq$2(a, b, loose) case '>': - return gt$2(a, b, loose) + return gt$6(a, b, loose) case '>=': - return gte$1(a, b, loose) + return gte$4(a, b, loose) case '<': - return lt$1(a, b, loose) + return lt$4(a, b, loose) case '<=': - return lte$1(a, b, loose) + return lte$4(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } }; - var cmp_1 = cmp$1; + var cmp_1$1 = cmp$3; - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; + const SemVer$l = semver$3; + const parse$6 = parse_1$1; + const {re: re$8, t: t$7} = re$b.exports; - const coerce = (version, options) => { - if (version instanceof SemVer$6) { + const coerce$1 = (version, options) => { + if (version instanceof SemVer$l) { return version } @@ -34151,7 +30928,7 @@ window.Buffer = buffer.Buffer; let match = null; if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); + match = version.match(re$8[t$7.COERCE]); } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. @@ -34162,25 +30939,25 @@ window.Buffer = buffer.Buffer; // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && + while ((next = re$8[t$7.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next; } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; + re$8[t$7.COERCERTL].lastIndex = -1; } if (match === null) return null - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) }; - var coerce_1 = coerce; + var coerce_1$1 = coerce$1; var yallist = Yallist$1; @@ -34942,22 +31719,22 @@ window.Buffer = buffer.Buffer; var lruCache = LRUCache; // hoisted class for cyclic dependency - class Range$a { + class Range$l { constructor (range, options) { - options = parseOptions$1(options); + options = parseOptions$6(options); - if (range instanceof Range$a) { + if (range instanceof Range$l) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { - return new Range$a(range.raw, options) + return new Range$l(range.raw, options) } } - if (range instanceof Comparator$3) { + if (range instanceof Comparator$7) { // just put it in the set and return this.raw = range.value; this.set = [[range]]; @@ -34988,13 +31765,13 @@ window.Buffer = buffer.Buffer; if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); + this.set = this.set.filter(c => !isNullSet$1(c[0])); if (this.set.length === 0) this.set = [first]; else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { + if (c.length === 1 && isAny$1(c[0])) { this.set = [c]; break } @@ -35026,24 +31803,24 @@ window.Buffer = buffer.Buffer; // this is a very hot path, and fully deterministic. const memoOpts = Object.keys(this.options).join(','); const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); + const cached = cache$1.get(memoKey); if (cached) return cached const loose = this.options.loose; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); + const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); + debug$5('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); + debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); // normalize spaces range = range.split(/\s+/).join(' '); @@ -35051,17 +31828,17 @@ window.Buffer = buffer.Buffer; // At this point, the range is completely trimmed and // ready to be split into comparators. - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; const rangeList = range .split(' ') - .map(comp => parseComparator(comp, this.options)) + .map(comp => parseComparator$1(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) + .map(comp => replaceGTE0$1(comp, this.options)) // in loose mode, throw out any that are not valid comparators .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); + .map(comp => new Comparator$7(comp, this.options)); // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators @@ -35069,7 +31846,7 @@ window.Buffer = buffer.Buffer; rangeList.length; const rangeMap = new Map(); for (const comp of rangeList) { - if (isNullSet(comp)) + if (isNullSet$1(comp)) return [comp] rangeMap.set(comp.value, comp); } @@ -35077,21 +31854,21 @@ window.Buffer = buffer.Buffer; rangeMap.delete(''); const result = [...rangeMap.values()]; - cache.set(memoKey, result); + cache$1.set(memoKey, result); return result } intersects (range, options) { - if (!(range instanceof Range$a)) { + if (!(range instanceof Range$l)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( - isSatisfiable(thisComparators, options) && + isSatisfiable$1(thisComparators, options) && range.set.some((rangeComparators) => { return ( - isSatisfiable(rangeComparators, options) && + isSatisfiable$1(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) @@ -35111,43 +31888,43 @@ window.Buffer = buffer.Buffer; if (typeof version === 'string') { try { - version = new SemVer$5(version, this.options); + version = new SemVer$k(version, this.options); } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { + if (testSet$1(this.set[i], version, this.options)) { return true } } return false } } - var range = Range$a; + var range$1 = Range$l; - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); + const LRU$1 = lruCache; + const cache$1 = new LRU$1({ max: 1000 }); - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; + const parseOptions$6 = parseOptions_1$1; + const Comparator$7 = comparator$1; + const debug$5 = debug_1$1; + const SemVer$k = semver$3; const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; + re: re$7, + t: t$6, + comparatorTrimReplace: comparatorTrimReplace$1, + tildeTrimReplace: tildeTrimReplace$1, + caretTrimReplace: caretTrimReplace$1 + } = re$b.exports; - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; + const isNullSet$1 = c => c.value === '<0.0.0-0'; + const isAny$1 = c => c.value === ''; // take a set of comparators and determine whether there // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { + const isSatisfiable$1 = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); @@ -35166,20 +31943,20 @@ window.Buffer = buffer.Buffer; // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); + const parseComparator$1 = (comp, options) => { + debug$5('comp', comp, options); + comp = replaceCarets$1(comp, options); + debug$5('caret', comp); + comp = replaceTildes$1(comp, options); + debug$5('tildes', comp); + comp = replaceXRanges$1(comp, options); + debug$5('xrange', comp); + comp = replaceStars$1(comp, options); + debug$5('stars', comp); return comp }; - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 @@ -35187,26 +31964,26 @@ window.Buffer = buffer.Buffer; // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => + const replaceTildes$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) + return replaceTilde$1(comp, options) }).join(' '); - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + const replaceTilde$1 = (comp, options) => { + const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); + debug$5('tilde', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { - debug$1('replaceTilde pr', pr); + debug$5('replaceTilde pr', pr); ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0`; } else { @@ -35215,7 +31992,7 @@ window.Buffer = buffer.Buffer; } <${M}.${+m + 1}.0-0`; } - debug$1('tilde return', ret); + debug$5('tilde return', ret); return ret }) }; @@ -35226,31 +32003,31 @@ window.Buffer = buffer.Buffer; // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => + const replaceCarets$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) + return replaceCaret$1(comp, options) }).join(' '); - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const replaceCaret$1 = (comp, options) => { + debug$5('caret', comp, options); + const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; const z = options.includePrerelease ? '-0' : ''; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); + debug$5('caret', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { - debug$1('replaceCaret pr', pr); + debug$5('replaceCaret pr', pr); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr @@ -35264,7 +32041,7 @@ window.Buffer = buffer.Buffer; } <${+M + 1}.0.0-0`; } } else { - debug$1('no pr'); + debug$5('no pr'); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p @@ -35279,26 +32056,26 @@ window.Buffer = buffer.Buffer; } } - debug$1('caret return', ret); + debug$5('caret return', ret); return ret }) }; - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); + const replaceXRanges$1 = (comp, options) => { + debug$5('replaceXRanges', comp, options); return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) + return replaceXRange$1(comp, options) }).join(' ') }; - const replaceXRange = (comp, options) => { + const replaceXRange$1 = (comp, options) => { comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); + debug$5('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX$1(M); + const xm = xM || isX$1(m); + const xp = xm || isX$1(p); const anyX = xp; if (gtlt === '=' && anyX) { @@ -35359,7 +32136,7 @@ window.Buffer = buffer.Buffer; } <${M}.${+m + 1}.0-0`; } - debug$1('xRange return', ret); + debug$5('xRange return', ret); return ret }) @@ -35367,16 +32144,16 @@ window.Buffer = buffer.Buffer; // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); + const replaceStars$1 = (comp, options) => { + debug$5('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') + return comp.trim().replace(re$7[t$6.STAR], '') }; - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); + const replaceGTE0$1 = (comp, options) => { + debug$5('replaceGTE0', comp, options); return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') }; // This function is passed to string.replace(re[t.HYPHENRANGE]) @@ -35384,14 +32161,14 @@ window.Buffer = buffer.Buffer; // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, + const hyphenReplace$1 = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { + if (isX$1(fM)) { from = ''; - } else if (isX(fm)) { + } else if (isX$1(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { + } else if (isX$1(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; } else if (fpr) { from = `>=${from}`; @@ -35399,11 +32176,11 @@ window.Buffer = buffer.Buffer; from = `>=${from}${incPr ? '-0' : ''}`; } - if (isX(tM)) { + if (isX$1(tM)) { to = ''; - } else if (isX(tm)) { + } else if (isX$1(tm)) { to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { + } else if (isX$1(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; @@ -35416,7 +32193,7 @@ window.Buffer = buffer.Buffer; return (`${from} ${to}`).trim() }; - const testSet = (set, version, options) => { + const testSet$1 = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false @@ -35430,8 +32207,8 @@ window.Buffer = buffer.Buffer; // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { + debug$5(set[i].semver); + if (set[i].semver === Comparator$7.ANY) { continue } @@ -35452,16 +32229,16 @@ window.Buffer = buffer.Buffer; return true }; - const ANY$2 = Symbol('SemVer ANY'); + const ANY$5 = Symbol('SemVer ANY'); // hoisted class for cyclic dependency - class Comparator$2 { + class Comparator$6 { static get ANY () { - return ANY$2 + return ANY$5 } constructor (comp, options) { - options = parseOptions(options); + options = parseOptions$5(options); - if (comp instanceof Comparator$2) { + if (comp instanceof Comparator$6) { if (comp.loose === !!options.loose) { return comp } else { @@ -35469,22 +32246,22 @@ window.Buffer = buffer.Buffer; } } - debug('comparator', comp, options); + debug$4('comparator', comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); - if (this.semver === ANY$2) { + if (this.semver === ANY$5) { this.value = ''; } else { this.value = this.operator + this.semver.version; } - debug('comp', this); + debug$4('comp', this); } parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; const m = comp.match(r); if (!m) { @@ -35498,9 +32275,9 @@ window.Buffer = buffer.Buffer; // if it literally is just '>' or '' then allow anything. if (!m[2]) { - this.semver = ANY$2; + this.semver = ANY$5; } else { - this.semver = new SemVer$4(m[2], this.options.loose); + this.semver = new SemVer$j(m[2], this.options.loose); } } @@ -35509,25 +32286,25 @@ window.Buffer = buffer.Buffer; } test (version) { - debug('Comparator.test', version, this.options.loose); + debug$4('Comparator.test', version, this.options.loose); - if (this.semver === ANY$2 || version === ANY$2) { + if (this.semver === ANY$5 || version === ANY$5) { return true } if (typeof version === 'string') { try { - version = new SemVer$4(version, this.options); + version = new SemVer$j(version, this.options); } catch (er) { return false } } - return cmp(version, this.operator, this.semver, this.options) + return cmp$2(version, this.operator, this.semver, this.options) } intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { + if (!(comp instanceof Comparator$6)) { throw new TypeError('a Comparator is required') } @@ -35542,12 +32319,12 @@ window.Buffer = buffer.Buffer; if (this.value === '') { return true } - return new Range$9(comp.value, options).test(this.value) + return new Range$k(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } - return new Range$9(this.value, options).test(comp.semver) + return new Range$k(this.value, options).test(comp.semver) } const sameDirectionIncreasing = @@ -35561,11 +32338,11 @@ window.Buffer = buffer.Buffer; (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && + cmp$2(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && + cmp$2(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); @@ -35579,44 +32356,44 @@ window.Buffer = buffer.Buffer; } } - var comparator = Comparator$2; + var comparator$1 = Comparator$6; - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; + const parseOptions$5 = parseOptions_1$1; + const {re: re$6, t: t$5} = re$b.exports; + const cmp$2 = cmp_1$1; + const debug$4 = debug_1$1; + const SemVer$j = semver$3; + const Range$k = range$1; - const Range$8 = range; - const satisfies$3 = (version, range, options) => { + const Range$j = range$1; + const satisfies$7 = (version, range, options) => { try { - range = new Range$8(range, options); + range = new Range$j(range, options); } catch (er) { return false } return range.test(version) }; - var satisfies_1 = satisfies$3; + var satisfies_1$1 = satisfies$7; - const Range$7 = range; + const Range$i = range$1; // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set + const toComparators$1 = (range, options) => + new Range$i(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - var toComparators_1 = toComparators; + var toComparators_1$1 = toComparators$1; - const SemVer$3 = semver$1; - const Range$6 = range; + const SemVer$i = semver$3; + const Range$h = range$1; - const maxSatisfying = (versions, range, options) => { + const maxSatisfying$1 = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { - rangeObj = new Range$6(range, options); + rangeObj = new Range$h(range, options); } catch (er) { return null } @@ -35626,22 +32403,22 @@ window.Buffer = buffer.Buffer; if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v; - maxSV = new SemVer$3(max, options); + maxSV = new SemVer$i(max, options); } } }); return max }; - var maxSatisfying_1 = maxSatisfying; + var maxSatisfying_1$1 = maxSatisfying$1; - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { + const SemVer$h = semver$3; + const Range$g = range$1; + const minSatisfying$1 = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { - rangeObj = new Range$5(range, options); + rangeObj = new Range$g(range, options); } catch (er) { return null } @@ -35651,27 +32428,27 @@ window.Buffer = buffer.Buffer; if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v; - minSV = new SemVer$2(min, options); + minSV = new SemVer$h(min, options); } } }); return min }; - var minSatisfying_1 = minSatisfying; + var minSatisfying_1$1 = minSatisfying$1; - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; + const SemVer$g = semver$3; + const Range$f = range$1; + const gt$5 = gt_1$1; - const minVersion = (range, loose) => { - range = new Range$4(range, loose); + const minVersion$1 = (range, loose) => { + range = new Range$f(range, loose); - let minver = new SemVer$1('0.0.0'); + let minver = new SemVer$g('0.0.0'); if (range.test(minver)) { return minver } - minver = new SemVer$1('0.0.0-0'); + minver = new SemVer$g('0.0.0-0'); if (range.test(minver)) { return minver } @@ -35683,7 +32460,7 @@ window.Buffer = buffer.Buffer; let setMin = null; comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); + const compver = new SemVer$g(comparator.semver.version); switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { @@ -35695,7 +32472,7 @@ window.Buffer = buffer.Buffer; /* fallthrough */ case '': case '>=': - if (!setMin || gt$1(compver, setMin)) { + if (!setMin || gt$5(compver, setMin)) { setMin = compver; } break @@ -35708,7 +32485,7 @@ window.Buffer = buffer.Buffer; throw new Error(`Unexpected operation: ${comparator.operator}`) } }); - if (setMin && (!minver || gt$1(minver, setMin))) + if (setMin && (!minver || gt$5(minver, setMin))) minver = setMin; } @@ -35718,47 +32495,47 @@ window.Buffer = buffer.Buffer; return null }; - var minVersion_1 = minVersion; + var minVersion_1$1 = minVersion$1; - const Range$3 = range; - const validRange = (range, options) => { + const Range$e = range$1; + const validRange$1 = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' + return new Range$e(range, options).range || '*' } catch (er) { return null } }; - var valid = validRange; + var valid$2 = validRange$1; - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; + const SemVer$f = semver$3; + const Comparator$5 = comparator$1; + const {ANY: ANY$4} = Comparator$5; + const Range$d = range$1; + const satisfies$6 = satisfies_1$1; + const gt$4 = gt_1$1; + const lt$3 = lt_1$1; + const lte$3 = lte_1$1; + const gte$3 = gte_1$1; - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); + const outside$5 = (version, range, hilo, options) => { + version = new SemVer$f(version, options); + range = new Range$d(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; + gtfn = gt$4; + ltefn = lte$3; + ltfn = lt$3; comp = '>'; ecomp = '>='; break case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; + gtfn = lt$3; + ltefn = gte$3; + ltfn = gt$4; comp = '<'; ecomp = '<='; break @@ -35767,7 +32544,7 @@ window.Buffer = buffer.Buffer; } // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { + if (satisfies$6(version, range, options)) { return false } @@ -35781,8 +32558,8 @@ window.Buffer = buffer.Buffer; let low = null; comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); + if (comparator.semver === ANY$4) { + comparator = new Comparator$5('>=0.0.0'); } high = high || comparator; low = low || comparator; @@ -35811,38 +32588,38 @@ window.Buffer = buffer.Buffer; return true }; - var outside_1 = outside$2; + var outside_1$1 = outside$5; // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; + const outside$4 = outside_1$1; + const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); + var gtr_1$1 = gtr$1; - const outside = outside_1; + const outside$3 = outside_1$1; // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; + const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); + var ltr_1$1 = ltr$1; - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); + const Range$c = range$1; + const intersects$1 = (r1, r2, options) => { + r1 = new Range$c(r1, options); + r2 = new Range$c(r2, options); return r1.intersects(r2) }; - var intersects_1 = intersects; + var intersects_1$1 = intersects$1; // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { + const satisfies$5 = satisfies_1$1; + const compare$c = compare_1$1; + var simplify$1 = (versions, range, options) => { const set = []; let min = null; let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); + const v = versions.sort((a, b) => compare$c(a, b, options)); for (const version of v) { - const included = satisfies$1(version, range, options); + const included = satisfies$5(version, range, options); if (included) { prev = version; if (!min) @@ -35876,11 +32653,11 @@ window.Buffer = buffer.Buffer; return simplified.length < original.length ? simplified : range }; - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; + const Range$b = range$1; + const Comparator$4 = comparator$1; + const { ANY: ANY$3 } = Comparator$4; + const satisfies$4 = satisfies_1$1; + const compare$b = compare_1$1; // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR @@ -35918,17 +32695,17 @@ window.Buffer = buffer.Buffer; // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true - const subset = (sub, dom, options = {}) => { + const subset$1 = (sub, dom, options = {}) => { if (sub === dom) return true - sub = new Range(sub, options); - dom = new Range(dom, options); + sub = new Range$b(sub, options); + dom = new Range$b(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); + const isSub = simpleSubset$1(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) continue OUTER @@ -35943,33 +32720,33 @@ window.Buffer = buffer.Buffer; return true }; - const simpleSubset = (sub, dom, options) => { + const simpleSubset$1 = (sub, dom, options) => { if (sub === dom) return true - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) + if (sub.length === 1 && sub[0].semver === ANY$3) { + if (dom.length === 1 && dom[0].semver === ANY$3) return true else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; + sub = [ new Comparator$4('>=0.0.0-0') ]; else - sub = [ new Comparator('>=0.0.0') ]; + sub = [ new Comparator$4('>=0.0.0') ]; } - if (dom.length === 1 && dom[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY$3) { if (options.includePrerelease) return true else - dom = [ new Comparator('>=0.0.0') ]; + dom = [ new Comparator$4('>=0.0.0') ]; } const eqSet = new Set(); let gt, lt; for (const c of sub) { if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); + gt = higherGT$1(gt, c, options); else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); + lt = lowerLT$1(lt, c, options); else eqSet.add(c.semver); } @@ -35979,7 +32756,7 @@ window.Buffer = buffer.Buffer; let gtltComp; if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); + gtltComp = compare$b(gt.semver, lt.semver, options); if (gtltComp > 0) return null else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) @@ -35988,1441 +32765,2603 @@ window.Buffer = buffer.Buffer; // will iterate one or zero times for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) + if (gt && !satisfies$4(eq, String(gt), options)) return null - if (lt && !satisfies(eq, String(lt), options)) + if (lt && !satisfies$4(eq, String(lt), options)) return null - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + for (const c of dom) { + if (!satisfies$4(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT$1(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT$1(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1$1 = subset$1; + + // just pre-load all the stuff that index.js lazily exports + const internalRe$1 = re$b.exports; + var semver$2 = { + re: internalRe$1.re, + src: internalRe$1.src, + tokens: internalRe$1.t, + SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, + SemVer: semver$3, + compareIdentifiers: identifiers$1.compareIdentifiers, + rcompareIdentifiers: identifiers$1.rcompareIdentifiers, + parse: parse_1$1, + valid: valid_1$1, + clean: clean_1$1, + inc: inc_1$1, + diff: diff_1$1, + major: major_1$1, + minor: minor_1$1, + patch: patch_1$1, + prerelease: prerelease_1$1, + compare: compare_1$1, + rcompare: rcompare_1$1, + compareLoose: compareLoose_1$1, + compareBuild: compareBuild_1$1, + sort: sort_1$1, + rsort: rsort_1$1, + gt: gt_1$1, + lt: lt_1$1, + eq: eq_1$1, + neq: neq_1$1, + gte: gte_1$1, + lte: lte_1$1, + cmp: cmp_1$1, + coerce: coerce_1$1, + Comparator: comparator$1, + Range: range$1, + satisfies: satisfies_1$1, + toComparators: toComparators_1$1, + maxSatisfying: maxSatisfying_1$1, + minSatisfying: minSatisfying_1$1, + minVersion: minVersion_1$1, + validRange: valid$2, + outside: outside_1$1, + gtr: gtr_1$1, + ltr: ltr_1$1, + intersects: intersects_1$1, + simplifyRange: simplify$1, + subset: subset_1$1, + }; + + function unsafeTo64bitLE(n) { + // we want to represent the input as a 8-bytes array + if (n > Number.MAX_SAFE_INTEGER) { + throw new Error("Can't convert numbers > MAX_SAFE_INT"); + } + var byteArray = Buffer$m.alloc(8, 0); + for (var index = 0; index < byteArray.length; index++) { + var byte = n & 0xff; + byteArray[index] = byte; + n = (n - byte) / 256; + } + return byteArray; + } + function unsafeFrom64bitLE(byteArray) { + var value = 0; + if (byteArray.length != 8) { + throw new Error("Expected Bufffer of lenght 8"); + } + if (byteArray[7] != 0) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + if (byteArray[6] > 0x1f) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + for (var i = byteArray.length - 1; i >= 0; i--) { + value = value * 256 + byteArray[i]; + } + return value; + } + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$m.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + var bytes = unsafeTo64bitLE(i); + this.writeSlice(bytes); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$m.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$m.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var buf = this.readSlice(8); + var n = unsafeFrom64bitLE(buf); + return n; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); + } + + var __extends$4 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$4(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$4(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$4(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$m.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$m.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$m.concat([ + Buffer$m.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$4(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$m.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$4(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$m.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false + finally { if (e) throw e.error; } } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + return ar; + }; + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a + return to.concat(ar || Array.prototype.slice.call(from)); }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$m.concat([Buffer$m.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$m.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$m.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$m.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + } - var subset_1 = subset; + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$m.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(psbt.getOutputAmount(i)); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$5.apply(this, arguments); }; - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$l.alloc(alloc); - fn(b); - this.bufs.push(b); + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$l.from(slice)); + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); }; - BufferWriter.prototype.buffer = function () { - return Buffer$l.concat(this.bufs); + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } - - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); + return unsafeFrom64bitLE(buf); }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$l.concat([h, h, x])); + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$l.concat([ - Buffer$l.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + buf.writeSlice(Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$m.from(k.substring(2), "hex")); + } + }); + return result; }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$m.from([])); + this.globalMap.set(key.toString(), value); }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); }; - return p2wpkh; - }(SingleKeyAccount)); - - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; + return (maps[index] = new Map()); }; - Merkle.prototype.size = function () { - return this.leaves.length; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); }; - Merkle.prototype.getLeaves = function () { - return this.leaves; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), - leaves: [] - }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$m.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); }; - return Merkle; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$l.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$l.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); }; - return Node; + return KeyPair; }()); - function proveNode(node) { - if (!node.parent) { - return []; + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); + keyPair.serialize(buf); } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); + buf.writeUInt8(0); + } + function b() { + return Buffer$m.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$m.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + return unsafeTo64bitLE(n); + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input ".concat(i, " present")); } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); } } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; + psbt.deleteInputEntries(inputIndex, keyTypes); } - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$l.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$m.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); } - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$l.from([0, 1])); + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$m.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$m.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$m.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; } - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$m.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$m.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$m.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$m.concat([ + inputBuffer, + input.prevout, + Buffer$m.from([0x00]), + input.sequence, + ]) + : Buffer$m.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$m.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$m.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$m.alloc(0), + transaction.extraData || Buffer$m.alloc(0), + ]); + } + return Buffer$m.concat([ + transaction.version, + timestamp ? timestamp : Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return NoSuchEntry; - }(Error)); + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver$2.major(appAndVersion.version) >= 2); + } /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. - */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. + */ + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); + } + return [2 /*return*/, xpub]; + } + }); + }); }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime != undefined) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); }); }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$m.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence != undefined) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType != undefined) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input ".concat(k)); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); }); }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$2 = 0; + var subscribers$1 = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log$1 = function (type, message, data) { + var obj = { + type: type, + id: String(++id$2), + date: new Date() }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch$1(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen$1 = function (cb) { + subscribers$1.push(cb); + return function () { + var i = subscribers$1.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; + subscribers$1.pop(); } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; + }; + }; + function dispatch$1(log) { + for (var i = 0; i < subscribers$1.length; i++) { + try { + subscribers$1[i](log); } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; + catch (e) { + console.error(e); } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen$1; + } + + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log$1, + listen: listen$1 + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; + return t; }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$l.from(k.substring(2), "hex")); + return __assign$4.apply(this, arguments); + }; + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; } }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$l.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; + }); + } + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var browser = invariant; + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$m.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$m.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$m.from([0x00]) + : Buffer$m.alloc(0); + data = Buffer$m.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$m.concat([ + output.amount, + isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$m.concat(endData); + extraPart = isDecred + ? data + : Buffer$m.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer$l.from(value); + }); } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); - keyPair.serialize(buf); - } - buf.writeUInt8(0); - } - function b() { - return Buffer$l.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$l.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer$l.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); } - - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$m.from([0x02]); + } } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); + else { + if (inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$m.from([0x00]); + } + } + data = Buffer$m.concat([ + prefix, + inputValue, + isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$l.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); + }); + }); } - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$l.alloc(1); - buffer_1[0] = value; - return buffer_1; + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$m.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); } - if (value <= 0xffff) { - var buffer_2 = Buffer$l.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); } - var buffer = Buffer$l.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; + hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); } - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$l.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$l.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$m.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$l.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$l.concat([ - inputBuffer, - input.prevout, - Buffer$l.from([0x00]), - input.sequence, - ]) - : Buffer$l.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$l.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$l.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$l.alloc(0), - transaction.extraData || Buffer$l.alloc(0), + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$m.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([sigHashType]), + ]) + : Buffer$m.concat([ + pathsBuffer, + Buffer$m.from([0x00]), + lockTimeBuffer, + Buffer$m.from([sigHashType]), ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$m.concat([buffer, expiryHeight]); } - return Buffer$l.concat([ - transaction.version, - timestamp ? timestamp : Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37431,7 +35370,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37458,459 +35397,116 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver.major(appAndVersion.version) >= 2); + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); + }); } - var id$2 = 0; - var subscribers$1 = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log$1 = function (type, message, data) { - var obj = { - type: type, - id: String(++id$2), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch$1(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen$1 = function (cb) { - subscribers$1.push(cb); - return function () { - var i = subscribers$1.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; - subscribers$1.pop(); - } - }; + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - function dispatch$1(log) { - for (var i = 0; i < subscribers$1.length; i++) { - try { - subscribers$1[i](log); - } - catch (e) { - console.error(e); - } + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen$1; - } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log$1, - listen: listen$1 - }); + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver$2.gte(version, "1.4.0"); + } - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -37918,9 +35514,9 @@ window.Buffer = buffer.Buffer; } return t; }; - return __assign$4.apply(this, arguments); + return __assign$3.apply(this, arguments); }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37929,7 +35525,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37956,89 +35552,474 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { switch (_b.label) { case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$m.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log$1("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$m.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$m.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$m.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$m.concat([ + Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$m.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$m.concat([ + Buffer$m.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$m.alloc(1); + keySize = Buffer$m.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$m.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$m.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$m.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$m.concat([ + Buffer$m.from("02", "hex"), + Buffer$m.from([signatures[i].length]), + signatures[i], + Buffer$m.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$m.concat([witness, tmpScriptData]); + } + result = Buffer$m.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$m.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$m.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$m.alloc(0), + targetTransaction.extraData || Buffer$m.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$m.concat([ + decredWitness_1, + Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0xff, 0xff, 0xff, 0xff]), + Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$m.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; } }); }); } - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$m.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); }; - - var browser = invariant; - - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38047,7 +36028,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38074,7 +36055,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$7 = (undefined && undefined.__values) || function(o) { + var __values$4 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38085,260 +36066,573 @@ window.Buffer = buffer.Buffer; }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$l.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { switch (_c.label) { case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$l.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ - transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + _c.label = 1; case 1: - _c.sent(); + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); _c.label = 2; case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; + if (!!inputs_1_1.done) return [3 /*break*/, 6]; input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$l.from([0x00]) - : Buffer$l.alloc(0); - data = Buffer$l.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$m.from(trustedInput, "hex") + : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: e_1_1 = _c.sent(); e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: + return [3 /*break*/, 9]; + case 8: try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; case 11: _c.sent(); _c.label = 12; case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + i = 0; _c.label = 13; case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$l.concat([ - output.amount, - isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; case 14: _c.sent(); - _c.label = 15; + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$l.concat(endData); - extraPart = isDecred - ? data - : Buffer$l.concat([createVarint(data.length), data]); + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; } - return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; } }); }); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$m.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$m.concat([ + Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$m.concat([ + asBufferUInt32BE(version), + Buffer$m.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$m.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } } + return ar; }; - var __values$6 = (undefined && undefined.__values) || function(o) { + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38349,213 +36643,296 @@ window.Buffer = buffer.Buffer; }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$l.concat([ - transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$l.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$l.from([0x00]); - } - } - data = Buffer$l.concat([ - prefix, - inputValue, - isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$l.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$l.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$m.from(request.subarray(1))); + this.progressCallback(); + return Buffer$m.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + GetPreimageCommand.prototype.execute = function (request) { + var req = Buffer$m.from(request.subarray(1)); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$m.from([known_preimage[i]])); + } + } + return Buffer$m.concat([ + preimage_len_varint, + Buffer$m.from([payload_size]), + Buffer$m.from(known_preimage.subarray(0, payload_size)), + ]); + } + throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = Buffer$m.from(request.subarray(1)); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$m.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$m.from([proof.length]), + Buffer$m.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = Buffer$m.from(request.subarray(1)); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; } - hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$l.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$l.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$l.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([sigHashType]), - ]) - : Buffer$l.concat([ - pathsBuffer, - Buffer$l.from([0x00]), - lockTimeBuffer, - Buffer$l.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$l.concat([buffer, expiryHeight]); + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$m.concat(__spreadArray$1([ + Buffer$m.from([n_returned_elements]), + Buffer$m.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code ".concat(cmd.code)); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); + this.addKnownPreimage(preimage); + } } - return result; - }); - } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code ".concat(cmdCode)); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38564,7 +36941,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38591,45 +36968,380 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ + Buffer$m.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$m.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ + Buffer$m.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + Buffer$m.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput ".concat(i, ":"); + str += " prevout ".concat(prevout.toString("hex")); + str += " script ".concat(script.toString("hex")); + str += " sequence ".concat(sequence.toString("hex")); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput ".concat(i, ":"); + str += " amount ".concat(amount.toString("hex")); + str += " script ".concat(script.toString("hex")); + }); + return str; } - function hashOutputFull(transport, outputScript, additionals) { + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$m.alloc(0); + var nExpiryHeight = Buffer$m.alloc(0); + var nVersionGroupId = Buffer$m.alloc(0); + var extraData = Buffer$m.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$m.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$m.alloc(0); + var tree = Buffer$m.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree }); - }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log$1("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + return t; } - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38638,7 +37350,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38665,435 +37377,504 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } - - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + else { + options = opts || {}; } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$l.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$l.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$l.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$l.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$l.concat([ - Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$l.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$l.concat([ - Buffer$l.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; } else { - signatureSize = Buffer$l.alloc(1); - keySize = Buffer$l.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$l.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$l.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$l.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$l.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$l.concat([ - Buffer$l.from("02", "hex"), - Buffer$l.from([signatures[i].length]), - signatures[i], - Buffer$l.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$l.concat([witness, tmpScriptData]); + return [2 /*return*/, this["new"]()]; } - result = Buffer$l.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$l.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$l.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$l.alloc(0), - targetTransaction.extraData || Buffer$l.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$l.concat([ - decredWitness_1, - Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0xff, 0xff, 0xff, 0xff]), - Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$l.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } + } + }); }); - }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; } - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses$3 = {}; + var deserializers$3 = {}; + var addCustomErrorDeserializer$3 = function (name, deserializer) { + deserializers$3[name] = deserializer; + }; + var createCustomErrorClass$3 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$3[name] = C; + return C; + }; + + createCustomErrorClass$3("AccountNameRequired"); + createCustomErrorClass$3("AccountNotSupported"); + createCustomErrorClass$3("AmountRequired"); + createCustomErrorClass$3("BluetoothRequired"); + createCustomErrorClass$3("BtcUnmatchedApp"); + createCustomErrorClass$3("CantOpenDevice"); + createCustomErrorClass$3("CashAddrNotSupported"); + createCustomErrorClass$3("CurrencyNotSupported"); + createCustomErrorClass$3("DeviceAppVerifyNotSupported"); + createCustomErrorClass$3("DeviceGenuineSocketEarlyClose"); + createCustomErrorClass$3("DeviceNotGenuine"); + createCustomErrorClass$3("DeviceOnDashboardExpected"); + createCustomErrorClass$3("DeviceOnDashboardUnexpected"); + createCustomErrorClass$3("DeviceInOSUExpected"); + createCustomErrorClass$3("DeviceHalted"); + createCustomErrorClass$3("DeviceNameInvalid"); + createCustomErrorClass$3("DeviceSocketFail"); + createCustomErrorClass$3("DeviceSocketNoBulkStatus"); + createCustomErrorClass$3("DisconnectedDevice"); + createCustomErrorClass$3("DisconnectedDeviceDuringOperation"); + createCustomErrorClass$3("EnpointConfig"); + createCustomErrorClass$3("EthAppPleaseEnableContractData"); + createCustomErrorClass$3("FeeEstimationFailed"); + createCustomErrorClass$3("FirmwareNotRecognized"); + createCustomErrorClass$3("HardResetFail"); + createCustomErrorClass$3("InvalidXRPTag"); + createCustomErrorClass$3("InvalidAddress"); + createCustomErrorClass$3("InvalidAddressBecauseDestinationIsAlsoSource"); + createCustomErrorClass$3("LatestMCUInstalledError"); + createCustomErrorClass$3("UnknownMCU"); + createCustomErrorClass$3("LedgerAPIError"); + createCustomErrorClass$3("LedgerAPIErrorWithMessage"); + createCustomErrorClass$3("LedgerAPINotAvailable"); + createCustomErrorClass$3("ManagerAppAlreadyInstalled"); + createCustomErrorClass$3("ManagerAppRelyOnBTC"); + createCustomErrorClass$3("ManagerAppDepInstallRequired"); + createCustomErrorClass$3("ManagerAppDepUninstallRequired"); + createCustomErrorClass$3("ManagerDeviceLocked"); + createCustomErrorClass$3("ManagerFirmwareNotEnoughSpace"); + createCustomErrorClass$3("ManagerNotEnoughSpace"); + createCustomErrorClass$3("ManagerUninstallBTCDep"); + createCustomErrorClass$3("NetworkDown"); + createCustomErrorClass$3("NoAddressesFound"); + createCustomErrorClass$3("NotEnoughBalance"); + createCustomErrorClass$3("NotEnoughBalanceToDelegate"); + createCustomErrorClass$3("NotEnoughBalanceInParentAccount"); + createCustomErrorClass$3("NotEnoughSpendableBalance"); + createCustomErrorClass$3("NotEnoughBalanceBecauseDestinationNotCreated"); + createCustomErrorClass$3("NoAccessToCamera"); + createCustomErrorClass$3("NotEnoughGas"); + createCustomErrorClass$3("NotSupportedLegacyAddress"); + createCustomErrorClass$3("GasLessThanEstimate"); + createCustomErrorClass$3("PasswordsDontMatch"); + createCustomErrorClass$3("PasswordIncorrect"); + createCustomErrorClass$3("RecommendSubAccountsToEmpty"); + createCustomErrorClass$3("RecommendUndelegation"); + createCustomErrorClass$3("TimeoutTagged"); + createCustomErrorClass$3("UnexpectedBootloader"); + createCustomErrorClass$3("MCUNotGenuineToDashboard"); + createCustomErrorClass$3("RecipientRequired"); + createCustomErrorClass$3("UnavailableTezosOriginatedAccountReceive"); + createCustomErrorClass$3("UnavailableTezosOriginatedAccountSend"); + createCustomErrorClass$3("UpdateFetchFileFail"); + createCustomErrorClass$3("UpdateIncorrectHash"); + createCustomErrorClass$3("UpdateIncorrectSig"); + createCustomErrorClass$3("UpdateYourApp"); + createCustomErrorClass$3("UserRefusedDeviceNameChange"); + createCustomErrorClass$3("UserRefusedAddress"); + createCustomErrorClass$3("UserRefusedFirmwareUpdate"); + createCustomErrorClass$3("UserRefusedAllowManager"); + createCustomErrorClass$3("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + createCustomErrorClass$3("TransportOpenUserCancelled"); + createCustomErrorClass$3("TransportInterfaceNotAvailable"); + var TransportRaceCondition$2 = createCustomErrorClass$3("TransportRaceCondition"); + createCustomErrorClass$3("TransportWebUSBGestureRequired"); + createCustomErrorClass$3("DeviceShouldStayInApp"); + createCustomErrorClass$3("WebsocketConnectionError"); + createCustomErrorClass$3("WebsocketConnectionFailed"); + createCustomErrorClass$3("WrongDeviceForAccount"); + createCustomErrorClass$3("WrongAppForCurrency"); + createCustomErrorClass$3("ETHAddressNonEIP"); + createCustomErrorClass$3("CantScanQRCode"); + createCustomErrorClass$3("FeeNotLoaded"); + createCustomErrorClass$3("FeeRequired"); + createCustomErrorClass$3("FeeTooHigh"); + createCustomErrorClass$3("SyncError"); + createCustomErrorClass$3("PairingFailed"); + createCustomErrorClass$3("GenuineCheckFailed"); + createCustomErrorClass$3("LedgerAPI4xx"); + createCustomErrorClass$3("LedgerAPI5xx"); + createCustomErrorClass$3("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + createCustomErrorClass$3("NoDBPathGiven"); + createCustomErrorClass$3("DBWrongPassword"); + createCustomErrorClass$3("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$3(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$3.prototype = new Error(); + addCustomErrorDeserializer$3("TransportError", function (e) { return new TransportError$3(e.message, e.id); }); + var StatusCodes$3 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$3(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$3(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$3).find(function (k) { return StatusCodes$3[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$3(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$3.prototype = new Error(); + addCustomErrorDeserializer$3("TransportStatusError", function (e) { return new TransportStatusError$3(e.statusCode); }); + + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39102,7 +37883,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39129,127 +37910,296 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$l.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport$1 = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$m.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes$3.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError$3("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); + return [4 /*yield*/, this.exchange(Buffer$m.concat([ + Buffer$m.from([cla, ins, p1, p2]), + Buffer$m.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError$3(sw); + } + return [2 /*return*/, response]; } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition$2("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; + } + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); + }; + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); + }; + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); + }; + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + }; + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError$3(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError$3(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values$1(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } } - return t; }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError$3("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); + + var hidFraming$1 = {}; + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -39260,2427 +38210,2495 @@ window.Buffer = buffer.Buffer; }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION + var errorClasses$2 = {}; + var deserializers$2 = {}; + var addCustomErrorDeserializer$2 = function (name, deserializer) { + deserializers$2[name] = deserializer; }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$l.from(trustedInput, "hex") - : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; + var createCustomErrorClass$2 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$2[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers$2[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses$2[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass$2(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } } - }); - }); + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass$2("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass$2("AccountNotSupported"); + var AmountRequired = createCustomErrorClass$2("AmountRequired"); + var BluetoothRequired = createCustomErrorClass$2("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass$2("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass$2("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass$2("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass$2("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass$2("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass$2("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass$2("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass$2("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass$2("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass$2("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass$2("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass$2("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass$2("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass$2("DeviceSocketNoBulkStatus"); + var DisconnectedDevice$1 = createCustomErrorClass$2("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation$1 = createCustomErrorClass$2("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass$2("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass$2("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass$2("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass$2("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass$2("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass$2("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass$2("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$2("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass$2("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass$2("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass$2("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass$2("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass$2("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass$2("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass$2("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass$2("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass$2("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass$2("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$2("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass$2("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass$2("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass$2("NetworkDown"); + var NoAddressesFound = createCustomErrorClass$2("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass$2("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass$2("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass$2("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass$2("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$2("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass$2("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass$2("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass$2("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass$2("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass$2("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass$2("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass$2("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass$2("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass$2("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass$2("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass$2("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass$2("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$2("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$2("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass$2("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass$2("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass$2("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass$2("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass$2("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass$2("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass$2("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass$2("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass$2("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled$1 = createCustomErrorClass$2("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable$1 = createCustomErrorClass$2("TransportInterfaceNotAvailable"); + var TransportRaceCondition$1 = createCustomErrorClass$2("TransportRaceCondition"); + var TransportWebUSBGestureRequired$1 = createCustomErrorClass$2("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass$2("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass$2("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass$2("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass$2("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass$2("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass$2("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass$2("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass$2("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass$2("FeeRequired"); + var FeeTooHigh = createCustomErrorClass$2("FeeTooHigh"); + var SyncError = createCustomErrorClass$2("SyncError"); + var PairingFailed = createCustomErrorClass$2("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass$2("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass$2("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass$2("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass$2("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass$2("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass$2("DBWrongPassword"); + var DBNotReset = createCustomErrorClass$2("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$2(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$2.prototype = new Error(); + addCustomErrorDeserializer$2("TransportError", function (e) { return new TransportError$2(e.message, e.id); }); + var StatusCodes$2 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$2(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$2(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$2).find(function (k) { return StatusCodes$2[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$2(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; } + TransportStatusError$2.prototype = new Error(); + addCustomErrorDeserializer$2("TransportStatusError", function (e) { return new TransportStatusError$2(e.statusCode); }); + + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass$2, + addCustomErrorDeserializer: addCustomErrorDeserializer$2, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice$1, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation$1, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled$1, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable$1, + TransportRaceCondition: TransportRaceCondition$1, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired$1, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError$2, + StatusCodes: StatusCodes$2, + getAltStatusMessage: getAltStatusMessage$2, + TransportStatusError: TransportStatusError$2 + }); - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$m.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$m.alloc(0), + dataLength: 0, + sequence: 0 }; /** - * Bitcoin API. * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); - } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$m.concat([ + data, + Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$m.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$m.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$m.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } } - return signP2SHTransaction(this.transport, arg); }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$l.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$l.concat([ - Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$l.concat([ - asBufferUInt32BE(version), - Buffer$l.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } + exports["default"] = createHIDframing; + + }(hidFraming$1)); + + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$3; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$l.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } } - finally { if (e) throw e.error; } + return id + }); } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; + + if (other.version === this.version) { + return 0 } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$l.from(request.subarray(1))); - this.progressCallback(); - return Buffer$l.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$l.from([known_preimage[i]])); - } - } - return Buffer$l.concat([ - preimage_len_varint, - Buffer$l.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$l.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$l.from([proof.length]), - Buffer$l.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$l.concat(__spreadArray$1([ - Buffer$l.from([n_returned_elements]), - Buffer$l.from([element_len]) - ], __read$1(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); - this.addKnownPreimage(preimage); + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); + } else { + this.prerelease = [identifier, 0]; + } } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); + break - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + default: + throw new Error(`invalid increment argument: ${release}`) } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$l.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), - Buffer$l.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; - }); - }); - }; - return AppClient; - }()); + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$l.alloc(0); - var nExpiryHeight = Buffer$l.alloc(0); - var nVersionGroupId = Buffer$l.alloc(0); - var extraData = Buffer$l.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$l.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } } + } } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$l.alloc(0); - var tree = Buffer$l.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } - else { - locktime = transaction.slice(offset, offset + 4); + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } } - if (hasExtraData) { - extraData = transaction.slice(offset); + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); + + debug$1('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; - } - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + debug$1('caret return', ret); + return ret + }) }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@backpacker69/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); - }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; } - return false; - } - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); + debug$1('xRange return', ret); - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + return ret + }) }; - var errorClasses$1 = {}; - var deserializers$1 = {}; - var addCustomErrorDeserializer$1 = function (name, deserializer) { - deserializers$1[name] = deserializer; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') }; - var createCustomErrorClass$1 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$1[name] = C; - return C; + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers$1[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass$1(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } - return error; + } } - return new Error(String(object)); + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } + + debug('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - if (typeof from.name === "string") { - to.name = from.name; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); } - if (typeof from.message === "string") { - to.message = from.message; + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true } - if (typeof from.stack === "string") { - to.stack = from.stack; + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } } - return to; - } - var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); - var AmountRequired = createCustomErrorClass$1("AmountRequired"); - var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass$1("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass$1("NetworkDown"); - var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); - var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass$1("FeeRequired"); - var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); - var SyncError = createCustomErrorClass$1("SyncError"); - var PairingFailed = createCustomErrorClass$1("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); - var DBNotReset = createCustomErrorClass$1("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$1(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); - var StatusCodes$1 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$1(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$1(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$1(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass$1, - addCustomErrorDeserializer: addCustomErrorDeserializer$1, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition$1, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError$1, - StatusCodes: StatusCodes$1, - getAltStatusMessage: getAltStatusMessage$1, - TransportStatusError: TransportStatusError$1 - }); + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } } + }); + return max }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - return ar; + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; } - return to.concat(ar || Array.prototype.slice.call(from)); + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport$1 = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$l.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$l.concat([ - Buffer$l.from([cla, ins, p1, p2]), - Buffer$l.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError$1(sw); - } - return [2 /*return*/, response]; - } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; - } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } - var hidFraming$1 = {}; + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$l.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$l.alloc(0), - dataLength: 0, - sequence: 0 + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$l.concat([ - data, - Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$l.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$l.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$l.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - exports["default"] = createHIDframing; - }(hidFraming$1)); + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -41798,6 +40816,216 @@ window.Buffer = buffer.Buffer; } } + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses$1 = {}; + var deserializers$1 = {}; + var addCustomErrorDeserializer$1 = function (name, deserializer) { + deserializers$1[name] = deserializer; + }; + var createCustomErrorClass$1 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$1[name] = C; + return C; + }; + + createCustomErrorClass$1("AccountNameRequired"); + createCustomErrorClass$1("AccountNotSupported"); + createCustomErrorClass$1("AmountRequired"); + createCustomErrorClass$1("BluetoothRequired"); + createCustomErrorClass$1("BtcUnmatchedApp"); + createCustomErrorClass$1("CantOpenDevice"); + createCustomErrorClass$1("CashAddrNotSupported"); + createCustomErrorClass$1("CurrencyNotSupported"); + createCustomErrorClass$1("DeviceAppVerifyNotSupported"); + createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); + createCustomErrorClass$1("DeviceNotGenuine"); + createCustomErrorClass$1("DeviceOnDashboardExpected"); + createCustomErrorClass$1("DeviceOnDashboardUnexpected"); + createCustomErrorClass$1("DeviceInOSUExpected"); + createCustomErrorClass$1("DeviceHalted"); + createCustomErrorClass$1("DeviceNameInvalid"); + createCustomErrorClass$1("DeviceSocketFail"); + createCustomErrorClass$1("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); + createCustomErrorClass$1("EnpointConfig"); + createCustomErrorClass$1("EthAppPleaseEnableContractData"); + createCustomErrorClass$1("FeeEstimationFailed"); + createCustomErrorClass$1("FirmwareNotRecognized"); + createCustomErrorClass$1("HardResetFail"); + createCustomErrorClass$1("InvalidXRPTag"); + createCustomErrorClass$1("InvalidAddress"); + createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); + createCustomErrorClass$1("LatestMCUInstalledError"); + createCustomErrorClass$1("UnknownMCU"); + createCustomErrorClass$1("LedgerAPIError"); + createCustomErrorClass$1("LedgerAPIErrorWithMessage"); + createCustomErrorClass$1("LedgerAPINotAvailable"); + createCustomErrorClass$1("ManagerAppAlreadyInstalled"); + createCustomErrorClass$1("ManagerAppRelyOnBTC"); + createCustomErrorClass$1("ManagerAppDepInstallRequired"); + createCustomErrorClass$1("ManagerAppDepUninstallRequired"); + createCustomErrorClass$1("ManagerDeviceLocked"); + createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); + createCustomErrorClass$1("ManagerNotEnoughSpace"); + createCustomErrorClass$1("ManagerUninstallBTCDep"); + createCustomErrorClass$1("NetworkDown"); + createCustomErrorClass$1("NoAddressesFound"); + createCustomErrorClass$1("NotEnoughBalance"); + createCustomErrorClass$1("NotEnoughBalanceToDelegate"); + createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); + createCustomErrorClass$1("NotEnoughSpendableBalance"); + createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); + createCustomErrorClass$1("NoAccessToCamera"); + createCustomErrorClass$1("NotEnoughGas"); + createCustomErrorClass$1("NotSupportedLegacyAddress"); + createCustomErrorClass$1("GasLessThanEstimate"); + createCustomErrorClass$1("PasswordsDontMatch"); + createCustomErrorClass$1("PasswordIncorrect"); + createCustomErrorClass$1("RecommendSubAccountsToEmpty"); + createCustomErrorClass$1("RecommendUndelegation"); + createCustomErrorClass$1("TimeoutTagged"); + createCustomErrorClass$1("UnexpectedBootloader"); + createCustomErrorClass$1("MCUNotGenuineToDashboard"); + createCustomErrorClass$1("RecipientRequired"); + createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); + createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); + createCustomErrorClass$1("UpdateFetchFileFail"); + createCustomErrorClass$1("UpdateIncorrectHash"); + createCustomErrorClass$1("UpdateIncorrectSig"); + createCustomErrorClass$1("UpdateYourApp"); + createCustomErrorClass$1("UserRefusedDeviceNameChange"); + createCustomErrorClass$1("UserRefusedAddress"); + createCustomErrorClass$1("UserRefusedFirmwareUpdate"); + createCustomErrorClass$1("UserRefusedAllowManager"); + createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); + createCustomErrorClass$1("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); + createCustomErrorClass$1("DeviceShouldStayInApp"); + createCustomErrorClass$1("WebsocketConnectionError"); + createCustomErrorClass$1("WebsocketConnectionFailed"); + createCustomErrorClass$1("WrongDeviceForAccount"); + createCustomErrorClass$1("WrongAppForCurrency"); + createCustomErrorClass$1("ETHAddressNonEIP"); + createCustomErrorClass$1("CantScanQRCode"); + createCustomErrorClass$1("FeeNotLoaded"); + createCustomErrorClass$1("FeeRequired"); + createCustomErrorClass$1("FeeTooHigh"); + createCustomErrorClass$1("SyncError"); + createCustomErrorClass$1("PairingFailed"); + createCustomErrorClass$1("GenuineCheckFailed"); + createCustomErrorClass$1("LedgerAPI4xx"); + createCustomErrorClass$1("LedgerAPI5xx"); + createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + createCustomErrorClass$1("NoDBPathGiven"); + createCustomErrorClass$1("DBWrongPassword"); + createCustomErrorClass$1("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$1(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); + var StatusCodes$1 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$1(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$1(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$1(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -42116,7 +41344,7 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$l.from(r.data.buffer); + buffer = Buffer$m.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -43120,12 +42348,12 @@ window.Buffer = buffer.Buffer; this.deviceModel = null; this._events = new EventEmitter$1(); - this.send = async (cla, ins, p1, p2, data = Buffer$l.alloc(0), statusList = [StatusCodes.OK]) => { + this.send = async (cla, ins, p1, p2, data = Buffer$m.alloc(0), statusList = [StatusCodes.OK]) => { if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - const response = await this.exchange(Buffer$l.concat([Buffer$l.from([cla, ins, p1, p2]), Buffer$l.from([data.length]), data])); + const response = await this.exchange(Buffer$m.concat([Buffer$m.from([cla, ins, p1, p2]), Buffer$m.from([data.length]), data])); const sw = response.readUInt16BE(response.length - 2); if (!statusList.some(s => s === sw)) { @@ -43388,7 +42616,7 @@ window.Buffer = buffer.Buffer; } function wrapApdu(apdu, key) { - const result = Buffer$l.alloc(apdu.length); + const result = Buffer$m.alloc(apdu.length); for (let i = 0; i < apdu.length; i++) { result[i] = apdu[i] ^ key[i % key.length]; @@ -43405,7 +42633,7 @@ window.Buffer = buffer.Buffer; function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$l.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const challenge = Buffer$m.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); const signRequest = { version: "U2F_V2", keyHandle: webSafe64(keyHandle.toString("base64")), @@ -43419,7 +42647,7 @@ window.Buffer = buffer.Buffer; } = response; if (typeof signatureData === "string") { - const data = Buffer$l.from(normal64(signatureData), "base64"); + const data = Buffer$m.from(normal64(signatureData), "base64"); let result; if (!unwrap) { @@ -43505,7 +42733,7 @@ window.Buffer = buffer.Buffer; setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$l.from(scrambleKey, "ascii"); + this.scrambleKey = Buffer$m.from(scrambleKey, "ascii"); } /** */ From 00981b77e942766784660774fe486969278d3366 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 24 Jan 2022 14:30:41 +1100 Subject: [PATCH 36/78] kludge for multisig test --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index dfa74386..6cdf84c3 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -729,7 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],false,!isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From f9456c909b5110c6cf6b6af8370de70d78e5df28 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 25 Jan 2022 09:28:07 +1100 Subject: [PATCH 37/78] Revert "kludge for multisig test" This reverts commit 00981b77e942766784660774fe486969278d3366. --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 6cdf84c3..dfa74386 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -729,7 +729,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],false,!isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); + inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From 548c7b77c043cc5e9c13a08abbfa828f0015e7ec Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 25 Jan 2022 15:20:18 +1100 Subject: [PATCH 38/78] return my packages --- index.html | 2 +- js/ledger.js | 113 ++++++++++++++++++++------------------------------- 2 files changed, 46 insertions(+), 69 deletions(-) diff --git a/index.html b/index.html index 11102462..eccde99b 100644 --- a/index.html +++ b/index.html @@ -1440,7 +1440,7 @@

Settings

- + diff --git a/js/ledger.js b/js/ledger.js index e87d1215..b0e56200 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -32925,35 +32925,6 @@ window.Buffer = buffer.Buffer; subset: subset_1$1, }; - function unsafeTo64bitLE(n) { - // we want to represent the input as a 8-bytes array - if (n > Number.MAX_SAFE_INTEGER) { - throw new Error("Can't convert numbers > MAX_SAFE_INT"); - } - var byteArray = Buffer$m.alloc(8, 0); - for (var index = 0; index < byteArray.length; index++) { - var byte = n & 0xff; - byteArray[index] = byte; - n = (n - byte) / 256; - } - return byteArray; - } - function unsafeFrom64bitLE(byteArray) { - var value = 0; - if (byteArray.length != 8) { - throw new Error("Expected Bufffer of lenght 8"); - } - if (byteArray[7] != 0) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); - } - if (byteArray[6] > 0x1f) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); - } - for (var i = byteArray.length - 1; i >= 0; i--) { - value = value * 256 + byteArray[i]; - } - return value; - } var BufferWriter = /** @class */ (function () { function BufferWriter() { this.bufs = []; @@ -32973,8 +32944,7 @@ window.Buffer = buffer.Buffer; this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); }; BufferWriter.prototype.writeUInt64 = function (i) { - var bytes = unsafeTo64bitLE(i); - this.writeSlice(bytes); + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); }; BufferWriter.prototype.writeVarInt = function (i) { this.bufs.push(varuintBitcoin.encode(i)); @@ -33016,9 +32986,9 @@ window.Buffer = buffer.Buffer; return result; }; BufferReader.prototype.readUInt64 = function () { - var buf = this.readSlice(8); - var n = unsafeFrom64bitLE(buf); - return n; + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; }; BufferReader.prototype.readVarInt = function () { var vi = varuintBitcoin.decode(this.buffer, this.offset); @@ -33240,7 +33210,7 @@ window.Buffer = buffer.Buffer; if (userSuppliedRedeemScript && !expectedRedeemScript.equals(userSuppliedRedeemScript)) { // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); } this.psbt.setInputRedeemScript(i, expectedRedeemScript); this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); @@ -33455,7 +33425,7 @@ window.Buffer = buffer.Buffer; }()); function createKey$1(masterFingerprint, path, xpub) { var accountPath = pathArrayToString(path); - return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; } /** @@ -33487,7 +33457,7 @@ window.Buffer = buffer.Buffer; var outputCount = psbt.getGlobalOutputCount(); tx.writeVarInt(outputCount); for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(psbt.getOutputAmount(i)); + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); tx.writeVarSlice(psbt.getOutputScript(i)); } tx.writeSlice(witnessWriter.buffer()); @@ -33741,8 +33711,7 @@ window.Buffer = buffer.Buffer; this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); }; PsbtV2.prototype.getOutputAmount = function (outputIndex) { - var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); - return unsafeFrom64bitLE(buf); + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); }; PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); @@ -33982,7 +33951,9 @@ window.Buffer = buffer.Buffer; return b; } function uint64LE(n) { - return unsafeTo64bitLE(n); + var b = Buffer$m.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; } function varint(n) { var b = new BufferWriter(); @@ -34014,11 +33985,11 @@ window.Buffer = buffer.Buffer; var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); var taprootSig = psbt.getInputTapKeySig(i); if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input ".concat(i, " present")); + throw Error("No signature for input " + i + " present"); } if (legacyPubkeys.length > 0) { if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); } if (taprootSig) { throw Error("Both taproot and non-taproot signatures present."); @@ -34329,7 +34300,7 @@ window.Buffer = buffer.Buffer; xpub = _b.sent(); xpubComponents = getXpubComponents(xpub); if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); } return [2 /*return*/, xpub]; } @@ -34430,7 +34401,7 @@ window.Buffer = buffer.Buffer; case 1: masterFp = _a.sent(); accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime != undefined) { + if (arg.lockTime) { // The signer will assume locktime 0 if unset psbt.setGlobalFallbackLocktime(arg.lockTime); } @@ -34541,7 +34512,7 @@ window.Buffer = buffer.Buffer; // going on. for (i = 0; i < accountPath.length; i++) { if (accountPath[i] != pathElems[i]) { - throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); } } return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; @@ -34569,10 +34540,10 @@ window.Buffer = buffer.Buffer; spentOutputIndex = input[1]; redeemScript = input[2] ? Buffer$m.from(input[2], "hex") : undefined; sequence = input[3]; - if (sequence != undefined) { + if (sequence) { psbt.setInputSequence(i, sequence); } - if (sigHashType != undefined) { + if (sigHashType) { psbt.setInputSighashType(i, sigHashType); } inputTxBuffer = serializeTransaction(inputTx, true); @@ -34623,7 +34594,7 @@ window.Buffer = buffer.Buffer; // No legacy BIP32_DERIVATION, assume we're using taproot. pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input ".concat(k)); + throw Error("Missing pubkey derivation for input " + k); } psbt.setInputTapKeySig(k, v); } @@ -36682,7 +36653,7 @@ window.Buffer = buffer.Buffer; return _this; } GetPreimageCommand.prototype.execute = function (request) { - var req = Buffer$m.from(request.subarray(1)); + var req = request.subarray(1); // we expect no more data to read if (req.length != 1 + 32) { throw new Error("Invalid request, unexpected trailing data"); @@ -36711,10 +36682,10 @@ window.Buffer = buffer.Buffer; return Buffer$m.concat([ preimage_len_varint, Buffer$m.from([payload_size]), - Buffer$m.from(known_preimage.subarray(0, payload_size)), + known_preimage.subarray(0, payload_size), ]); } - throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); + throw Error("Requested unknown preimage for: " + req_hash_hex); }; return GetPreimageCommand; }(ClientCommand)); @@ -36729,7 +36700,7 @@ window.Buffer = buffer.Buffer; } GetMerkleLeafProofCommand.prototype.execute = function (request) { var _a; - var req = Buffer$m.from(request.subarray(1)); + var req = request.subarray(1); if (req.length < 32 + 1 + 1) { throw new Error("Invalid request, expected at least 34 bytes"); } @@ -36747,7 +36718,7 @@ window.Buffer = buffer.Buffer; } var mt = this.known_trees.get(hash_hex); if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); } if (leaf_index >= tree_size || mt.size() != tree_size) { throw Error("Invalid index or tree size."); @@ -36779,7 +36750,7 @@ window.Buffer = buffer.Buffer; return _this; } GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = Buffer$m.from(request.subarray(1)); + var req = request.subarray(1); if (req.length != 32 + 32) { throw new Error("Invalid request, unexpected trailing data"); } @@ -36797,7 +36768,7 @@ window.Buffer = buffer.Buffer; var leef_hash_hex = leef_hash.toString("hex"); var mt = this.known_trees.get(root_hash_hex); if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); } var leaf_index = 0; var found = 0; @@ -36876,7 +36847,7 @@ window.Buffer = buffer.Buffer; for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { var cmd = commands_1_1.value; if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code ".concat(cmd.code)); + throw new Error("Multiple commands with code " + cmd.code); } this.commands.set(cmd.code, cmd); } @@ -36925,7 +36896,7 @@ window.Buffer = buffer.Buffer; var cmdCode = request[0]; var cmd = this.commands.get(cmdCode); if (!cmd) { - throw new Error("Unexpected command code ".concat(cmdCode)); + throw new Error("Unexpected command code " + cmdCode); } return cmd.execute(request); }; @@ -37192,16 +37163,16 @@ window.Buffer = buffer.Buffer; } transaction.inputs.forEach(function (_a, i) { var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput ".concat(i, ":"); - str += " prevout ".concat(prevout.toString("hex")); - str += " script ".concat(script.toString("hex")); - str += " sequence ".concat(sequence.toString("hex")); + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); }); (transaction.outputs || []).forEach(function (_a, i) { var amount = _a.amount, script = _a.script; - str += "\noutput ".concat(i, ":"); - str += " amount ".concat(amount.toString("hex")); - str += " script ".concat(script.toString("hex")); + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); }); return str; } @@ -37220,10 +37191,13 @@ window.Buffer = buffer.Buffer; var nVersionGroupId = Buffer$m.alloc(0); var extraData = Buffer$m.alloc(0); var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); var transaction = Buffer$m.from(transactionHex, "hex"); var version = transaction.slice(offset, offset + 4); var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$m.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$m.from([0x02, 0x00, 0x00, 0x00])); offset += 4; if (!hasTimestamp && isSegwitSupported && @@ -37233,8 +37207,11 @@ window.Buffer = buffer.Buffer; witness = true; } if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } } if (overwinter) { nVersionGroupId = transaction.slice(offset, 4 + offset); @@ -37337,7 +37314,7 @@ window.Buffer = buffer.Buffer; nExpiryHeight: nExpiryHeight, extraData: extraData }; - log$1("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); return t; } @@ -37381,7 +37358,7 @@ window.Buffer = buffer.Buffer; * Bitcoin API. * * @example - * import Btc from "@ledgerhq/hw-app-btc"; + * import Btc from "@backpacker69/hw-app-btc"; * const btc = new Btc(transport) */ var Btc = /** @class */ (function () { From 5f2e5fccb5cac6f5df77fc2b67026e7c3be28033 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 25 Jan 2022 17:21:33 +1100 Subject: [PATCH 39/78] new version --- js/cointoolkit.js | 2 +- js/ledger.js | 45743 ++++++++++++++++++++++---------------------- 2 files changed, 23270 insertions(+), 22475 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index dfa74386..a8e9f2cc 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -748,7 +748,7 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, sigHashType: hashType, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, additionals: ["peercoin"]}; result = await appBtc.signP2SHTransaction(params); var success=false; diff --git a/js/ledger.js b/js/ledger.js index b0e56200..ad61cb7f 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1033,12 +1033,12 @@ window.Buffer = buffer.Buffer; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$m.TYPED_ARRAY_SUPPORT + return Buffer$l.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1047,14 +1047,14 @@ window.Buffer = buffer.Buffer; if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$m(length); + that = new Buffer$l(length); } that.length = length; } @@ -1072,9 +1072,9 @@ window.Buffer = buffer.Buffer; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$m (arg, encodingOrOffset, length) { - if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { - return new Buffer$m(arg, encodingOrOffset, length) + function Buffer$l (arg, encodingOrOffset, length) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { + return new Buffer$l(arg, encodingOrOffset, length) } // Common case. @@ -1089,11 +1089,11 @@ window.Buffer = buffer.Buffer; return from$1(this, arg, encodingOrOffset, length) } - Buffer$m.poolSize = 8192; // not used by this implementation + Buffer$l.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$m._augment = function (arr) { - arr.__proto__ = Buffer$m.prototype; + Buffer$l._augment = function (arr) { + arr.__proto__ = Buffer$l.prototype; return arr }; @@ -1121,13 +1121,13 @@ window.Buffer = buffer.Buffer; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$m.from = function (value, encodingOrOffset, length) { + Buffer$l.from = function (value, encodingOrOffset, length) { return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { - Buffer$m.prototype.__proto__ = Uint8Array.prototype; - Buffer$m.__proto__ = Uint8Array; + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + Buffer$l.prototype.__proto__ = Uint8Array.prototype; + Buffer$l.__proto__ = Uint8Array; } function assertSize (size) { @@ -1158,14 +1158,14 @@ window.Buffer = buffer.Buffer; * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$m.alloc = function (size, fill, encoding) { + Buffer$l.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1176,13 +1176,13 @@ window.Buffer = buffer.Buffer; /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$m.allocUnsafe = function (size) { + Buffer$l.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$m.allocUnsafeSlow = function (size) { + Buffer$l.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1191,7 +1191,7 @@ window.Buffer = buffer.Buffer; encoding = 'utf8'; } - if (!Buffer$m.isEncoding(encoding)) { + if (!Buffer$l.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1238,10 +1238,10 @@ window.Buffer = buffer.Buffer; array = new Uint8Array(array, byteOffset, length); } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1288,12 +1288,12 @@ window.Buffer = buffer.Buffer; } return length | 0 } - Buffer$m.isBuffer = isBuffer; + Buffer$l.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$m.compare = function compare (a, b) { + Buffer$l.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1316,7 +1316,7 @@ window.Buffer = buffer.Buffer; return 0 }; - Buffer$m.isEncoding = function isEncoding (encoding) { + Buffer$l.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1335,13 +1335,13 @@ window.Buffer = buffer.Buffer; } }; - Buffer$m.concat = function concat (list, length) { + Buffer$l.concat = function concat (list, length) { if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$m.alloc(0) + return Buffer$l.alloc(0) } var i; @@ -1352,7 +1352,7 @@ window.Buffer = buffer.Buffer; } } - var buffer = Buffer$m.allocUnsafe(length); + var buffer = Buffer$l.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1408,7 +1408,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$m.byteLength = byteLength$1; + Buffer$l.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1482,7 +1482,7 @@ window.Buffer = buffer.Buffer; // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$m.prototype._isBuffer = true; + Buffer$l.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1490,7 +1490,7 @@ window.Buffer = buffer.Buffer; b[m] = i; } - Buffer$m.prototype.swap16 = function swap16 () { + Buffer$l.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1501,7 +1501,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$m.prototype.swap32 = function swap32 () { + Buffer$l.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1513,7 +1513,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$m.prototype.swap64 = function swap64 () { + Buffer$l.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1527,20 +1527,20 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$m.prototype.toString = function toString () { + Buffer$l.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$m.prototype.equals = function equals (b) { + Buffer$l.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$m.compare(this, b) === 0 + return Buffer$l.compare(this, b) === 0 }; - Buffer$m.prototype.inspect = function inspect () { + Buffer$l.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1550,7 +1550,7 @@ window.Buffer = buffer.Buffer; return '' }; - Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1649,7 +1649,7 @@ window.Buffer = buffer.Buffer; // Normalize val if (typeof val === 'string') { - val = Buffer$m.from(val, encoding); + val = Buffer$l.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1661,7 +1661,7 @@ window.Buffer = buffer.Buffer; return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$m.TYPED_ARRAY_SUPPORT && + if (Buffer$l.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1731,15 +1731,15 @@ window.Buffer = buffer.Buffer; return -1 } - Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1790,7 +1790,7 @@ window.Buffer = buffer.Buffer; return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$m.prototype.write = function write (string, offset, length, encoding) { + Buffer$l.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1862,7 +1862,7 @@ window.Buffer = buffer.Buffer; } }; - Buffer$m.prototype.toJSON = function toJSON () { + Buffer$l.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2015,7 +2015,7 @@ window.Buffer = buffer.Buffer; return res } - Buffer$m.prototype.slice = function slice (start, end) { + Buffer$l.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2037,12 +2037,12 @@ window.Buffer = buffer.Buffer; if (end < start) end = start; var newBuf; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$m.prototype; + newBuf.__proto__ = Buffer$l.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$m(sliceLen, undefined); + newBuf = new Buffer$l(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2059,7 +2059,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2074,7 +2074,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2090,22 +2090,22 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2114,7 +2114,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] * 0x1000000) }; - Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2123,7 +2123,7 @@ window.Buffer = buffer.Buffer; this[offset + 3]) }; - Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2141,7 +2141,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2159,25 +2159,25 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2186,7 +2186,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] << 24) }; - Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2195,22 +2195,22 @@ window.Buffer = buffer.Buffer; (this[offset + 3]) }; - Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2221,7 +2221,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2240,7 +2240,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2259,11 +2259,11 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2276,11 +2276,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2289,11 +2289,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2309,11 +2309,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2324,11 +2324,11 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2339,7 +2339,7 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2362,7 +2362,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2385,21 +2385,21 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2408,11 +2408,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2421,11 +2421,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2436,12 +2436,12 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$m.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$l.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; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2465,11 +2465,11 @@ window.Buffer = buffer.Buffer; return offset + 4 } - Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2481,16 +2481,16 @@ window.Buffer = buffer.Buffer; return offset + 8 } - Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2522,7 +2522,7 @@ window.Buffer = buffer.Buffer; for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2542,7 +2542,7 @@ window.Buffer = buffer.Buffer; // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$m.prototype.fill = function fill (val, start, end, encoding) { + Buffer$l.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2562,7 +2562,7 @@ window.Buffer = buffer.Buffer; if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2591,7 +2591,7 @@ window.Buffer = buffer.Buffer; } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$m(val, encoding).toString()); + : utf8ToBytes(new Buffer$l(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5751,7 +5751,7 @@ window.Buffer = buffer.Buffer; function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require$2 = buffer, - Buffer$l = _require$2.Buffer; + Buffer$k = _require$2.Buffer; var _require2 = require$$3, inspect$1 = _require2.inspect; @@ -5759,7 +5759,7 @@ window.Buffer = buffer.Buffer; var custom = inspect$1 && inspect$1.custom || 'inspect'; function copyBuffer(src, target, offset) { - Buffer$l.prototype.copy.call(src, target, offset); + Buffer$k.prototype.copy.call(src, target, offset); } var buffer_list = @@ -5826,8 +5826,8 @@ window.Buffer = buffer.Buffer; }, { key: "concat", value: function concat(n) { - if (this.length === 0) return Buffer$l.alloc(0); - var ret = Buffer$l.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer$k.alloc(0); + var ret = Buffer$k.allocUnsafe(n >>> 0); var p = this.head; var i = 0; @@ -5901,7 +5901,7 @@ window.Buffer = buffer.Buffer; }, { key: "_getBuffer", value: function _getBuffer(n) { - var ret = Buffer$l.allocUnsafe(n); + var ret = Buffer$k.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); @@ -6308,16 +6308,16 @@ window.Buffer = buffer.Buffer; /**/ - var Buffer$k = buffer.Buffer; + var Buffer$j = buffer.Buffer; var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer$1(chunk) { - return Buffer$k.from(chunk); + return Buffer$j.from(chunk); } function _isUint8Array$1(obj) { - return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; + return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; } var destroyImpl$1 = destroy_1; @@ -6532,7 +6532,7 @@ window.Buffer = buffer.Buffer; var isBuf = !state.objectMode && _isUint8Array$1(chunk); - if (isBuf && !Buffer$k.isBuffer(chunk)) { + if (isBuf && !Buffer$j.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer$1(chunk); } @@ -6583,7 +6583,7 @@ window.Buffer = buffer.Buffer; function decodeChunk$1(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$k.from(chunk, encoding); + chunk = Buffer$j.from(chunk, encoding); } return chunk; @@ -7052,14 +7052,14 @@ window.Buffer = buffer.Buffer; } }); - var string_decoder$1 = {}; + var string_decoder = {}; /**/ - var Buffer$j = safeBuffer.exports.Buffer; + var Buffer$i = safeBuffer.exports.Buffer; /**/ - var isEncoding = Buffer$j.isEncoding || function (encoding) { + var isEncoding = Buffer$i.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': @@ -7100,15 +7100,15 @@ window.Buffer = buffer.Buffer; // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer$j.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + if (typeof nenc !== 'string' && (Buffer$i.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. - string_decoder$1.StringDecoder = StringDecoder$3; - function StringDecoder$3(encoding) { + var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { @@ -7133,10 +7133,10 @@ window.Buffer = buffer.Buffer; } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer$j.allocUnsafe(nb); + this.lastChar = Buffer$i.allocUnsafe(nb); } - StringDecoder$3.prototype.write = function (buf) { + StringDecoder$2.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; @@ -7152,13 +7152,13 @@ window.Buffer = buffer.Buffer; return r || ''; }; - StringDecoder$3.prototype.end = utf8End; + StringDecoder$2.prototype.end = utf8End; // Returns only complete characters in a Buffer - StringDecoder$3.prototype.text = utf8Text; + StringDecoder$2.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$3.prototype.fillLast = function (buf) { + StringDecoder$2.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); @@ -7661,28 +7661,28 @@ window.Buffer = buffer.Buffer; /**/ - var Buffer$i = buffer.Buffer; + var Buffer$h = buffer.Buffer; var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { - return Buffer$i.from(chunk); + return Buffer$h.from(chunk); } function _isUint8Array(obj) { - return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = require$$3; - var debug$9; + var debug$5; if (debugUtil && debugUtil.debuglog) { - debug$9 = debugUtil.debuglog('stream'); + debug$5 = debugUtil.debuglog('stream'); } else { - debug$9 = function debug() {}; + debug$5 = function debug() {}; } /**/ @@ -7701,7 +7701,7 @@ window.Buffer = buffer.Buffer; ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - var StringDecoder$2; + var StringDecoder$1; var createReadableStreamAsyncIterator; var from; @@ -7778,8 +7778,8 @@ window.Buffer = buffer.Buffer; this.encoding = null; if (options.encoding) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - this.decoder = new StringDecoder$2(options.encoding); + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); this.encoding = options.encoding; } } @@ -7846,7 +7846,7 @@ window.Buffer = buffer.Buffer; encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$i.from(chunk, encoding); + chunk = Buffer$h.from(chunk, encoding); encoding = ''; } @@ -7865,7 +7865,7 @@ window.Buffer = buffer.Buffer; }; function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$9('readableAddChunk', chunk); + debug$5('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { @@ -7878,7 +7878,7 @@ window.Buffer = buffer.Buffer; if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { chunk = _uint8ArrayToBuffer(chunk); } @@ -7940,8 +7940,8 @@ window.Buffer = buffer.Buffer; Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - var decoder = new StringDecoder$2(enc); + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: @@ -8008,7 +8008,7 @@ window.Buffer = buffer.Buffer; Readable$1.prototype.read = function (n) { - debug$9('read', n); + debug$5('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -8017,7 +8017,7 @@ window.Buffer = buffer.Buffer; // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$9('read: emitReadable', state.length, state.ended); + debug$5('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); return null; } @@ -8052,20 +8052,20 @@ window.Buffer = buffer.Buffer; var doRead = state.needReadable; - debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$9('length less than watermark', doRead); + debug$5('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$9('reading or ended', doRead); + debug$5('reading or ended', doRead); } else if (doRead) { - debug$9('do read'); + debug$5('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -8103,7 +8103,7 @@ window.Buffer = buffer.Buffer; }; function onEofChunk$1(stream, state) { - debug$9('onEofChunk'); + debug$5('onEofChunk'); if (state.ended) return; if (state.decoder) { @@ -8138,11 +8138,11 @@ window.Buffer = buffer.Buffer; function emitReadable$1(stream) { var state = stream._readableState; - debug$9('emitReadable', state.needReadable, state.emittedReadable); + debug$5('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { - debug$9('emitReadable', state.flowing); + debug$5('emitReadable', state.flowing); state.emittedReadable = true; nextTick(emitReadable_$1, stream); } @@ -8150,7 +8150,7 @@ window.Buffer = buffer.Buffer; function emitReadable_$1(stream) { var state = stream._readableState; - debug$9('emitReadable_', state.destroyed, state.length, state.ended); + debug$5('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); @@ -8206,7 +8206,7 @@ window.Buffer = buffer.Buffer; // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; - debug$9('maybeReadMore read 0'); + debug$5('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; @@ -8242,14 +8242,14 @@ window.Buffer = buffer.Buffer; } state.pipesCount += 1; - debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { - debug$9('onunpipe'); + debug$5('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { @@ -8260,7 +8260,7 @@ window.Buffer = buffer.Buffer; } function onend() { - debug$9('onend'); + debug$5('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() @@ -8273,7 +8273,7 @@ window.Buffer = buffer.Buffer; var cleanedUp = false; function cleanup() { - debug$9('cleanup'); // cleanup event handlers once the pipe is broken + debug$5('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -8295,9 +8295,9 @@ window.Buffer = buffer.Buffer; src.on('data', ondata); function ondata(chunk) { - debug$9('ondata'); + debug$5('ondata'); var ret = dest.write(chunk); - debug$9('dest.write', ret); + debug$5('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible @@ -8305,7 +8305,7 @@ window.Buffer = buffer.Buffer; // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$9('false write response, pause', state.awaitDrain); + debug$5('false write response, pause', state.awaitDrain); state.awaitDrain++; } @@ -8316,7 +8316,7 @@ window.Buffer = buffer.Buffer; function onerror(er) { - debug$9('onerror', er); + debug$5('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); @@ -8333,7 +8333,7 @@ window.Buffer = buffer.Buffer; dest.once('close', onclose); function onfinish() { - debug$9('onfinish'); + debug$5('onfinish'); dest.removeListener('close', onclose); unpipe(); } @@ -8341,7 +8341,7 @@ window.Buffer = buffer.Buffer; dest.once('finish', onfinish); function unpipe() { - debug$9('unpipe'); + debug$5('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to @@ -8349,7 +8349,7 @@ window.Buffer = buffer.Buffer; dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { - debug$9('pipe resume'); + debug$5('pipe resume'); src.resume(); } @@ -8359,7 +8359,7 @@ window.Buffer = buffer.Buffer; function pipeOnDrain$1(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; - debug$9('pipeOnDrain', state.awaitDrain); + debug$5('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { @@ -8434,7 +8434,7 @@ window.Buffer = buffer.Buffer; state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; - debug$9('on readable', state.length, state.reading); + debug$5('on readable', state.length, state.reading); if (state.length) { emitReadable$1(this); @@ -8495,7 +8495,7 @@ window.Buffer = buffer.Buffer; } function nReadingNextTick$1(self) { - debug$9('readable nexttick read 0'); + debug$5('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. @@ -8505,7 +8505,7 @@ window.Buffer = buffer.Buffer; var state = this._readableState; if (!state.flowing) { - debug$9('resume'); // we flow only if there is no one listening + debug$5('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() @@ -8525,7 +8525,7 @@ window.Buffer = buffer.Buffer; } function resume_$1(stream, state) { - debug$9('resume', state.reading); + debug$5('resume', state.reading); if (!state.reading) { stream.read(0); @@ -8538,10 +8538,10 @@ window.Buffer = buffer.Buffer; } Readable$1.prototype.pause = function () { - debug$9('call pause flowing=%j', this._readableState.flowing); + debug$5('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { - debug$9('pause'); + debug$5('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -8552,7 +8552,7 @@ window.Buffer = buffer.Buffer; function flow$1(stream) { var state = stream._readableState; - debug$9('flow', state.flowing); + debug$5('flow', state.flowing); while (state.flowing && stream.read() !== null) { } @@ -8567,7 +8567,7 @@ window.Buffer = buffer.Buffer; var state = this._readableState; var paused = false; stream.on('end', function () { - debug$9('wrapped end'); + debug$5('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); @@ -8577,7 +8577,7 @@ window.Buffer = buffer.Buffer; _this.push(null); }); stream.on('data', function (chunk) { - debug$9('wrapped data'); + debug$5('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; @@ -8609,7 +8609,7 @@ window.Buffer = buffer.Buffer; this._read = function (n) { - debug$9('wrapped _read', n); + debug$5('wrapped _read', n); if (paused) { paused = false; @@ -8694,7 +8694,7 @@ window.Buffer = buffer.Buffer; function endReadable$1(stream) { var state = stream._readableState; - debug$9('endReadable', state.endEmitted); + debug$5('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; @@ -8703,7 +8703,7 @@ window.Buffer = buffer.Buffer; } function endReadableNT$1(state, stream) { - debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; @@ -9000,12 +9000,12 @@ window.Buffer = buffer.Buffer; exports.pipeline = pipeline_1; }(readableBrowser, readableBrowser.exports)); - var Buffer$h = safeBuffer.exports.Buffer; + var Buffer$g = safeBuffer.exports.Buffer; var Transform$2 = readableBrowser.exports.Transform; var inherits$i = inherits_browser.exports; function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer') } } @@ -9013,7 +9013,7 @@ window.Buffer = buffer.Buffer; function HashBase$2 (blockSize) { Transform$2.call(this); - this._block = Buffer$h.allocUnsafe(blockSize); + this._block = Buffer$g.allocUnsafe(blockSize); this._blockSize = blockSize; this._blockOffset = 0; this._length = [0, 0, 0, 0]; @@ -9048,7 +9048,7 @@ window.Buffer = buffer.Buffer; HashBase$2.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data'); if (this._finalized) throw new Error('Digest already called') - if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); // consume data var block = this._block; @@ -9097,7 +9097,7 @@ window.Buffer = buffer.Buffer; var inherits$h = inherits_browser.exports; var HashBase$1 = hashBase; - var Buffer$g = safeBuffer.exports.Buffer; + var Buffer$f = safeBuffer.exports.Buffer; var ARRAY16$1 = new Array(16); @@ -9211,7 +9211,7 @@ window.Buffer = buffer.Buffer; this._update(); // produce result - var buffer = Buffer$g.allocUnsafe(16); + var buffer = Buffer$f.allocUnsafe(16); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9241,7 +9241,7 @@ window.Buffer = buffer.Buffer; var md5_js = MD5$2; - var Buffer$f = buffer.Buffer; + var Buffer$e = buffer.Buffer; var inherits$g = inherits_browser.exports; var HashBase = hashBase; @@ -9369,7 +9369,7 @@ window.Buffer = buffer.Buffer; this._update(); // produce result - var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9406,11 +9406,11 @@ window.Buffer = buffer.Buffer; var sha_js = {exports: {}}; - var Buffer$e = safeBuffer.exports.Buffer; + var Buffer$d = safeBuffer.exports.Buffer; // prototype class for hash functions function Hash$7 (blockSize, finalSize) { - this._block = Buffer$e.alloc(blockSize); + this._block = Buffer$d.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; @@ -9419,7 +9419,7 @@ window.Buffer = buffer.Buffer; Hash$7.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8'; - data = Buffer$e.from(data, enc); + data = Buffer$d.from(data, enc); } var block = this._block; @@ -9498,7 +9498,7 @@ window.Buffer = buffer.Buffer; var inherits$f = inherits_browser.exports; var Hash$6 = hash$3; - var Buffer$d = safeBuffer.exports.Buffer; + var Buffer$c = safeBuffer.exports.Buffer; var K$4 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9570,7 +9570,7 @@ window.Buffer = buffer.Buffer; }; Sha.prototype._hash = function () { - var H = Buffer$d.allocUnsafe(20); + var H = Buffer$c.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9594,7 +9594,7 @@ window.Buffer = buffer.Buffer; var inherits$e = inherits_browser.exports; var Hash$5 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + var Buffer$b = safeBuffer.exports.Buffer; var K$3 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9670,7 +9670,7 @@ window.Buffer = buffer.Buffer; }; Sha1.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + var H = Buffer$b.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9693,7 +9693,7 @@ window.Buffer = buffer.Buffer; var inherits$d = inherits_browser.exports; var Hash$4 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + var Buffer$a = safeBuffer.exports.Buffer; var K$2 = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, @@ -9803,7 +9803,7 @@ window.Buffer = buffer.Buffer; }; Sha256$1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(32); + var H = Buffer$a.allocUnsafe(32); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9830,7 +9830,7 @@ window.Buffer = buffer.Buffer; var inherits$c = inherits_browser.exports; var Sha256 = sha256$2; var Hash$3 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + var Buffer$9 = safeBuffer.exports.Buffer; var W$2 = new Array(64); @@ -9858,7 +9858,7 @@ window.Buffer = buffer.Buffer; }; Sha224.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(28); + var H = Buffer$9.allocUnsafe(28); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9875,7 +9875,7 @@ window.Buffer = buffer.Buffer; var inherits$b = inherits_browser.exports; var Hash$2 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + var Buffer$8 = safeBuffer.exports.Buffer; var K$1 = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, @@ -10113,7 +10113,7 @@ window.Buffer = buffer.Buffer; }; Sha512.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(64); + var H = Buffer$8.allocUnsafe(64); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10137,7 +10137,7 @@ window.Buffer = buffer.Buffer; var inherits$a = inherits_browser.exports; var SHA512$2 = sha512; var Hash$1 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + var Buffer$7 = safeBuffer.exports.Buffer; var W = new Array(160); @@ -10173,7 +10173,7 @@ window.Buffer = buffer.Buffer; }; Sha384.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(48); + var H = Buffer$7.allocUnsafe(48); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10768,234 +10768,9 @@ window.Buffer = buffer.Buffer; return ret; }; - var string_decoder = {}; - - var StringDecoder_1; - // 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$7 = buffer.Buffer; - - var isBufferEncoding = Buffer$7.isEncoding - || function(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 assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } - - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$7(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; - - - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$1.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; - }; - - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; - - StringDecoder$1.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; - }; - - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } - - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } - - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - Readable.ReadableState = ReadableState; - var debug$8 = debuglog('stream'); + var debug$4 = debuglog('stream'); inherits$9(Readable, EventEmitter$1); function prependListener(emitter, event, fn) { @@ -11109,7 +10884,7 @@ window.Buffer = buffer.Buffer; if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$m.from(chunk, encoding); + chunk = Buffer$l.from(chunk, encoding); encoding = ''; } } @@ -11234,7 +11009,7 @@ window.Buffer = buffer.Buffer; // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { - debug$8('read', n); + debug$4('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -11245,7 +11020,7 @@ window.Buffer = buffer.Buffer; // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$8('read: emitReadable', state.length, state.ended); + debug$4('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } @@ -11282,21 +11057,21 @@ window.Buffer = buffer.Buffer; // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; - debug$8('need readable', doRead); + debug$4('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$8('length less than watermark', doRead); + debug$4('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$8('reading or ended', doRead); + debug$4('reading or ended', doRead); } else if (doRead) { - debug$8('do read'); + debug$4('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -11363,14 +11138,14 @@ window.Buffer = buffer.Buffer; var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { - debug$8('emitReadable', state.flowing); + debug$4('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { - debug$8('emit readable'); + debug$4('emit readable'); stream.emit('readable'); flow(stream); } @@ -11391,7 +11166,7 @@ window.Buffer = buffer.Buffer; function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$8('maybeReadMore read 0'); + debug$4('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. @@ -11424,7 +11199,7 @@ window.Buffer = buffer.Buffer; break; } state.pipesCount += 1; - debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false); @@ -11433,14 +11208,14 @@ window.Buffer = buffer.Buffer; dest.on('unpipe', onunpipe); function onunpipe(readable) { - debug$8('onunpipe'); + debug$4('onunpipe'); if (readable === src) { cleanup(); } } function onend() { - debug$8('onend'); + debug$4('onend'); dest.end(); } @@ -11453,7 +11228,7 @@ window.Buffer = buffer.Buffer; var cleanedUp = false; function cleanup() { - debug$8('cleanup'); + debug$4('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -11481,7 +11256,7 @@ window.Buffer = buffer.Buffer; var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { - debug$8('ondata'); + debug$4('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { @@ -11490,7 +11265,7 @@ window.Buffer = buffer.Buffer; // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$8('false write response, pause', src._readableState.awaitDrain); + debug$4('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } @@ -11501,7 +11276,7 @@ window.Buffer = buffer.Buffer; // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { - debug$8('onerror', er); + debug$4('onerror', er); unpipe(); dest.removeListener('error', onerror); if (listenerCount(dest, 'error') === 0) dest.emit('error', er); @@ -11517,14 +11292,14 @@ window.Buffer = buffer.Buffer; } dest.once('close', onclose); function onfinish() { - debug$8('onfinish'); + debug$4('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { - debug$8('unpipe'); + debug$4('unpipe'); src.unpipe(dest); } @@ -11533,7 +11308,7 @@ window.Buffer = buffer.Buffer; // start the flow if it hasn't been started already. if (!state.flowing) { - debug$8('pipe resume'); + debug$4('pipe resume'); src.resume(); } @@ -11543,7 +11318,7 @@ window.Buffer = buffer.Buffer; function pipeOnDrain(src) { return function () { var state = src._readableState; - debug$8('pipeOnDrain', state.awaitDrain); + debug$4('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && src.listeners('data').length) { state.flowing = true; @@ -11627,7 +11402,7 @@ window.Buffer = buffer.Buffer; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { - debug$8('readable nexttick read 0'); + debug$4('readable nexttick read 0'); self.read(0); } @@ -11636,7 +11411,7 @@ window.Buffer = buffer.Buffer; Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { - debug$8('resume'); + debug$4('resume'); state.flowing = true; resume(this, state); } @@ -11652,7 +11427,7 @@ window.Buffer = buffer.Buffer; function resume_(stream, state) { if (!state.reading) { - debug$8('resume read 0'); + debug$4('resume read 0'); stream.read(0); } @@ -11664,9 +11439,9 @@ window.Buffer = buffer.Buffer; } Readable.prototype.pause = function () { - debug$8('call pause flowing=%j', this._readableState.flowing); + debug$4('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { - debug$8('pause'); + debug$4('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -11675,7 +11450,7 @@ window.Buffer = buffer.Buffer; function flow(stream) { var state = stream._readableState; - debug$8('flow', state.flowing); + debug$4('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } @@ -11688,7 +11463,7 @@ window.Buffer = buffer.Buffer; var self = this; stream.on('end', function () { - debug$8('wrapped end'); + debug$4('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); @@ -11698,7 +11473,7 @@ window.Buffer = buffer.Buffer; }); stream.on('data', function (chunk) { - debug$8('wrapped data'); + debug$4('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode @@ -11732,7 +11507,7 @@ window.Buffer = buffer.Buffer; // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function (n) { - debug$8('wrapped _read', n); + debug$4('wrapped _read', n); if (paused) { paused = false; stream.resume(); @@ -11819,7 +11594,7 @@ window.Buffer = buffer.Buffer; // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { - var ret = Buffer$m.allocUnsafe(n); + var ret = Buffer$l.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -12963,7 +12738,7 @@ window.Buffer = buffer.Buffer; var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$m.alloc(1 + paths.length * 4); + var buffer = Buffer$l.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -13152,7 +12927,7 @@ window.Buffer = buffer.Buffer; } crypto$5.hmacSHA512 = hmacSHA512; - var bn = {exports: {}}; + var bn$1 = {exports: {}}; (function (module) { (function (module, exports) { @@ -16598,7 +16373,7 @@ window.Buffer = buffer.Buffer; return res._forceRed(this); }; })(module, commonjsGlobal); - }(bn)); + }(bn$1)); var elliptic = {}; @@ -16675,2303 +16450,3503 @@ window.Buffer = buffer.Buffer; var utils$n = {}; - var minimalisticAssert = assert$f; + var bn = {exports: {}}; - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } + (function (module) { + (function (module, exports) { - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - var utils$m = {}; + // 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; + } - (function (exports) { + // BN - var utils = exports; + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - 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; + 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 (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)); + if (typeof module === 'object') { + module.exports = BN; } 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); + 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 = require('buffer').Buffer; } + } catch (e) { } - return res; - } - utils.toArray = toArray; - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils.zero2 = zero2; + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils.toHex = toHex; + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; - }; - }(utils$m)); + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - (function (exports) { + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - utils.assert = minAssert; - utils.toArray = minUtils.toArray; - utils.zero2 = minUtils.zero2; - utils.toHex = minUtils.toHex; - utils.encode = minUtils.encode; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - // 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); + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - var ws = 1 << (w + 1); - var k = num.clone(); + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - 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); + 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 { - z = 0; + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - naf[i] = z; - k.iushrn(1); - } + if (endian !== 'le') return; - return naf; - } - utils.getNAF = getNAF; + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - // Represent k1, k2 in a Joint Sparse Form - function getJSF(k1, k2) { - var jsf = [ - [], - [], - ]; + 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; + } - 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; + 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; } - jsf[0].push(u1); - var u2; - if ((m24 & 1) === 0) { - u2 = 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 { - m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + return (c - 48) & 0xf; } - 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); + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; } - return jsf; - } - utils.getJSF = getJSF; + 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; + } - 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; + // 24-bits chunks + var off = 0; + var j = 0; - function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; - } - utils.parseBytes = parseBytes; + 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; + } + } + } - function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); - } - utils.intFromLE = intFromLE; - }(utils$n)); + this.strip(); + }; - var brorand = {exports: {}}; + 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; - var r$1; + r *= mul; - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - return r$1.generate(len); - }; + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - function Rand(rand) { - this.rand = rand; - } - brorand.exports.Rand = Rand; + // '0' - '9' + } else { + r += c; + } + } + return r; + } - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - 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$4 = require('crypto'); - if (typeof crypto$4.randomBytes !== 'function') - throw new Error('Not supported'); + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - Rand.prototype._rand = function _rand(n) { - return crypto$4.randomBytes(n); - }; - } catch (e) { - } - } + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - var curve = {}; + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); + for (i = 0; i < mod; i++) { + pow *= base; + } - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); + this.strip(); + }; - // Curve configuration, optional - this.n = conf.n && new BN$8(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + 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; + }; - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - this._bitLength = this.n ? this.n.bitLength() : 0; + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; - // 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); - } - } - var base = BaseCurve; + // 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(); + }; - BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); - }; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); - }; + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$e(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; + var zeros = []; + var groupSizes = []; + var groupBases = []; - // 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 s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; } - - 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()); + 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; } - a = a.add(b); + groupSizes[base] = groupSize; + groupBases[base] = groupBase; } - 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; + 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' + ]; - // Get NAF form - var naf = getNAF(k, w, this._bitLength); + 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 + ]; - // 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); + 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 + ]; - if (i < 0) - break; - var z = naf[i]; - assert$e(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; - }; + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; - BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; + 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; + } - // 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; - } + 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); - // 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; + 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; } - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; + assert(false, 'Base should be between 2 and 36'); + }; - // 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()); + 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; + }; - 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 */ - ]; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - 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; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - var k = 0; + 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'); - 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; + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); - for (j = 0; j < len; j++) { - var z = tmp[j]; - 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(); + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (i = 0; i < len; i++) - wnd[i] = null; + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - if (jacobianResult) - return acc; - else - return acc.toP(); - }; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; - } - BaseCurve.BasePoint = BasePoint; + res[i] = b; + } - BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); - }; + for (; i < reqLength; i++) { + res[i] = 0; + } + } - BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); - }; + return res; + }; - BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$l.toArray(bytes, enc); + 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; + }; + } - var len = this.p.byteLength(); + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - // 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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(bytes[bytes.length - 1] % 2 === 1); + 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; + }; - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); + // 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; + }; - 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); + 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; } - throw new Error('Unknown point format'); - }; - BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); - }; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); + 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; + }; - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); - }; + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); - }; + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - var precomputed = { - doubles: null, - naf: null, - beta: null, + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - return this; - }; + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } - BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; + return this; + }; - var doubles = this.precomputed.doubles; - if (!doubles) - return false; + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); - }; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + return this.strip(); + }; - 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, + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); }; - }; - BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; + // 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); + }; - 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, + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); }; - }; - BasePoint.prototype._getBeta = function _getBeta() { - return null; - }; + // 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; + } - BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; - }; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$3 = inherits_browser.exports; - var Base$2 = base; + this.length = b.length; - var assert$d = utils$k.assert; + return this.strip(); + }; - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); + // 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); + }; - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; - // 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$3(ShortCurve, Base$2); - var short = ShortCurve; + // 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; + } - ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } } - } - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN$7(vec.a, 16), - b: new BN$7(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } + this.length = a.length; - return { - beta: beta, - lambda: lambda, - basis: basis, + return this.strip(); }; - }; - - 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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; - }; + // 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); + }; - ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(1); + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - // 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 bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - 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)); + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + if (bitsLeft > 0) { + bytesNeeded--; } - 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; - } + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ]; - }; + // And remove leading zeroes + return this.strip(); + }; - ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); + var off = (bit / 26) | 0; + var wbit = bit % 26; - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; - }; + this._expand(off + 1); - ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$7(x, 16); - if (!x.red) - x = x.toRed(this.red); + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - 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'); + return this.strip(); + }; - // 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(); + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; - return this.point(x, y); - }; + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } - 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); - } + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } - 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); + 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; + } - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; + 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 res; - }; - - function Point$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - Point$2.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); + // 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; + } - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + if (this.length > num.length) return this.clone().iadd(num); - 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); - }; + return num.clone().iadd(this); + }; - Point$2.prototype.dbl = function dbl() { - if (this.inf) - return 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(); - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } - var a = this.curve.a; + // At this point both numbers are positive + var cmp = this.cmp(num); - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } - 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); - }; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - Point$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; + 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; + } - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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); - }; + this.length = Math.max(this.length, i); - Point$2.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); - }; + if (a !== this) { + this.negative = 1; + } - Point$2.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); - }; + return this.strip(); + }; - Point$2.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); - }; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; - Point$2.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + 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; - 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; - }; + // 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; - Point$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; + 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--; + } - function JPoint(curve, x, y, z) { - Base$2.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(z, 16); + return out.strip(); } - 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$3(JPoint, Base$2.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; + // 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; - // P + O = P - if (p.isInfinity()) - return this; + 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) ; 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(); + }; - // 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)); + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; - 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(); - } + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + BN.prototype.iabs = function iabs () { + this.negative = 0; - 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; + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; - JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; - // P + O = P - if (p.isInfinity()) - return this; + this._expand(len); - // 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 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; + } - 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(); - } + if (carry === 0) return this.strip(); - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + // 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; - 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.strip(); + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; - JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); + var a = this.clone(); + var b = num; - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (i = 0; i < pow; i++) - r = r.dbl(); - return r; - } + // 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); + } - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; + 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; + } - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + a.isub(b); + } while (true); - // 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)); + return b.iushln(shift); + }; - 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); + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; - jx = nx; - jz = nz; - jyd = dny; - } + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); - }; + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; - JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); - }; + // 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; - 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 + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } - // 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); + // 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; + }; - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; - // 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 + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; - // 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(); + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); + this.strip(); - // 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); - } + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - return this.curve.jpoint(nx, ny, nz); - }; + assert(num <= 0x3ffffff, 'Number is too big'); - 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 + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; - // 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 + // 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; - // 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); - } + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; - return this.curve.jpoint(nx, ny, nz); - }; + // 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; - JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; - 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); + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; - 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); + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; - JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; - // 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); + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; - JPoint.prototype.mul = function mul(k, kbase) { - k = new BN$7(k, kbase); + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; - return this.curve._wnafMul(this, k); - }; + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; - JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + 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); + }; - if (this === p) - return true; + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; - // 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; + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; - // 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; - }; + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - 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; + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; - 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; + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; - var BN$6 = bn.exports; - var inherits$2 = inherits_browser.exports; - var Base$1 = base; + 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); + }; - var utils$j = utils$n; + 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); + }; - function MontCurve(conf) { - Base$1.call(this, 'mont', conf); + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); - } - inherits$2(MontCurve, Base$1); - var mont = MontCurve; + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; - 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(); + // 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); + }; - return y.redSqr().cmp(rhs) === 0; - }; + 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); + }; - function Point$1(curve, x, z) { - Base$1.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$6(x, 16); - this.z = new BN$6(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$2(Point$1, Base$1.BasePoint); + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; + // 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); - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; + this.tmp = this._tmp(); + } - Point$1.prototype.precompute = function precompute() { - // No-op - }; + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; + 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; - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + 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(); + } + } - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + return r; + }; - Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; - // 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); - }; + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; - Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); - Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - // 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); - }; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; - Point$1.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 + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - 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(); + 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 { - // 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(); + input.length -= 9; } - } - return b; - }; - - Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + }; - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; + // 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); + } - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; - }; + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); - return this.x.fromRed(); - }; + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$1 = inherits_browser.exports; - var Base = base; + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); - var assert$c = utils$i.assert; + 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; - 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; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; - Base.call(this, 'edwards', conf); + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; - this.a = new BN$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); + 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; - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits$1(EdwardsCurve, Base); - var edwards = EdwardsCurve; + return prime; + }; - EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); - }; + // + // 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; + } + } - EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); - }; + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - // Just for compatibility with Short curve - EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); - }; + 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'); + }; - EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$5(x, 16); - if (!x.red) - x = x.toRed(this.red); + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; - 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)); + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + return this.m.sub(a)._forceRed(this); + }; - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + Red.prototype.add = function add (a, b) { + this._verify2(a, b); - return this.point(x, y); - }; + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; - EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN$5(y, 16); - if (!y.red) - y = y.toRed(this.red); + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); - // 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()); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); - return this.point(x, y); - }; + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; - EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; - 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))); + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; - return lhs.cmp(rhs) === 0; - }; + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; - 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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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; + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; - // 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$1(Point, Base.BasePoint); + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); - EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); - }; + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); - EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); - }; + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } - Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); - }; + // 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()); - Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); - 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)); - }; + // 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); - Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - // 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); - }; + 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)); - 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 + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } - // 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(); + return r; + }; - 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); + 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 { - // 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); + return this.imod(inv); } - } 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(); - }; + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); - Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M + 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); + } - // 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); - }; + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S + 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); + } - // 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); - }; + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); - }; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } - Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); - }; + return res; + }; - Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); - }; + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); - }; + return r === num ? r.clone() : r; + }; - Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; - // 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; - }; + // + // Montgomery method engine + // - Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); - }; + BN.mont = function mont (num) { + return new Mont(num); + }; - Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); - }; + function Mont (m) { + Red.call(this, m); - Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); - }; + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } - Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; - }; + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; + 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); - 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; + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - // Compatibility with BaseCurve - Point.prototype.toP = Point.prototype.normalize; - Point.prototype.mixedAdd = Point.prototype.add; + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - (function (exports) { + 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; - var curve = exports; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); + return res._forceRed(this); + }; - var curves$2 = {}; + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var hash$2 = {}; + 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); + } - var utils$h = {}; + return res._forceRed(this); + }; - var assert$b = minimalisticAssert; - var inherits = inherits_browser.exports; + 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); + }; + })(module, commonjsGlobal); + }(bn)); - utils$h.inherits = inherits; + var minimalisticAssert = assert$f; - 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 assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); } - 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; - } - utils$h.toArray = toArray; + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils$h.toHex = toHex; + var utils$m = {}; - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.htonl = htonl; + (function (exports) { + + var utils = exports; - 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)); + 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$h.toHex32 = toHex32; + utils.toArray = toArray; function zero2(word) { if (word.length === 1) @@ -18979,17591 +19954,16309 @@ window.Buffer = buffer.Buffer; else return word; } - utils$h.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; - } - utils$h.zero8 = zero8; - - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.join32 = join32; + utils.zero2 = zero2; - 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; - } - } + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); return res; } - utils$h.split32 = split32; - - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); - } - utils$h.rotr32 = rotr32$1; - - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; - - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; + utils.toHex = toHex; - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + }(utils$m)); - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; + (function (exports) { - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - utils$h.sum32_5 = sum32_5$2; + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; - function sum64$1(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; - } - utils$h.sum64 = sum64$1; + // 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); - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - utils$h.sum64_hi = sum64_hi$1; + var ws = 1 << (w + 1); + var k = num.clone(); - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - utils$h.sum64_lo = sum64_lo$1; + 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; + } - function sum64_4_hi$1(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; + naf[i] = z; + k.iushrn(1); + } - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; + return naf; } - utils$h.sum64_4_hi = sum64_4_hi$1; + utils.getNAF = getNAF; - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; - function sum64_5_hi$1(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; + 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 hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; - } - utils$h.sum64_5_hi = sum64_5_hi$1; + 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); - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; + // 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 lo >>> 0; + return jsf; } - utils$h.sum64_5_lo = sum64_5_lo$1; + utils.getJSF = getJSF; - function rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; + 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$h.rotr64_hi = rotr64_hi$1; + utils.cachedProperty = cachedProperty; - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; } - utils$h.rotr64_lo = rotr64_lo$1; + utils.parseBytes = parseBytes; - function shr64_hi$1(ah, al, num) { - return ah >>> num; + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); } - utils$h.shr64_hi = shr64_hi$1; + utils.intFromLE = intFromLE; + }(utils$n)); - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.shr64_lo = shr64_lo$1; + var brorand = {exports: {}}; - var common$5 = {}; + var r$1; - var utils$g = utils$h; - var assert$a = minimalisticAssert; + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); - function BlockHash$4() { - 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'; + return r$1.generate(len); + }; - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; + function Rand(rand) { + this.rand = rand; } - common$5.BlockHash = BlockHash$4; - - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.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$g.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); - } + brorand.exports.Rand = Rand; - return this; + Rand.prototype.generate = function generate(len) { + return this._rand(len); }; - BlockHash$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); - return this._digest(enc); + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; }; - BlockHash$4.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; + 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; + }; - for (t = 8; t < this.padLength; t++) - res[i++] = 0; + // 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$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); - return res; - }; - - var sha = {}; - - var common$4 = {}; + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { + } + } - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; + var curve = {}; - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; + // Curve configuration, optional + this.n = conf.n && new BN$8(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; + this._bitLength = this.n ? this.n.bitLength() : 0; - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + // 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); + } } - common$4.g1_256 = g1_256$1; - - var utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; + var base = BaseCurve; - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); + }; - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); + }; - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$e(p.precomputed); + var doubles = p._getDoubles(); - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); - } + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; - utils$e.inherits(SHA1, BlockHash$3); - var _1 = SHA1; + // 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); + } - SHA1.blockSize = 512; - SHA1.outSize = 160; - SHA1.hmacStrength = 80; - SHA1.padLength = 64; + 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(); + }; - SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; - for(; i < W.length; i++) - W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + // Get NAF form + var naf = getNAF(k, w, this._bitLength); - 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]; + // 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); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; + if (i < 0) + break; + var z = naf[i]; + assert$e(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()); + } } - - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); + return p.type === 'affine' ? acc.toP() : acc; }; - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); - }; + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; + // 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; + } - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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; + // 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 BlockHash$2 = common$2.BlockHash; + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; - 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 - ]; + // 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()); + } - function SHA256$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); + 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 */ + ]; - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$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; - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } - SHA256$1.prototype._update = function _update(msg, start) { - var W = this.W; + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + 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; - 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]; + for (j = 0; j < len; j++) { + var z = tmp[j]; + 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(); - assert$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } } + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; - - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); + if (jacobianResult) + return acc; else - return utils$d.split32(this.h, 'big'); + return acc.toP(); }; - var utils$c = utils$h; - var SHA256 = _256; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; } - utils$c.inherits(SHA224, SHA256); - var _224 = SHA224; + BaseCurve.BasePoint = BasePoint; - SHA224.blockSize = 512; - SHA224.outSize = 224; - SHA224.hmacStrength = 192; - SHA224.padLength = 64; + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; - SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); }; - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils$l.toArray(bytes, enc); - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; + var len = this.p.byteLength(); - var BlockHash$1 = common$1.BlockHash; + // 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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(bytes[bytes.length - 1] % 2 === 1); - 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 - ]; + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); - function SHA512$1() { - if (!(this instanceof SHA512$1)) - return new SHA512$1(); + 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'); + }; - BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); - var _512 = SHA512$1; + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; - SHA512$1.blockSize = 1024; - SHA512$1.outSize = 512; - SHA512$1.hmacStrength = 192; - SHA512$1.padLength = 128; + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); - SHA512$1.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - // 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]; + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); + }; - 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); - } + BasePoint.prototype.encode = function encode(enc, compact) { + return utils$l.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); }; - SHA512$1.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; - var W = this.W; + 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, + }; + }; - 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]; + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; - assert$8(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); - 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 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, + }; + }; - 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); + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; - 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); + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; - hh = gh; - hl = gl; + var assert$d = utils$k.assert; - gh = fh; - gl = fl; + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); - fh = eh; - fl = el; + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - dh = ch; - dl = cl; + // 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$3(ShortCurve, Base$2); + var short = ShortCurve; - ch = bh; - cl = bl; + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; - bh = ah; - bl = al; + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN$7(vec.a, 16), + b: new BN$7(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); } - 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); + return { + beta: beta, + lambda: lambda, + basis: basis, + }; }; - SHA512$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.split32(this.h, 'big'); + 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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; }; - function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; - } + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(1); - function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; - } + // 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; - function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; - } + 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)); - 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 + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; - 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 len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } - 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 + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; + }; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; - 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 c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); - 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); + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$7(x, 16); + if (!x.red) + x = x.toRed(this.red); - 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 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'); - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + // 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(); - 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); + return this.point(x, y); + }; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; - 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 x = point.x; + var y = point.y; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + 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; + }; - var utils$a = utils$h; + 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(); - var SHA512 = _512; + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } - function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); + 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); - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; + // 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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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; + } } - utils$a.inherits(SHA384, SHA512); - var _384 = SHA384; + inherits$3(Point$2, Base$2.BasePoint); - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); }; - sha.sha1 = _1; - sha.sha224 = _224; - sha.sha256 = _256; - sha.sha384 = _384; - sha.sha512 = _512; + Point$2.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; - var ripemd = {}; + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; - var utils$9 = utils$h; - var common = common$5; + 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; + }; - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; - var BlockHash = common.BlockHash; + Point$2.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; - function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); + 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), + }, + } ]; + }; - BlockHash.call(this); + Point$2.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; - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils$9.inherits(RIPEMD160, BlockHash); - ripemd.ripemd160 = RIPEMD160; + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } - RIPEMD160.blockSize = 512; - RIPEMD160.outSize = 160; - RIPEMD160.hmacStrength = 192; - RIPEMD160.padLength = 64; + 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; + }; - 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; + Point$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; }; - RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); - else - return utils$9.split32(this.h, 'little'); + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; }; - 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)); - } + Point$2.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; - 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; - } + // P + O = P + if (p.inf) + return this; - 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; - } + // P + P = 2P + if (this.eq(p)) + return this.dbl(); - 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 - ]; + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); - 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 - ]; + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); - 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 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); + }; - 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 - ]; + Point$2.prototype.dbl = function dbl() { + if (this.inf) + return this; - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); - 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; + var a = this.curve.a; - this._init(utils$8.toArray(key, enc)); - } - var hmac = Hmac; + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(key.length <= this.blockSize); + 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); + }; - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); + Point$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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); }; - Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; + Point$2.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); }; - Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); + Point$2.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); }; - (function (exports) { - var hash = exports; + Point$2.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); + }; - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha; - hash.ripemd = ripemd; - hash.hmac = hmac; + Point$2.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; - // 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; - }(hash$2)); + 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; + }; - (function (exports) { + Point$2.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); - var curves = exports; + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; - var hash = hash$2; - var curve$1 = curve; - var utils = utils$n; + function JPoint(curve, x, y, z) { + Base$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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); - var assert = utils.assert; + this.zOne = this.z === this.curve.one; + } + inherits$3(JPoint, Base$2.BasePoint); - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; + ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); + }; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); - } - curves.PresetCurve = PresetCurve; + JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); - 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; - }, - }); - } + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); - 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', - ], - }); + return this.curve.point(ax, ay); + }; - 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', - ], - }); + JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; - 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', - ], - }); + JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; - 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', - ], - }); + // P + O = P + if (p.isInfinity()) + return this; - 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', - ], - }); + // 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); - 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', - ], - }); + 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); - 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', + return this.curve.jpoint(nx, ny, nz); + }; - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658', - ], - }); + JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); - var pre; - try { - pre = require('./precomputed/secp256k1'); - } catch (e) { - pre = undefined; - } + // P + O = P + if (p.isInfinity()) + return this; - 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, + // 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); - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3', - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15', - }, - ], + 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(); + } - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre, - ], - }); - }(curves$2)); + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); - var hash$1 = hash$2; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; + 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); - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + return this.curve.jpoint(nx, ny, nz); + }; - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow; i++) + r = r.dbl(); + return r; + } - var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; - HmacDRBG$1.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); - 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; + // 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; } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; - HmacDRBG$1.prototype._hmac = function hmac() { - return new hash$1.hmac(this.hash, this.K); + 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(); }; - HmacDRBG$1.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; + 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 - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); - }; + // 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); - HmacDRBG$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); + // 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 - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + // 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(); - this._update(entropy.concat(add || [])); - this._reseed = 1; + // 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); }; - HmacDRBG$1.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); + 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 - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } + // 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 - // Optional additional data - if (add) { - add = utils$7.toArray(add, addEnc || 'hex'); - this._update(add); + // 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); } - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } + return this.curve.jpoint(nx, ny, nz); + }; - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils$7.encode(res, enc); + 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); }; - var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; + JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); - function KeyPair$4(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); - } - var key$1 = KeyPair$4; + // 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); - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; + return this.curve.jpoint(nx, ny, nz); + }; - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); + JPoint.prototype.mul = function mul(k, kbase) { + k = new BN$7(k, kbase); + + return this.curve._wnafMul(this, k); }; - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; + JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); + 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; }; - KeyPair$4.prototype.validate = function validate() { - var pub = this.getPublic(); + 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; - 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' }; + 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; - return { result: true, reason: null }; + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + }; + + JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; }; - KeyPair$4.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } + JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); + var BN$6 = bn.exports; + var inherits$2 = inherits_browser.exports; + var Base$1 = base; - if (!enc) - return this.pub; + var utils$j = utils$n; - return this.pub.encode(enc, compact); - }; + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); - KeyPair$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$2(MontCurve, Base$1); + var mont = MontCurve; - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(key, enc || 16); + 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(); - // 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); + return y.redSqr().cmp(rhs) === 0; }; - KeyPair$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; + function Point$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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); } - this.pub = this.ec.curve.decodePoint(key, enc); - }; + } + inherits$2(Point$1, Base$1.BasePoint); - // ECDH - KeyPair$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); }; - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); }; - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); }; - KeyPair$4.prototype.inspect = function inspect() { - return ''; + Point$1.prototype.precompute = function precompute() { + // No-op }; - var BN$3 = bn.exports; - - var utils$5 = utils$n; - var assert$4 = utils$5.assert; + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; - if (this._importDER(options, enc)) - return; + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; - function Position() { - this.place = 0; - } + Point$1.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A - function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; + // 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); + }; - // Indefinite length or overflow - if (octetLen === 0 || octetLen > 4) { - return false; - } + Point$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - val >>>= 0; - } + Point$1.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A - // Leading zeroes - if (val <= 0x7f) { - return false; - } + // 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); + }; - p.place = off; - return val; - } + Point$1.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 - 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); - } + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); - Signature$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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); + 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 { - // Leading zeroes - return false; + // 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(); } } - - this.r = new BN$3(r); - this.s = new BN$3(s); - this.recoveryParam = null; - - return true; + return b; }; - 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$3.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); + Point$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; - r = rmPadding(r); - s = rmPadding(s); + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; - 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$5.encode(res, enc); + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; }; - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; - var KeyPair$3 = key$1; - var Signature$2 = signature$1; + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); + return this.x.fromRed(); + }; - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$1 = inherits_browser.exports; + var Base = base; - options = curves$1[options]; - } + var assert$c = utils$i.assert; - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.PresetCurve) - options = { curve: options }; + 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; - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; + Base.call(this, 'edwards', conf); - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); + this.a = new BN$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; } - var ec = EC$1; + inherits$1(EdwardsCurve, Base); + var edwards = EdwardsCurve; - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); + EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); }; - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); + EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); }; - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); + // Just for compatibility with Short curve + EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); }; - EC$1.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; + EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$5(x, 16); + if (!x.red) + x = x.toRed(this.red); - // 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 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 bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN$2(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); - EC$1.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; + return this.point(x, y); }; - EC$1.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$2(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', - }); + EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN$5(y, 16); + if (!y.red) + y = y.toRed(this.red); - // Number of bytes to generate - var ns1 = this.n.sub(new BN$2(1)); + // 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()); - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + return this.point(x, y); + }; - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); - return new Signature$2({ r: r, s: s, recoveryParam: recoveryParam }); - } + 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; }; - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(signature, 'hex'); + 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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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; - // 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; + // 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$1(Point, Base.BasePoint); - // 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; + EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; - if (!this.curve._maxwellTrick) { - p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); + }; - return p.getX().umod(this.n).cmp(r) === 0; - } + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); + }; - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + 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)); + }; - // 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); + 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); }; - EC$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); + 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 - var n = this.n; - var e = new BN$2(msg); - var r = signature.r; - var s = signature.s; + // 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(); - // 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'); + 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); + }; - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); else - r = this.curve.pointFromX(r, isYOdd); + return this._projDbl(); + }; - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); + Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); + // 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); }; - EC$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(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; - } + Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S - if (Qprime.eq(Q)) - return i; + // 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); } - throw new Error('Unable to find valid recovery factor'); + return this.curve.point(nx, ny, nz); }; - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.cachedProperty; + Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; - /** - * @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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; + if (this.curve.extended) + return this._extAdd(p); else - this._pubBytes = parseBytes$2(params.pub); - } + return this._projAdd(p); + }; - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); + Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); }; - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); + Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); }; - KeyPair$2.prototype.secret = function secret() { - return this._secret; + Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); }; - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); + Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); + // 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; + }; - cachedProperty$1(KeyPair$2, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; + Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); + }; - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); + }; - return a; - }); + Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); + }; - cachedProperty$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); + Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; + }; - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); + Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); + 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; - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } }; - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; + // Compatibility with BaseCurve + Point.prototype.toP = Point.prototype.normalize; + Point.prototype.mixedAdd = Point.prototype.add; - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); - }; + (function (exports) { - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); - }; + var curve = exports; - var key = KeyPair$2; + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.parseBytes; + var curves$2 = {}; - /** - * @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$1(eddsa, sig) { - this.eddsa = eddsa; + var hash$2 = {}; - if (typeof sig !== 'object') - sig = parseBytes$1(sig); + var utils$h = {}; - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; + var assert$b = minimalisticAssert; + var inherits = inherits_browser.exports; + + utils$h.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; + } + utils$h.toArray = toArray; - assert$1(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; } + utils$h.toHex = toHex; - cachedProperty(Signature$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.htonl = htonl; - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); + 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; + } + utils$h.toHex32 = toHex32; - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.zero2 = zero2; - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); + 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; + } + utils$h.zero8 = zero8; - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.join32 = join32; - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; + 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; + } + utils$h.split32 = split32; - var signature = Signature$1; + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; - var hash = hash$2; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; - function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; - if (!(this instanceof EDDSA)) - return new EDDSA(curve); + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; - curve = curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; } + utils$h.sum32_5 = sum32_5$2; - var eddsa = EDDSA; + function sum64$1(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; - /** - * @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 }); - }; + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; + } + utils$h.sum64 = sum64$1; - /** - * @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); - }; + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; - EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils$1.intFromLE(hash.digest()).umod(this.curve.n); - }; + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; + function sum64_4_hi$1(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; - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.fromSecret(this, secret); - }; + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; + } + utils$h.sum64_4_hi = sum64_4_hi$1; - EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); - }; + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; - /** - * * 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; - }; + function sum64_5_hi$1(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; - EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils$1.parseBytes(bytes); + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; + } + utils$h.sum64_5_hi = sum64_5_hi$1; - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; - var y = utils$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); - }; + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; - EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); - }; + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; - EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils$1.intFromLE(bytes); - }; + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; - (function (exports) { + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; - var elliptic = exports; + var common$5 = {}; - elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; + var utils$g = utils$h; + var assert$a = minimalisticAssert; - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); + function BlockHash$4() { + 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'; - const createHmac = browser$2; + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; + } + common$5.BlockHash = BlockHash$4; - const ONE1 = Buffer$m.alloc(1, 1); - const ZERO1 = Buffer$m.alloc(1, 0); + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer$m.alloc(32, 0); - let v = Buffer$m.alloc(32, 1); + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + // 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; - // Step E - v = createHmac('sha256', k).update(v).digest(); + msg = utils$g.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); + } - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + return this; + }; - // Step G - v = createHmac('sha256', k).update(v).digest(); + BlockHash$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); + return this._digest(enc); + }; - let T = v; + BlockHash$4.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; - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; - v = createHmac('sha256', k).update(v).digest(); + 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; - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; + for (t = 8; t < this.padLength; t++) + res[i++] = 0; } - return T - } - - var rfc6979 = deterministicGenerateK$1; - - const BN = bn.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; - - const ZERO32 = Buffer$m.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + return res; + }; - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; + var sha = {}; - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + var common$4 = {}; - function isScalar (x) { - return isBuffer(x) && x.length === 32 - } + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); } + common$4.ft_1 = ft_1$1; - function isPoint (p) { - if (!isBuffer(p)) return false - if (p.length < 33) return false - - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); } + common$4.maj32 = maj32$1; - function __isPointCompressed (p) { - return p[0] !== 0x04 + function p32(x, y, z) { + return x ^ y ^ z; } + common$4.p32 = p32; - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } + common$4.s0_256 = s0_256$1; - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } + common$4.s1_256 = s1_256$1; - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); } + common$4.g0_256 = g0_256$1; - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); } + common$4.g1_256 = g1_256$1; - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); } - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + utils$e.inherits(SHA1, BlockHash$3); + var _1 = SHA1; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + SHA1.blockSize = 512; + SHA1.outSize = 160; + SHA1.hmacStrength = 80; + SHA1.padLength = 64; - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null + SHA1.prototype._update = function _update(msg, start) { + var W = this.W; - return getEncoded(uu, compressed) - } + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + for(; i < W.length; i++) + W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + 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]; - const compressed = assumeCompression(__compressed, p); + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } - return getEncoded(pp, compressed) - } + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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; - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + var BlockHash$2 = common$2.BlockHash; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null + 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 + ]; - return getEncoded(qq, compressed) + function SHA256$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null + SHA256$1.prototype._update = function _update(msg, start) { + var W = this.W; - return dt - } + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4$1(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + 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]; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null + assert$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } - return dt - } + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; - function sign$1 (hash, x) { - return __sign(hash, x) - } + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) - } + var utils$c = utils$h; + var SHA256 = _256; - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = SHA224; - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; - if (Q.isInfinity()) return false + SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; - r = Q.x.umod(n); - if (r.isZero() === 0) return false + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; - return true - }; + var BlockHash$1 = common$1.BlockHash; - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + 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 + ]; - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); - } + function SHA512$1() { + if (!(this instanceof SHA512$1)) + return new SHA512$1(); - const buffer = Buffer$m.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer + BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); + var _512 = SHA512$1; - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + SHA512$1.blockSize = 1024; + SHA512$1.outSize = 512; + SHA512$1.hmacStrength = 192; + SHA512$1.padLength = 128; - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + SHA512$1.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); + // 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]; - if (strict && s.cmp(nDiv2) > 0) { - return false + 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); } + }; - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + SHA512$1.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); + var W = this.W; - // Compute s^-1 - const sInv = s.invm(n); + 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]; - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); + assert$8(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); + 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); + 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; - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false + dh = ch; + dl = cl; - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; + ch = bh; + cl = bl; - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); + bh = ah; + bl = al; - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign: sign$1, - signWithEntropy, - verify + 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); }; - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } + SHA512$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.split32(this.h, 'big'); }; - // TODO: deprecate - types$c.Null = types$c.Nil; - - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); + function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; } - var native$1 = types$c; - - var native = native$1; - - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; } - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) + function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; } - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value + 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 captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } + 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 tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' + 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 - return type !== undefined ? type : '' + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); + 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 - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; } - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); + 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 - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; + 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); - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + 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 TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } + 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); - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; } - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + 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); - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; + var utils$a = utils$h; - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); + var SHA512 = _512; - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); - captureStackTrace(e); - return e + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; } + utils$a.inherits(SHA384, SHA512); + var _384 = SHA384; - var errors = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); }; - var NATIVE$1 = native$1; - var ERRORS$1 = errors; + sha.sha1 = _1; + sha.sha224 = _224; + sha.sha256 = _256; + sha.sha384 = _384; + sha.sha512 = _512; - function _Buffer (value) { - return isBuffer(value) - } + var ripemd = {}; - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } + var utils$9 = utils$h; + var common = common$5; - function _LengthN (type, length) { - var name = type.toJSON(); + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; + var BlockHash = common.BlockHash; - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true + function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; + BlockHash.call(this); - return Length + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; } + utils$9.inherits(RIPEMD160, BlockHash); + ripemd.ripemd160 = RIPEMD160; - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); + RIPEMD160.blockSize = 512; + RIPEMD160.outSize = 160; + RIPEMD160.hmacStrength = 192; + RIPEMD160.padLength = 64; - function Range$m (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) + 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; } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - }; - return _range - } + 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; + }; - var INT53_MAX = Math.pow(2, 53) - 1; + RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$9.toHex32(this.h, 'little'); + else + return utils$9.split32(this.h, 'little'); + }; - function Finite (value) { - return typeof value === 'number' && isFinite(value) + 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 Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value + + 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 UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value + + 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 types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$m, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; + 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 + ]; - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); + 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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); } + var hmac = Hmac; - var extra = types$b; + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(key.length <= this.blockSize); - var ERRORS = errors; - var NATIVE = native$1; + // 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); + }; + + (function (exports) { + var hash = exports; - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha; + hash.ripemd = ripemd; + hash.hmac = hmac; - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; + // 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; + }(hash$2)); - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false + (function (exports) { - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; + var curves = exports; - return _arrayOf - }, + var hash = hash$2; + var curve$1 = curve; + var utils = utils$n; - maybe: function maybe (type) { - type = compile(type); + var assert = utils.assert; - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; - return _maybe - }, + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); + } + curves.PresetCurve = PresetCurve; - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + 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; + }, + }); + } - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + 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', + ], + }); - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } + 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', + ], + }); - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } - } + 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', + ], + }); - return true - } + 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', + ], + }); - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; - } + 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', + ], + }); - return _map - }, + 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', + ], + }); - object: function object (uncompiled) { - var type = {}; + 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', - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658', + ], + }); - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + var pre; + try { + pre = require('./precomputed/secp256k1'); + } catch (e) { + pre = undefined; + } - var propertyName; + 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, - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3', + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15', + }, + ], - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre, + ], + }); + }(curves$2)); - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue + var hash$1 = hash$2; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; - throw new TfPropertyTypeError(undefined, propertyName) - } - } + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(options); + this.hash = options.hash; + this.predResist = !!options.predResist; - return true - } - _object.toJSON = function () { return tfJSON(type) }; + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; - return _object - }, + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); + var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + HmacDRBG$1.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); - return _anyOf - }, + 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; + } - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 + }; - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + HmacDRBG$1.prototype._hmac = function hmac() { + return new hash$1.hmac(this.hash, this.K); + }; - return _allOf - }, + HmacDRBG$1.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; - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type }; + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); + }; - return _quacksLike - }, + HmacDRBG$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; - return _tuple - }, + HmacDRBG$1.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected }; + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } - return _value + // Optional additional data + if (add) { + add = utils$7.toArray(add, addEnc || 'hex'); + this._update(add); } - }; - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils$7.encode(res, enc); + }; - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } + function KeyPair$4(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; - return TYPES.value(type) + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); } + var key$1 = KeyPair$4; - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; + + KeyPair$4.prototype.validate = function validate() { + var pub = this.getPublic(); - throw new TfTypeError(surrogate || type, value) - } + 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' }; - // JIT - return typeforce$b(compile(type), value, strict) - } + return { result: true, reason: null }; + }; - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } + KeyPair$4.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } + if (!enc) + return this.pub; - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + return this.pub.encode(enc, compact); + }; - var typeforce_1 = typeforce$b; + KeyPair$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; - var bs58check$4 = bs58check$5; + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(key, enc || 16); - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + // 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); + }; - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false + KeyPair$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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); + }; - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') + // ECDH + KeyPair$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$m(compressed ? 34 : 33); + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; - result.writeUInt8(version, 0); - privateKey.copy(result, 1); + var BN$3 = bn.exports; - if (compressed) { - result[33] = 0x01; - } + var utils$5 = utils$n; + var assert$4 = utils$5.assert; - return result + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; } + var signature$1 = Signature$3; - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) + function Position() { + this.place = 0; } - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } + // Indefinite length or overflow + if (octetLen === 0 || octetLen > 4) { + return false; + } - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw - }; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + val >>>= 0; + } - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$3 = crypto$5; - const bs58check$3 = bs58check$5; - const ecc$6 = js; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + // Leading zeroes + if (val <= 0x7f) { + return false; + } + + p.place = off; + return val; } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$3.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer$m.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); - } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer$m.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$3.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; - } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); - } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); - } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); - } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } + + 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); } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + + Signature$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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; } - return hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); - } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); - } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); - } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); - } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); + } + if (s[0] === 0) { + if (s[1] & 0x80) { + s = s.slice(1); + } else { + // Leading zeroes + return false; + } + } + + this.r = new BN$3(r); + this.s = new BN$3(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); } - bip32$1.fromSeed = fromSeed; - Object.defineProperty(src, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; + Signature$3.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); - var address$1 = {}; + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); - var networks$3 = {}; + r = rmPadding(r); + s = rmPadding(s); - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, + 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$5.encode(res, enc); }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); }; - var payments$4 = {}; + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; - var embed = {}; + EC$1.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; - var script$1 = {}; + // 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 script_number = {}; + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN$2(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); - } + priv.iaddn(1); + return this.keyFromPrivate(priv); } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; + }; + + EC$1.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$1.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer$m.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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; } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; + + // 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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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; } - return buffer; + throw new Error('Unable to find valid recovery factor'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); } - script_number.encode = encode$g; - var script_signature = {}; + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; - var types$a = {}; + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; + KeyPair$2.prototype.secret = function secret() { + return this._secret; }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); - var Buffer$2 = safeBuffer.exports.Buffer; + cachedProperty$1(KeyPair$2, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false + return a; + }); + + cachedProperty$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true - } + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + var key = KeyPair$2; - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.parseBytes; - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + /** + * @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$1(eddsa, sig) { + this.eddsa = eddsa; - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + if (typeof sig !== 'object') + sig = parseBytes$1(sig); - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + cachedProperty(Signature$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); - var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); - return signature - } + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); }; - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$m.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$m.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer$m.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$m.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; - - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); }; - var OPS$9 = require$$7; + var signature = Signature$1; - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 + var hash = hash$2; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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; } - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); + var eddsa = EDDSA; - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); + /** + * @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 }); + }; - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); + /** + * @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); + }; - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); + EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils$1.intFromLE(hash.digest()).umod(this.curve.n); + }; - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); - } + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; - return size - } + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.fromSecret(this, secret); + }; - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; + EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); + }; - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; + /** + * * 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; + }; - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; + EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils$1.parseBytes(bytes); - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + var y = utils$1.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); + }; - number = buffer.readUInt32LE(offset + 1); - size = 5; - } + EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); + }; - return { - opcode: opcode, - number: number, - size: size - } - } + EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils$1.intFromLE(bytes); + }; - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; }; - var OPS$8 = require$$7; + (function (exports) { - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } + var elliptic = exports; - var map_1 = map; + elliptic.version = require$$0$1.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = js; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer$m.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; - } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; - } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode - } else { - chunks.push(opcode); - i += 1; - } - } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); - } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer$m.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); - var lazy$7 = {}; + const createHmac = browser$2; - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; - }; - } - lazy$7.value = value; + const ONE1 = Buffer$l.alloc(1, 1); + const ZERO1 = Buffer$l.alloc(1, 0); - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } - } - return Object.assign(o, a); - } - embed.p2data = p2data; + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$l.alloc(32, 0); + let v = Buffer$l.alloc(32, 1); - var p2ms$3 = {}; + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = js; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); - } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); - } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); - } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); - } + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; } - return Object.assign(o, a); + + return T } - p2ms$3.p2ms = p2ms$2; - var p2pk$3 = {}; + var rfc6979 = deterministicGenerateK$1; - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = js; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); - } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); - } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); - } - } - return Object.assign(o, a); + const BN = bn$1.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer$l.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 } - p2pk$3.p2pk = p2pk$2; - var p2pkh$4 = {}; + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G + } - var crypto$2 = {}; + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false - Object.defineProperty(crypto$2, '__esModule', { value: true }); - const createHash = browser$3; - function ripemd160$1(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true } + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false } - crypto$2.ripemd160 = ripemd160$1; - function sha1(buffer) { - return createHash('sha1') - .update(buffer) - .digest(); + + function __isPointCompressed (p) { + return p[0] !== 0x04 } - crypto$2.sha1 = sha1; - function sha256$1(buffer) { - return createHash('sha256') - .update(buffer) - .digest(); + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) } - crypto$2.sha256 = sha256$1; - function hash160$1(buffer) { - return ripemd160$1(sha256$1(buffer)); + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G } - crypto$2.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$1(sha256$1(buffer)); + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 } - crypto$2.hash256 = hash256$1; - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); - const bcrypto$6 = crypto$2; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = js; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - } - if (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value } - p2pkh$4.p2pkh = p2pkh$3; - var p2sh$1 = {}; + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$2; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } - } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); - } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - } - } - return Object.assign(o, a); + + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) } - p2sh$1.p2sh = p2sh; - var p2wpkh$2 = {}; + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); + const compressed = assumeCompression(__compressed, p); - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; + return getEncoded(pp, compressed) } - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) } - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - chk = polymodStep(chk) ^ (c >> 5); - } - chk = polymodStep(chk); + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk + return getEncoded(qq, compressed) } - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - prefix = prefix.toLowerCase(); + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) + return dt + } - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; + return dt + } - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } + function sign$1 (hash, x) { + return __sign(hash, x) + } - return result + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) } - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' + if (Q.isInfinity()) return false - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk + r = Q.x.umod(n); + if (r.isZero() === 0) return false - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); } - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } + const buffer = Buffer$l.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer } - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) } - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign: sign$1, + signWithEntropy, + verify + }; - throw new Error(res) + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); } - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; + var native$1 = types$c; - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; + var native = native$1; - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); } + } - return result + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' } - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') } - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); - throw new Error(res) + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; } - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) } - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } - throw new Error(res) + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; } - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords - }; + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); - const bcrypto$4 = crypto$2; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = js; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$m.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); } - return Object.assign(o, a); + + captureStackTrace(e); + return e } - p2wpkh$2.p2wpkh = p2wpkh$1; - var p2wsh$1 = {}; + var errors = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors; - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$2; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = js; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$m.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); + function _Buffer (value) { + return isBuffer(value) } - function chunkHasUncompressedPubkey(chunk) { - if ( - isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; - } else { - return false; + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') } + Length.toJSON = function () { return name }; + + return Length } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } } + + return true } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); - } - } - return Object.assign(o, a); - } - p2wsh$1.p2wsh = p2wsh; + _object.toJSON = function () { return tfJSON(type) }; - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; + return _object + }, - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer$m.from(data), - }; - } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); - } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); - } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); - } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; - } + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; - - var ecpair = {}; + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - var browser$1 = {exports: {}}; + return _anyOf + }, - // limit of Crypto.getRandomValues() - // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues - var MAX_BYTES = 65536; + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); - // Node supports requesting up to this number of bytes - // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 - var MAX_UINT32 = 4294967295; + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') - } + return _allOf + }, - var Buffer$1 = safeBuffer.exports.Buffer; - var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; - if (crypto$1 && crypto$1.getRandomValues) { - browser$1.exports = randomBytes$1; - } else { - browser$1.exports = oldBrowser; - } + return _quacksLike + }, - function randomBytes$1 (size, cb) { - // phantomjs needs to throw - if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); - var bytes = Buffer$1.allocUnsafe(size); + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false - if (size > 0) { // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues - // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - for (var generated = 0; generated < size; generated += MAX_BYTES) { - // buffer.slice automatically checks if the end is past the end of - // the buffer so we don't have to here - crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); - } - } else { - crypto$1.getRandomValues(bytes); + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) } - } - - if (typeof cb === 'function') { - return nextTick(function () { - cb(null, bytes); - }) - } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; - return bytes - } + return _tuple + }, - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = js; - const randomBytes = browser$1.exports; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); - } - return sig; + value: function value (expected) { + function _value (actual) { + return actual === expected } + _value.toJSON = function () { return expected }; + + return _value } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; + }; - var block = {}; + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; - var bufferutils = {}; + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) - var Buffer = safeBuffer.exports.Buffer; + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$5 = 9007199254740991; + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') + return TYPES.value(type) } - function encode$b (number, buffer, offset) { - checkUInt53$1(number); - - if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; + throw new TfTypeError(surrogate || type, value) + } - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; + // JIT + return typeforce$b(compile(type), value, strict) + } - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } - return buffer + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; } - function decode$a (buffer, offset) { - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; - var first = buffer.readUInt8(offset); + var typeforce_1 = typeforce$b; - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first + var bs58check$4 = bs58check$5; - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') - return number + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true } } - function encodingLength$1 (number) { - checkUInt53$1(number); - - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$l(compressed ? 34 : 33); - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + result.writeUInt8(version, 0); + privateKey.copy(result, 1); - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer$m.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; - } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); + if (compressed) { + result[33] = 0x01; } + + return result } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); - } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); - } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; - } + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) } - bufferutils.BufferReader = BufferReader$1; - var transaction = {}; + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$2; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; - } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); - } - const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw }; - function isOutput(out) { - return out.value !== undefined; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$3 = crypto$5; + const bs58check$3 = bs58check$5; + const ecc$6 = js; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); + get depth() { + return this.__DEPTH; } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); + get index() { + return this.__INDEX; } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); - } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; + get privateKey() { + return this.__D; } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; - } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); + get identifier() { + return crypto$3.hash160(this.publicKey); } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; + get fingerprint() { + return this.identifier.slice(0, 4); } - // serialize and hash - const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer$m.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); + get compressed() { + return true; } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer$m.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); } - tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$l.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$l.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$3.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$l.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); - } else { - bufferWriter.writeSlice(txOut.valueBuffer); - } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; - } + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) + } + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } + return hd; } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; - var length = values.length; - var results = values.concat(); + var address$1 = {}; - while (length > 1) { - var j = 0; + var networks$3 = {}; - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$m.concat([left, right]); + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; - results[j] = digestFn(data); - } + var payments$4 = {}; - length = j; - } + var embed = {}; - return results[0] - }; + var script$1 = {}; - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$2; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer$m.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer$m.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$m && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer$m && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; - } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$l.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; } + return buffer; } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { - return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 - ); + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; } - function anyTxHasWitness(transactions) { + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' ); } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$2 = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } - var psbt$1 = {}; + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - var psbt = {}; + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - var combiner = {}; + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - var parser = {}; + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - var fromBuffer = {}; + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - var converter = {}; + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + } + } - var typeFields = {}; + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); + var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); - var globalXpub$1 = {}; + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$4 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$4(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; + return signature } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$m.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$l.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); + return x; } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$l.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$l.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$l.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); + } + + return size } - globalXpub$1.canAddToArray = canAddToArray$1; - var unsignedTx$1 = {}; + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), - }; - } - unsignedTx$1.encode = encode$9; + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; - var finalScriptSig$1 = {}; + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, - }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; - var finalScriptWitness$1 = {}; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); + number = buffer.readUInt32LE(offset + 1); + size = 5; } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { - key, - value: data, - }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); + opcode: opcode, + number: number, + size: size + } } - finalScriptWitness$1.canAdd = canAdd$4; - var nonWitnessUtxo$1 = {}; + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, - }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; } - nonWitnessUtxo$1.canAdd = canAdd$3; - var partialSig$1 = {}; + var map_1 = map; - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, - }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer$m.concat([head, pSig.pubkey]), - value: pSig.signature, - }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = js; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) ); } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; - - var porCommitment$1 = {}; - - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); - return { - key, - value: Buffer$m.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; - } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); } - porCommitment$1.canAdd = canAdd$2; - - var sighashType$1 = {}; - - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.readUInt32LE(0); + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$m.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; + function chunksIsBuffer(buf) { + return isBuffer(buf); } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; + function chunksIsArray(buf) { + return types.Array(buf); } - sighashType$1.canAdd = canAdd$1; - - var witnessUtxo$1 = {}; - - var tools = {}; - - var varint$1 = {}; - - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$4 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) - throw new RangeError('value out of range'); + function singleChunkIsBuffer(buf) { + return isBuffer(buf); } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$l.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); return buffer; } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } } + return chunks; } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; - } - varint$1.encodingLength = encodingLength; - - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); } - return buffer; - } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$m.from([0])); - return Buffer$m.concat(buffers); + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$m.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$l.from(chunkStr, 'hex'); + }), ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; } - tools.writeUInt64LE = writeUInt64LE; + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); - } - return { - script, - value, - }; + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; }; } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); } - witnessUtxo$1.canAdd = canAdd; + embed.p2data = p2data; - var bip32Derivation$1 = {}; + var p2ms$3 = {}; - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$3 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = js; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); } - return data; - } - function encode(data) { - const head = Buffer$m.from([TYPE_BYTE]); - const key = Buffer$m.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + + var p2pk$3 = {}; + + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = js; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } } - return { - decode, - encode, - check, - expected, - canAddToArray, - }; + return Object.assign(o, a); } - bip32Derivation$1.makeConverter = makeConverter$2; + p2pk$3.p2pk = p2pk$2; - var checkPubkey$1 = {}; + var p2pkh$4 = {}; - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); + var crypto$2 = {}; + + Object.defineProperty(crypto$2, '__esModule', { value: true }); + const createHash = browser$3; + function ripemd160$1(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } + } + crypto$2.ripemd160 = ripemd160$1; + function sha1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$2.sha1 = sha1; + function sha256$1(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$2.sha256 = sha256$1; + function hash160$1(buffer) { + return ripemd160$1(sha256$1(buffer)); + } + crypto$2.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$1(sha256$1(buffer)); + } + crypto$2.hash256 = hash256$1; + + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$2; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = js; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - return pubkey; - } - } - checkPubkey$1.makeChecker = makeChecker; - - var redeemScript$1 = {}; - - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - redeemScript$1.makeConverter = makeConverter$1; - - var witnessScript$1 = {}; - - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); - } - return { - decode, - encode, - check, - expected, - canAdd, - }; + return Object.assign(o, a); } - witnessScript$1.makeConverter = makeConverter; + p2pkh$4.p2pkh = p2pkh$3; - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), - }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), - }; - converter.outputs = outputs; + var p2sh$1 = {}; - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$2; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); return { - key, - value, + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); - } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; - } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); - } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); - } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; } - inputKeyVals.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); - } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - outputKeyVals.push(output); - } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); - } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$m.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); - } - } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); - } - } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); } - inputs.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); } - outputs.push(output); } - return { globalMap, inputs, outputs }; + return Object.assign(o, a); } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + p2sh$1.p2sh = p2sh; - var toBuffer = {}; + var p2wpkh$2 = {}; - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer$m.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$m.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$m.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); - }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along - return { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), - }; + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk } - toBuffer.psbtToKeyVals = psbtToKeyVals; - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + + return result } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' + + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } + + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) + } + + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result + } + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } + + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$2; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = js; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$l.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$l.from(data), + }; }); - } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); - }; - } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; - } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); }); - return set; + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); } + p2wpkh$2.p2wpkh = p2wpkh$1; - var utils = {}; + var p2wsh$1 = {}; - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$2; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = js; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$l.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); - } + function chunkHasUncompressedPubkey(chunk) { if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + return true; + } else { + return false; } } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$l.from(data), + }; }); - return count; - } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$l.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } } + return Object.assign(o, a); } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, - ); + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; - } - } - } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$l.from(data), }; } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$l.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } } - txBuf.writeUInt32LE(version, 0); - return txBuf; + throw new Error(address + ' has no matching Script'); } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); - } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; + address$1.toOutputScript = toOutputScript; + + var ecpair = {}; + + var browser$1 = {exports: {}}; + + // limit of Crypto.getRandomValues() + // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + var MAX_BYTES = 65536; + + // Node supports requesting up to this number of bytes + // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 + var MAX_UINT32 = 4294967295; + + function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, - }; - } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); - } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); - return this; + var Buffer$1 = safeBuffer.exports.Buffer; + var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + + if (crypto$1 && crypto$1.getRandomValues) { + browser$1.exports = randomBytes$1; + } else { + browser$1.exports = oldBrowser; + } + + function randomBytes$1 (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer$1.allocUnsafe(size); + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); + } + } else { + crypto$1.getRandomValues(bytes); + } } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); - return this; + + if (typeof cb === 'function') { + return nextTick(function () { + cb(null, bytes); + }) } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); - return this; + + return bytes + } + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = js; + const randomBytes = browser$1.exports; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); - return this; + get privateKey() { + return this.__D; } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - return this; + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - return this; + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$l.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); - return this; } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } - return this; + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number } } - psbt.Psbt = Psbt$1; - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$2; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, - }; - /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. - */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; } - static fromBase64(data, opts = {}) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, opts); + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$l.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); } - static fromHex(data, opts = {}) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, opts); + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); } - get inputCount() { - return this.data.inputs.length; + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); } - get version() { - return this.__CACHE.__TX.version; + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); } - set version(version) { - this.setVersion(version); + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; } - get locktime() { - return this.__CACHE.__TX.locktime; + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); } - set locktime(locktime) { - this.setLocktime(locktime); + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; + readVarSlice() { + return this.readSlice(this.readVarInt()); } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); - } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$2; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$l.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$l.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; } - addOutput(outputData) { + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); + hasWitnesses = true; + } else { + bufferReader.offset -= 2; } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); return tx; } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); - return this; + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); - return this; } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); - } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 ); } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); - } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); - } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$2(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 ); - return results.reduce((final, res) => res === true && final, true); } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); - } - return results.every(res => res === true); + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$2(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); + virtualSize() { + return Math.ceil(this.weight() / 4); } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; }); + return newTx; } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; } - return this; + // serialize and hash + const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$l.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); }); - }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$l.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - }); - }); + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); } toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); + return this.toBuffer(undefined, undefined).toString('hex'); } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); } - return this; - } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$l.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$2; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; + static fromHex(hex) { + return Block.fromBuffer(Buffer$l.from(hex, 'hex')); } - } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$l.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$l && result.length === 32)) return null; + return result; } - addOutput(output) { + hasWitnessCommit() { if ( - output.script === undefined || - output.value === undefined || - !isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); + this.witnessCommit instanceof Buffer$l && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; } - toBuffer() { - return this.tx.toBuffer(); + hasWitness() { + return anyTxHasWitness(this.transactions); } - } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, - ); + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; } - } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } - }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } - }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) ); } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); - } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 ); } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } - } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, - ); - } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', ); } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$l.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); return { - script: meaningfulScript, - sighashType, - hash, + key, + value, }; } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - } - return payment; + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } - } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; - } - return res; } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); - } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), ); } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; + return keyVal.value; } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); - } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; - } - function readVarSlice() { - return readSlice(readVarInt()); - } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; - } - return readVector(); + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; - } - return text; + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer$m.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); - } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); - } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); - } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); } - writeVector(witness); - return buffer; + return keyVal.value; } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, - }); + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; - } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); - } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); - } - return c[inputIndex]; + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); } + return keyVal.value; } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } if ( - !isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$l.concat([head, pSig.pubkey]), + value: pSig.signature, + }; } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', + key, + value: Buffer$l.from(data, 'utf8'), }; } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); } + return keyVal.value.readUInt32LE(0); } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$l.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; } - function range$2(n) { - return [...Array(n).keys()]; + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; } + sighashType$1.canAdd = canAdd$1; - var transaction_builder = {}; - - var classify$1 = {}; + var witnessUtxo$1 = {}; - var multisig$1 = {}; + var tools = {}; - var input$b = {}; + var varint$1 = {}; - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + return buffer; } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - - var output$e = {}; - - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; - - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; - - var nulldata = {}; - - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - - var pubkey = {}; - - var input$9 = {}; + varint$1.encodingLength = encodingLength; - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; - - var output$b = {}; - - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$l.from([0])); + return Buffer$l.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$l.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; - - var pubkeyhash = {}; - - var input$7 = {}; + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; - var output$9 = {}; + var bip32Derivation$1 = {}; - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG - ); + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$l.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; + bip32Derivation$1.makeConverter = makeConverter$2; - var scripthash = {}; + var checkPubkey$1 = {}; - var input$5 = {}; + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } + } + checkPubkey$1.makeChecker = makeChecker; - var output$7 = {}; + var redeemScript$1 = {}; - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 - ); + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$l.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; - }; + redeemScript$1.makeConverter = makeConverter$1; - var output$6 = {}; + var witnessScript$1 = {}; - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$l.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; + witnessScript$1.makeConverter = makeConverter; + + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), }; + converter.outputs = outputs; - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$l.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); } - // match types - if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; - }; + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - var output$5 = {}; + var toBuffer = {}; - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$l.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$l.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$l.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; - - var witnesscommitment = {}; - - var output$3 = {}; + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer$m.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$m.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; } - output$3.decode = decode; - - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; - - var witnesspubkeyhash = {}; - var input$3 = {}; + var utils = {}; - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; - - var witnessscripthash = {}; - - var input$1 = {}; - - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; - - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); } - classify$1.witness = classifyWitness; - - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$2; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); - } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$l.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; + static fromHex(data, txFromBuffer) { + const buffer = Buffer$l.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); + toBuffer() { + return parser_1.psbtToBuffer(this); } - build() { - return this.__build(false); + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; } - buildIncomplete() { - return this.__build(true); + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); - } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; - } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; - } - prevOutType = expanded.type; - } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); - } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); - } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; - } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); - }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); - } - } - return tx; + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); - }); + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], }); - } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); - }) + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; - } - return false; - }); + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); - return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, - }; - } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$2; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); - } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; + static fromBase64(data, opts = {}) { + const buffer = Buffer$l.from(data, 'base64'); + return this.fromBuffer(buffer, opts); } - return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; - } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); - } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); + static fromHex(data, opts = {}) { + const buffer = Buffer$l.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, }; - } - } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); + } + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + return results.every(res => res === true); } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, - ); - } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); } + return this; } - } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); - } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); - } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, - ); - } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), ); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), ); } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; - } - } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', - ); - } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, ); - // updates inline - Object.assign(input, prepared); } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + return this; } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); - } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; } - - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; - const address = address$1; - src$1.address = address; - const crypto = crypto$2; - var crypto_1 = src$1.crypto = crypto; - const ECPair = ecpair; - src$1.ECPair = ECPair; - const networks = networks$3; - src$1.networks = networks; - const payments = payments$4; - src$1.payments = payments; - const script = script$1; - src$1.script = script; - var block_1 = block; - src$1.Block = block_1.Block; - var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$1.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - - var re$b = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION$1 = '2.0.0'; - - const MAX_LENGTH$5 = 256; - const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - - var constants$1 = { - SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, - MAX_LENGTH: MAX_LENGTH$5, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, - MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 - }; - - const debug$7 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1$1 = debug$7; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; - const debug = debug_1$1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$b, re$b.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts$1 = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$9 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts$1.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1$1 = parseOptions$9; - - const numeric$1 = /^[0-9]+$/; - const compareIdentifiers$3 = (a, b) => { - const anum = numeric$1.test(a); - const bnum = numeric$1.test(b); - - if (anum && bnum) { - a = +a; - b = +b; + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - - var identifiers$1 = { - compareIdentifiers: compareIdentifiers$3, - rcompareIdentifiers: rcompareIdentifiers$1 - }; - - const debug$6 = debug_1$1; - const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; - const { re: re$a, t: t$9 } = re$b.exports; - - const parseOptions$8 = parseOptions_1$1; - const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; - class SemVer$t { - constructor (version, options) { - options = parseOptions$8(options); - - if (version instanceof SemVer$t) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$4) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$4} characters` - ) - } - - debug$6('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { - throw new TypeError('Invalid patch version') + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER$2) { - return num - } - } - return id - }); + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); + this.tx.addOutput(output.script, output.value); } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; } - return this.version + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); } - - toString () { - return this.version + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); } - - compare (other) { - debug$6('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$t)) { - if (typeof other === 'string' && other === this.version) { - return 0 + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; } - other = new SemVer$t(other, this.options); + if (whitelist.indexOf(action) === -1) { + throws = true; + } + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); } - - if (other.version === this.version) { - return 0 + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); } - - return this.compareMain(other) || this.comparePre(other) + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); } - - compareMain (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); - } - - return ( - compareIdentifiers$2(this.major, other.major) || - compareIdentifiers$2(this.minor, other.minor) || - compareIdentifiers$2(this.patch, other.patch) - ) + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); } - - comparePre (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); } - - compareBuild (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; } - this.format(); - this.raw = this.version; - return this } + return { + finalScriptSig, + finalScriptWitness, + }; } - - var semver$3 = SemVer$t; - - const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; - const { re: re$9, t: t$8 } = re$b.exports; - const SemVer$s = semver$3; - - const parseOptions$7 = parseOptions_1$1; - const parse$b = (version, options) => { - options = parseOptions$7(options); - - if (version instanceof SemVer$s) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH$3) { - return null - } - - const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; - if (!r.test(version)) { - return null + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); } - - try { - return new SemVer$s(version, options) - } catch (er) { - return null + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); } - }; - - var parse_1$1 = parse$b; - - const parse$a = parse_1$1; - const valid$3 = (version, options) => { - const v = parse$a(version, options); - return v ? v.version : null - }; - var valid_1$1 = valid$3; - - const parse$9 = parse_1$1; - const clean$1 = (version, options) => { - const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1$1 = clean$1; - - const SemVer$r = semver$3; - - const inc$1 = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); } - - try { - return new SemVer$r(version, options).inc(release, identifier).version - } catch (er) { - return null + return { + script: meaningfulScript, + sighashType, + hash, + }; + } + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; } - }; - var inc_1$1 = inc$1; - - const SemVer$q = semver$3; - const compare$l = (a, b, loose) => - new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - - var compare_1$1 = compare$l; - - const compare$k = compare_1$1; - const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; - var eq_1$1 = eq$5; - - const parse$8 = parse_1$1; - const eq$4 = eq_1$1; - - const diff$1 = (version1, version2) => { - if (eq$4(version1, version2)) { - return null + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; } else { - const v1 = parse$8(version1); - const v2 = parse$8(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; } - return defaultResult // may be undefined - } - }; - var diff_1$1 = diff$1; - - const SemVer$p = semver$3; - const major$1 = (a, loose) => new SemVer$p(a, loose).major; - var major_1$1 = major$1; - - const SemVer$o = semver$3; - const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; - var minor_1$1 = minor$1; - - const SemVer$n = semver$3; - const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; - var patch_1$1 = patch$1; - - const parse$7 = parse_1$1; - const prerelease$1 = (version, options) => { - const parsed = parse$7(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1$1 = prerelease$1; - - const compare$j = compare_1$1; - const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); - var rcompare_1$1 = rcompare$1; - - const compare$i = compare_1$1; - const compareLoose$1 = (a, b) => compare$i(a, b, true); - var compareLoose_1$1 = compareLoose$1; - - const SemVer$m = semver$3; - const compareBuild$5 = (a, b, loose) => { - const versionA = new SemVer$m(a, loose); - const versionB = new SemVer$m(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1$1 = compareBuild$5; - - const compareBuild$4 = compareBuild_1$1; - const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); - var sort_1$1 = sort$1; - - const compareBuild$3 = compareBuild_1$1; - const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); - var rsort_1$1 = rsort$1; - - const compare$h = compare_1$1; - const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; - var gt_1$1 = gt$7; - - const compare$g = compare_1$1; - const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; - var lt_1$1 = lt$5; - - const compare$f = compare_1$1; - const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; - var neq_1$1 = neq$3; - - const compare$e = compare_1$1; - const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; - var gte_1$1 = gte$5; - - const compare$d = compare_1$1; - const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; - var lte_1$1 = lte$5; - - const eq$3 = eq_1$1; - const neq$2 = neq_1$1; - const gt$6 = gt_1$1; - const gte$4 = gte_1$1; - const lt$4 = lt_1$1; - const lte$4 = lte_1$1; - - const cmp$3 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq$3(a, b, loose) - - case '!=': - return neq$2(a, b, loose) - - case '>': - return gt$6(a, b, loose) - - case '>=': - return gte$4(a, b, loose) - - case '<': - return lt$4(a, b, loose) - - case '<=': - return lte$4(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1$1 = cmp$3; - - const SemVer$l = semver$3; - const parse$6 = parse_1$1; - const {re: re$8, t: t$7} = re$b.exports; - - const coerce$1 = (version, options) => { - if (version instanceof SemVer$l) { - return version } - - if (typeof version === 'number') { - version = String(version); + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; } - - if (typeof version !== 'string') { - return null + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$8[t$7.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$8[t$7.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; } - re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - // leave it in a clean state - re$8[t$7.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null - - return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1$1 = coerce$1; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); } - } - - return self + return node; + }); + return signers; } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; } - - if (prev) { - prev.next = next; + function readVarSlice() { + return readSlice(readVarInt()); } - - if (node === this.head) { - this.head = next; + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; } - if (node === this.tail) { - this.tail = prev; + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$l.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); } - - if (node.list) { - node.list.removeNode(node); + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); } - - this.head = node; - if (!this.tail) { - this.tail = node; + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); } - - if (node.list) { - node.list.removeNode(node); + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); } - - this.tail = node; - if (!this.head) { - this.head = node; + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); } - this.length++; - }; + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; + var transaction_builder = {}; - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; + var classify$1 = {}; - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } + var multisig$1 = {}; - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); } - this.length--; - return res + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; }; - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } + var output$e = {}; - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; }; - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; + var nulldata = {}; - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; }; + const output$c = { check: check$b }; + nulldata.output = output$c; - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; + var pubkey = {}; - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; + var input$9 = {}; - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; }; - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } + var output$b = {}; - return acc + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; }; - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; - return acc - }; + var pubkeyhash = {}; - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; + var input$7 = {}; - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; }; - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; + var output$9 = {}; - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; }; - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } + var scripthash = {}; - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } + var input$5 = {}; - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; + var output$7 = {}; - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; }; - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); - - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } - - self.length++; + var output$6 = {}; - return inserted + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); } - self.length++; + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; - this.list = list; - this.value = value; + var witnesscommitment = {}; - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } + var output$3 = {}; - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$l.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$l.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; - const naiveLength = () => 1; + var witnesspubkeyhash = {}; - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; + var input$3 = {}; - if (!options) - options = {}; + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } + var witnessscripthash = {}; - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') + var input$1 = {}; - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; - this[MAX_AGE] = mA; - trim(this); + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$2; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); } - get maxAge () { - return this[MAX_AGE] + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, }); - } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; } + this.__USE_LOW_R = setting; + return setting; } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) + this.__TX.locktime = locktime; } - - dumpLru () { - return this[LRU_LIST] + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); } - - get (key) { - return get$1(this, key, true) + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); } - - peek (key) { - return get$1(this, key, false) + build() { + return this.__build(false); } - - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null - - del(this, node); - return node.value + buildIncomplete() { + return this.__build(true); } - - del (key) { - del(this, this[CACHE].get(key)); + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; } + prevOutType = expanded.type; } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); - } - } - - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); } } - return hit.value + return tx; } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; - - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; } } - - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; - - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$l { - constructor (range, options) { - options = parseOptions$6(options); - - if (range instanceof Range$l) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$l(range.raw, options) - } + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; } - - if (range instanceof Comparator$7) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet$1(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny$1(c[0])) { - this.set = [c]; - break - } - } - } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range } - - toString () { - return this.range + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache$1.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); - debug$5('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); - debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator$1(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0$1(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$7(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet$1(comp)) - return [comp] - rangeMap.set(comp.value, comp); + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache$1.set(memoKey, result); - return result + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; } - - intersects (range, options) { - if (!(range instanceof Range$l)) { - throw new TypeError('a Range is required') + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable$1(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable$1(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; } - - if (typeof version === 'string') { - try { - version = new SemVer$k(version, this.options); - } catch (er) { - return false - } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; } - - for (let i = 0; i < this.set.length; i++) { - if (testSet$1(this.set[i], version, this.options)) { - return true - } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; } - return false } + return { type }; } - var range$1 = Range$l; - - const LRU$1 = lruCache; - const cache$1 = new LRU$1({ max: 1000 }); - - const parseOptions$6 = parseOptions_1$1; - const Comparator$7 = comparator$1; - const debug$5 = debug_1$1; - const SemVer$k = semver$3; - const { - re: re$7, - t: t$6, - comparatorTrimReplace: comparatorTrimReplace$1, - tildeTrimReplace: tildeTrimReplace$1, - caretTrimReplace: caretTrimReplace$1 - } = re$b.exports; - - const isNullSet$1 = c => c.value === '<0.0.0-0'; - const isAny$1 = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable$1 = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator$1 = (comp, options) => { - debug$5('comp', comp, options); - comp = replaceCarets$1(comp, options); - debug$5('caret', comp); - comp = replaceTildes$1(comp, options); - debug$5('tildes', comp); - comp = replaceXRanges$1(comp, options); - debug$5('xrange', comp); - comp = replaceStars$1(comp, options); - debug$5('stars', comp); - return comp - }; - - const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde$1(comp, options) - }).join(' '); - - const replaceTilde$1 = (comp, options) => { - const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$5('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; - } - - debug$5('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret$1(comp, options) - }).join(' '); - - const replaceCaret$1 = (comp, options) => { - debug$5('caret', comp, options); - const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('caret', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$5('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$5('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$5('caret return', ret); - return ret - }) - }; - - const replaceXRanges$1 = (comp, options) => { - debug$5('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange$1(comp, options) - }).join(' ') - }; - - const replaceXRange$1 = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$5('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX$1(M); - const xm = xM || isX$1(m); - const xp = xm || isX$1(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); } - - debug$5('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars$1 = (comp, options) => { - debug$5('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$7[t$6.STAR], '') - }; - - const replaceGTE0$1 = (comp, options) => { - debug$5('replaceGTE0', comp, options); - return comp.trim() - .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace$1 = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX$1(fM)) { - from = ''; - } else if (isX$1(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX$1(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX$1(tM)) { - to = ''; - } else if (isX$1(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX$1(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet$1 = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$5(set[i].semver); - if (set[i].semver === Comparator$7.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$5 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$6 { - static get ANY () { - return ANY$5 + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - constructor (comp, options) { - options = parseOptions$5(options); - - if (comp instanceof Comparator$6) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); } - - debug$4('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$5) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - debug$4('comp', this); + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - parse (comp) { - const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$5; - } else { - this.semver = new SemVer$j(m[2], this.options.loose); + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - toString () { - return this.value - } - - test (version) { - debug$4('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$5 || version === ANY$5) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer$j(version, this.options); - } catch (er) { - return false - } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - return cmp$2(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$6)) { - throw new TypeError('a Comparator is required') + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$k(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); } - return new Range$k(this.value, options).test(comp.semver) + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); + } + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp$2(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp$2(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) } } - - var comparator$1 = Comparator$6; - - const parseOptions$5 = parseOptions_1$1; - const {re: re$6, t: t$5} = re$b.exports; - const cmp$2 = cmp_1$1; - const debug$4 = debug_1$1; - const SemVer$j = semver$3; - const Range$k = range$1; - - const Range$j = range$1; - const satisfies$7 = (version, range, options) => { - try { - range = new Range$j(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1$1 = satisfies$7; - - const Range$i = range$1; - - // Mostly just for testing and legacy API reasons - const toComparators$1 = (range, options) => - new Range$i(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1$1 = toComparators$1; - - const SemVer$i = semver$3; - const Range$h = range$1; - - const maxSatisfying$1 = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$h(range, options); - } catch (er) { - return null + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$i(max, options); + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); } - } - }); - return max - }; - var maxSatisfying_1$1 = maxSatisfying$1; - - const SemVer$h = semver$3; - const Range$g = range$1; - const minSatisfying$1 = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$g(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$h(min, options); + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); } - } - }); - return min - }; - var minSatisfying_1$1 = minSatisfying$1; - - const SemVer$g = semver$3; - const Range$f = range$1; - const gt$5 = gt_1$1; - - const minVersion$1 = (range, loose) => { - range = new Range$f(range, loose); - - let minver = new SemVer$g('0.0.0'); - if (range.test(minver)) { - return minver + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; } - - minver = new SemVer$g('0.0.0-0'); - if (range.test(minver)) { - return minver + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); + } + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$g(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$5(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$5(minver, setMin))) - minver = setMin; + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); } - - if (minver && range.test(minver)) { - return minver + if (keyPair === undefined) { + throw new Error('sign requires keypair'); } - - return null - }; - var minVersion_1$1 = minVersion$1; - - const Range$e = range$1; - const validRange$1 = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$e(range, options).range || '*' - } catch (er) { - return null + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); } - }; - var valid$2 = validRange$1; - - const SemVer$f = semver$3; - const Comparator$5 = comparator$1; - const {ANY: ANY$4} = Comparator$5; - const Range$d = range$1; - const satisfies$6 = satisfies_1$1; - const gt$4 = gt_1$1; - const lt$3 = lt_1$1; - const lte$3 = lte_1$1; - const gte$3 = gte_1$1; - - const outside$5 = (version, range, hilo, options) => { - version = new SemVer$f(version, options); - range = new Range$d(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt$4; - ltefn = lte$3; - ltfn = lt$3; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt$3; - ltefn = gte$3; - ltfn = gt$4; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); } - - // If it satisfies the range it is not outside - if (satisfies$6(version, range, options)) { - return false + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$2; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + var re$5 = {exports: {}}; - let high = null; - let low = null; + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; - comparators.forEach((comparator) => { - if (comparator.semver === ANY$4) { - comparator = new Comparator$5('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH }; - var outside_1$1 = outside$5; + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; - // Determine if version is greater than all the versions possible in the range. - const outside$4 = outside_1$1; - const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); - var gtr_1$1 = gtr$1; + var debug_1 = debug$3; - const outside$3 = outside_1$1; - // Determine if version is less than all the versions possible in the range - const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); - var ltr_1$1 = ltr$1; + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; - const Range$c = range$1; - const intersects$1 = (r1, r2, options) => { - r1 = new Range$c(r1, options); - r2 = new Range$c(r2, options); - return r1.intersects(r2) + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); }; - var intersects_1$1 = intersects$1; - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$5 = satisfies_1$1; - const compare$c = compare_1$1; - var simplify$1 = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$c(a, b, options)); - for (const version of v) { - const included = satisfies$5(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. - const Range$b = range$1; - const Comparator$4 = comparator$1; - const { ANY: ANY$3 } = Comparator$4; - const satisfies$4 = satisfies_1$1; - const compare$b = compare_1$1; + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. - const subset$1 = (sub, dom, options = {}) => { - if (sub === dom) - return true + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - sub = new Range$b(sub, options); - dom = new Range$b(dom, options); - let sawNonNull = false; + // ## Main Version + // Three dot-separated numeric identifiers. - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset$1(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); - const simpleSubset$1 = (sub, dom, options) => { - if (sub === dom) - return true + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - if (sub.length === 1 && sub[0].semver === ANY$3) { - if (dom.length === 1 && dom[0].semver === ANY$3) - return true - else if (options.includePrerelease) - sub = [ new Comparator$4('>=0.0.0-0') ]; - else - sub = [ new Comparator$4('>=0.0.0') ]; - } + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. - if (dom.length === 1 && dom[0].semver === ANY$3) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator$4('>=0.0.0') ]; - } + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT$1(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT$1(lt, c, options); - else - eqSet.add(c.semver); - } + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); - if (eqSet.size > 1) - return null + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. - let gtltComp; - if (gt && lt) { - gtltComp = compare$b(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies$4(eq, String(gt), options)) - return null + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - if (lt && !satisfies$4(eq, String(lt), options)) - return null + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. - for (const c of dom) { - if (!satisfies$4(eq, String(c), options)) - return false - } + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - return true - } + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT$1(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT$1(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + createToken('FULL', `^${src[t.FULLPLAIN]}$`); - return true - }; + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); - // >=1.2.3 is lower than >1.2.3 - const higherGT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - // <=1.2.3 is higher than <1.2.3 - const lowerLT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; + createToken('GTLT', '((?:<|>)?=?)'); - var subset_1$1 = subset$1; + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - // just pre-load all the stuff that index.js lazily exports - const internalRe$1 = re$b.exports; - var semver$2 = { - re: internalRe$1.re, - src: internalRe$1.src, - tokens: internalRe$1.t, - SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, - SemVer: semver$3, - compareIdentifiers: identifiers$1.compareIdentifiers, - rcompareIdentifiers: identifiers$1.rcompareIdentifiers, - parse: parse_1$1, - valid: valid_1$1, - clean: clean_1$1, - inc: inc_1$1, - diff: diff_1$1, - major: major_1$1, - minor: minor_1$1, - patch: patch_1$1, - prerelease: prerelease_1$1, - compare: compare_1$1, - rcompare: rcompare_1$1, - compareLoose: compareLoose_1$1, - compareBuild: compareBuild_1$1, - sort: sort_1$1, - rsort: rsort_1$1, - gt: gt_1$1, - lt: lt_1$1, - eq: eq_1$1, - neq: neq_1$1, - gte: gte_1$1, - lte: lte_1$1, - cmp: cmp_1$1, - coerce: coerce_1$1, - Comparator: comparator$1, - Range: range$1, - satisfies: satisfies_1$1, - toComparators: toComparators_1$1, - maxSatisfying: maxSatisfying_1$1, - minSatisfying: minSatisfying_1$1, - minVersion: minVersion_1$1, - validRange: valid$2, - outside: outside_1$1, - gtr: gtr_1$1, - ltr: ltr_1$1, - intersects: intersects_1$1, - simplifyRange: simplify$1, - subset: subset_1$1, - }; + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$m.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$m.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer$m.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); - }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); - }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); - }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; - }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; - }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$m.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; - }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); - }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; - }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$m.concat([h, h, x])); - }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$m.concat([ - Buffer$m.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$m.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; - }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); - } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; - }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); - }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$m.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; - }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; - }; - return p2wpkh; - }(SingleKeyAccount)); + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; - }; - Merkle.prototype.size = function () { - return this.leaves.length; - }; - Merkle.prototype.getLeaves = function () { - return this.leaves; - }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; - }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); - }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; - }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$m.concat([Buffer$m.from([1]), left, right])); - }; - return Merkle; - }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$m.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$m.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; - } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; - } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) } - if (isPowerOf2(n)) { - return n / 2; + + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; - } - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md - */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$m.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; - } - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$m.from([0, 1])); + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } } + return id + }); } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); - } + return this.version + } - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); - }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - return NoSuchEntry; - }(Error)); - /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. - * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. - */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; + + if (other.version === this.version) { + return 0 } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); - } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; - } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; - } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; - } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; - }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$m.from(k.substring(2), "hex")); - } - }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$m.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); - }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); - }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - // Make sure to return a copy, to protect the underlying data. - return Buffer$m.from(value); - } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); - keyPair.serialize(buf); + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - buf.writeUInt8(0); - } - function b() { - return Buffer$m.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$m.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer$m.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); - } - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); - } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } else { + this.prerelease = [identifier, 0]; + } } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); + break + + default: + throw new Error(`invalid increment argument: ${release}`) } - psbt.deleteInputEntries(inputIndex, keyTypes); + this.format(); + this.raw = this.version; + return this + } } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$m.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } - buf.writeSlice(data); - } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$m.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer$m.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer$m.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; - } + case '': + case '=': + case '==': + return eq(a, b, loose) - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$m.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$m.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$m.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$m.concat([ - inputBuffer, - input.prevout, - Buffer$m.from([0x00]), - input.sequence, - ]) - : Buffer$m.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$m.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$m.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$m.alloc(0), - transaction.extraData || Buffer$m.alloc(0), - ]); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); } - return Buffer$m.concat([ - transaction.version, - timestamp ? timestamp : Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); + } + + return self } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver$2.major(appAndVersion.version) >= 2); + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$m.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); - }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } } - var id$2 = 0; - var subscribers$1 = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log$1 = function (type, message, data) { - var obj = { - type: type, - id: String(++id$2), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch$1(obj); + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen$1 = function (cb) { - subscribers$1.push(cb); - return function () { - var i = subscribers$1.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; - subscribers$1.pop(); - } - }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) }; - function dispatch$1(log) { - for (var i = 0; i < subscribers$1.length; i++) { - try { - subscribers$1[i](log); - } - catch (e) { - console.error(e); + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } } + } + } + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen$1; - } + var range = Range$a; - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log$1, - listen: listen$1 - }); + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$4.apply(this, arguments); - }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) }); + + testComparator = remainingComparators.pop(); + } + + return result }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); - } - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; } - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } + debug$1('tilde return', ret); + return ret + }) }; - var browser = invariant; + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$7 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$m.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$m.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$m.from([0x00]) - : Buffer$m.alloc(0); - data = Buffer$m.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$m.concat([ - output.amount, - isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$m.concat(endData); - extraPart = isDecred - ? data - : Buffer$m.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + debug$1('caret return', ret); + return ret + }) }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') }; - var __values$6 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$1('xRange return', ret); + + return ret + }) }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$m.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$m.from([0x00]); - } - } - data = Buffer$m.concat([ - prefix, - inputValue, - isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$m.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + }; + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; } - hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$m.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } + debug('comp', this); + } - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$m.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([sigHashType]), - ]) - : Buffer$m.concat([ - pathsBuffer, - Buffer$m.from([0x00]), - lockTimeBuffer, - Buffer$m.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$m.concat([buffer, expiryHeight]); + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); - }); - } - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true } - }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver$2.gte(version, "1.4.0"); - } + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$m.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$m.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$m.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$m.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$m.concat([ - Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$m.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$m.concat([ - Buffer$m.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer$m.alloc(1); - keySize = Buffer$m.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$m.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$m.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$m.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$m.concat([ - Buffer$m.from("02", "hex"), - Buffer$m.from([signatures[i].length]), - signatures[i], - Buffer$m.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$m.concat([witness, tmpScriptData]); - } - result = Buffer$m.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$m.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$m.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$m.alloc(0), - targetTransaction.extraData || Buffer$m.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$m.concat([ - decredWitness_1, - Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0xff, 0xff, 0xff, 0xff]), - Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$m.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } - }); - }); + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } } + }); + return min }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$m.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } }); - } + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); + if (minver && range.test(minver)) { + return minver + } + + return null }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$m.from(trustedInput, "hex") - : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); - } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; } - return createTransaction(this.transport, arg); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; } - return signP2SHTransaction(this.transport, arg); - }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$m.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$m.concat([ - Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$m.concat([ - asBufferUInt32BE(version), - Buffer$m.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$m.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$l.alloc(alloc); + fn(b); + this.bufs.push(b); }; - return MerkleMap; - }()); - - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$l.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$l.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; - } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; }; - return MerkelizedPsbt; - }(PsbtV2)); + return BufferReader; + }()); - var __extends$1 = (undefined && undefined.__extends) || (function () { + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); + } + + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36578,1280 +36271,1158 @@ window.Buffer = buffer.Buffer; d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; } - return ClientCommand; + return BaseAccount; }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$4(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$m.from(request.subarray(1))); - this.progressCallback(); - return Buffer$m.from(""); + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); } - // read the hash - var hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$m.from([known_preimage[i]])); - } - } - return Buffer$m.concat([ - preimage_len_varint, - Buffer$m.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); } - throw Error("Requested unknown preimage for: " + req_hash_hex); + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$4(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); } - return Buffer$m.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$m.from([proof.length]), - Buffer$m.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$4(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$l.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); } - return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$l.concat([ + Buffer$l.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$4(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); - } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); - } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$m.concat(__spreadArray$1([ - Buffer$m.from([n_returned_elements]), - Buffer$m.from([element_len]) - ], __read$1(returned_elements), false)); + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); - this.addKnownPreimage(preimage); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); - } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$4(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); } - return cmd.execute(request); + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); }; - return ClientCommandInterpreter; - }()); + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } } + return ar; }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + return to.concat(ar || Array.prototype.slice.call(from)); }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ - Buffer$m.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); + Merkle.prototype.size = function () { + return this.leaves.length; }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$m.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ - Buffer$m.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - Buffer$m.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); + Merkle.prototype.getLeaves = function () { + return this.leaves; }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.from([]))]; - }); - }); + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); }; - return AppClient; - }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$m.alloc(0); - var nExpiryHeight = Buffer$m.alloc(0); - var nVersionGroupId = Buffer$m.alloc(0); - var extraData = Buffer$m.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$m.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$m.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$m.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), + leaves: [] + }; } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$l.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$l.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$m.alloc(0); - var tree = Buffer$m.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); } - else { - locktime = transaction.slice(offset, offset + 4); + if (isPowerOf2(n)) { + return n / 2; } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; } - if (hasExtraData) { - extraData = transaction.slice(offset); + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$l.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$l.from([0, 1])); } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); } } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); } - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$5.apply(this, arguments); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; } - }; + return NoSuchEntry; + }(Error)); /** - * Bitcoin API. + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki * - * @example - * import Btc from "@backpacker69/hw-app-btc"; - * const btc = new Btc(transport) + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); + }; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); + }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); } }); }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; + } + }; + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$l.from(k.substring(2), "hex")); + } }); + return result; }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$l.from([])); + this.globalMap.set(key.toString(), value); }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); }); }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$l.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); }; - return Btc; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer$l.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$l.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + var b = Buffer$l.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); } - return false; } - - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses$3 = {}; - var deserializers$3 = {}; - var addCustomErrorDeserializer$3 = function (name, deserializer) { - deserializers$3[name] = deserializer; - }; - var createCustomErrorClass$3 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$3[name] = C; - return C; - }; - - createCustomErrorClass$3("AccountNameRequired"); - createCustomErrorClass$3("AccountNotSupported"); - createCustomErrorClass$3("AmountRequired"); - createCustomErrorClass$3("BluetoothRequired"); - createCustomErrorClass$3("BtcUnmatchedApp"); - createCustomErrorClass$3("CantOpenDevice"); - createCustomErrorClass$3("CashAddrNotSupported"); - createCustomErrorClass$3("CurrencyNotSupported"); - createCustomErrorClass$3("DeviceAppVerifyNotSupported"); - createCustomErrorClass$3("DeviceGenuineSocketEarlyClose"); - createCustomErrorClass$3("DeviceNotGenuine"); - createCustomErrorClass$3("DeviceOnDashboardExpected"); - createCustomErrorClass$3("DeviceOnDashboardUnexpected"); - createCustomErrorClass$3("DeviceInOSUExpected"); - createCustomErrorClass$3("DeviceHalted"); - createCustomErrorClass$3("DeviceNameInvalid"); - createCustomErrorClass$3("DeviceSocketFail"); - createCustomErrorClass$3("DeviceSocketNoBulkStatus"); - createCustomErrorClass$3("DisconnectedDevice"); - createCustomErrorClass$3("DisconnectedDeviceDuringOperation"); - createCustomErrorClass$3("EnpointConfig"); - createCustomErrorClass$3("EthAppPleaseEnableContractData"); - createCustomErrorClass$3("FeeEstimationFailed"); - createCustomErrorClass$3("FirmwareNotRecognized"); - createCustomErrorClass$3("HardResetFail"); - createCustomErrorClass$3("InvalidXRPTag"); - createCustomErrorClass$3("InvalidAddress"); - createCustomErrorClass$3("InvalidAddressBecauseDestinationIsAlsoSource"); - createCustomErrorClass$3("LatestMCUInstalledError"); - createCustomErrorClass$3("UnknownMCU"); - createCustomErrorClass$3("LedgerAPIError"); - createCustomErrorClass$3("LedgerAPIErrorWithMessage"); - createCustomErrorClass$3("LedgerAPINotAvailable"); - createCustomErrorClass$3("ManagerAppAlreadyInstalled"); - createCustomErrorClass$3("ManagerAppRelyOnBTC"); - createCustomErrorClass$3("ManagerAppDepInstallRequired"); - createCustomErrorClass$3("ManagerAppDepUninstallRequired"); - createCustomErrorClass$3("ManagerDeviceLocked"); - createCustomErrorClass$3("ManagerFirmwareNotEnoughSpace"); - createCustomErrorClass$3("ManagerNotEnoughSpace"); - createCustomErrorClass$3("ManagerUninstallBTCDep"); - createCustomErrorClass$3("NetworkDown"); - createCustomErrorClass$3("NoAddressesFound"); - createCustomErrorClass$3("NotEnoughBalance"); - createCustomErrorClass$3("NotEnoughBalanceToDelegate"); - createCustomErrorClass$3("NotEnoughBalanceInParentAccount"); - createCustomErrorClass$3("NotEnoughSpendableBalance"); - createCustomErrorClass$3("NotEnoughBalanceBecauseDestinationNotCreated"); - createCustomErrorClass$3("NoAccessToCamera"); - createCustomErrorClass$3("NotEnoughGas"); - createCustomErrorClass$3("NotSupportedLegacyAddress"); - createCustomErrorClass$3("GasLessThanEstimate"); - createCustomErrorClass$3("PasswordsDontMatch"); - createCustomErrorClass$3("PasswordIncorrect"); - createCustomErrorClass$3("RecommendSubAccountsToEmpty"); - createCustomErrorClass$3("RecommendUndelegation"); - createCustomErrorClass$3("TimeoutTagged"); - createCustomErrorClass$3("UnexpectedBootloader"); - createCustomErrorClass$3("MCUNotGenuineToDashboard"); - createCustomErrorClass$3("RecipientRequired"); - createCustomErrorClass$3("UnavailableTezosOriginatedAccountReceive"); - createCustomErrorClass$3("UnavailableTezosOriginatedAccountSend"); - createCustomErrorClass$3("UpdateFetchFileFail"); - createCustomErrorClass$3("UpdateIncorrectHash"); - createCustomErrorClass$3("UpdateIncorrectSig"); - createCustomErrorClass$3("UpdateYourApp"); - createCustomErrorClass$3("UserRefusedDeviceNameChange"); - createCustomErrorClass$3("UserRefusedAddress"); - createCustomErrorClass$3("UserRefusedFirmwareUpdate"); - createCustomErrorClass$3("UserRefusedAllowManager"); - createCustomErrorClass$3("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - createCustomErrorClass$3("TransportOpenUserCancelled"); - createCustomErrorClass$3("TransportInterfaceNotAvailable"); - var TransportRaceCondition$2 = createCustomErrorClass$3("TransportRaceCondition"); - createCustomErrorClass$3("TransportWebUSBGestureRequired"); - createCustomErrorClass$3("DeviceShouldStayInApp"); - createCustomErrorClass$3("WebsocketConnectionError"); - createCustomErrorClass$3("WebsocketConnectionFailed"); - createCustomErrorClass$3("WrongDeviceForAccount"); - createCustomErrorClass$3("WrongAppForCurrency"); - createCustomErrorClass$3("ETHAddressNonEIP"); - createCustomErrorClass$3("CantScanQRCode"); - createCustomErrorClass$3("FeeNotLoaded"); - createCustomErrorClass$3("FeeRequired"); - createCustomErrorClass$3("FeeTooHigh"); - createCustomErrorClass$3("SyncError"); - createCustomErrorClass$3("PairingFailed"); - createCustomErrorClass$3("GenuineCheckFailed"); - createCustomErrorClass$3("LedgerAPI4xx"); - createCustomErrorClass$3("LedgerAPI5xx"); - createCustomErrorClass$3("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - createCustomErrorClass$3("NoDBPathGiven"); - createCustomErrorClass$3("DBWrongPassword"); - createCustomErrorClass$3("DBNotReset"); /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. */ - function TransportError$3(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); } - TransportError$3.prototype = new Error(); - addCustomErrorDeserializer$3("TransportError", function (e) { return new TransportError$3(e.message, e.id); }); - var StatusCodes$3 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$3(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$l.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$l.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$l.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; } + var buffer = Buffer$l.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; } + /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$3(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$3).find(function (k) { return StatusCodes$3[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$3(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$l.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$l.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$l.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$l.concat([ + inputBuffer, + input.prevout, + Buffer$l.from([0x00]), + input.sequence, + ]) + : Buffer$l.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$l.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$l.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$l.alloc(0), + transaction.extraData || Buffer$l.alloc(0), + ]); + } + return Buffer$l.concat([ + transaction.version, + timestamp ? timestamp : Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); } - TransportStatusError$3.prototype = new Error(); - addCustomErrorDeserializer$3("TransportStatusError", function (e) { return new TransportStatusError$3(e.statusCode); }); - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37860,7 +37431,7 @@ window.Buffer = buffer.Buffer; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37887,2795 +37458,4229 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. */ - var Transport$1 = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$m.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes$3.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError$3("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; + } + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); + }; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); + }; + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); } - return [4 /*yield*/, this.exchange(Buffer$m.concat([ - Buffer$m.from([cla, ins, p1, p2]), - Buffer$m.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError$3(sw); + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); } - return [2 /*return*/, response]; - } - }); + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { + }); + }; + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$e(this, function (_a) { switch (_a.label) { case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition$2("An action was already pending on the Ledger device. Please deny or reconnect."); + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; } }); - }); }; - this._appAPIlock = null; - } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; + }); }; /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError$3(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; } }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError$3(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; }); }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values$1(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError$3("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } }); - }; + }); }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; + return BtcNew; }()); - - var hidFraming$1 = {}; - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses$2 = {}; - var deserializers$2 = {}; - var addCustomErrorDeserializer$2 = function (name, deserializer) { - deserializers$2[name] = deserializer; - }; - var createCustomErrorClass$2 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$2[name] = C; - return C; - }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers$2[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses$2[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass$2(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass$2("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass$2("AccountNotSupported"); - var AmountRequired = createCustomErrorClass$2("AmountRequired"); - var BluetoothRequired = createCustomErrorClass$2("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass$2("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass$2("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass$2("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass$2("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass$2("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass$2("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass$2("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass$2("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass$2("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass$2("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass$2("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass$2("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass$2("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass$2("DeviceSocketNoBulkStatus"); - var DisconnectedDevice$1 = createCustomErrorClass$2("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation$1 = createCustomErrorClass$2("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass$2("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass$2("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass$2("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass$2("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass$2("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass$2("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass$2("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$2("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass$2("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass$2("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass$2("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass$2("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass$2("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass$2("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass$2("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass$2("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass$2("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass$2("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$2("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass$2("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass$2("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass$2("NetworkDown"); - var NoAddressesFound = createCustomErrorClass$2("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass$2("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass$2("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass$2("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass$2("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$2("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass$2("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass$2("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass$2("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass$2("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass$2("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass$2("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass$2("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass$2("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass$2("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass$2("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass$2("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass$2("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$2("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$2("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass$2("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass$2("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass$2("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass$2("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass$2("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass$2("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass$2("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass$2("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass$2("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled$1 = createCustomErrorClass$2("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable$1 = createCustomErrorClass$2("TransportInterfaceNotAvailable"); - var TransportRaceCondition$1 = createCustomErrorClass$2("TransportRaceCondition"); - var TransportWebUSBGestureRequired$1 = createCustomErrorClass$2("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass$2("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass$2("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass$2("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass$2("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass$2("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass$2("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass$2("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass$2("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass$2("FeeRequired"); - var FeeTooHigh = createCustomErrorClass$2("FeeTooHigh"); - var SyncError = createCustomErrorClass$2("SyncError"); - var PairingFailed = createCustomErrorClass$2("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass$2("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass$2("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass$2("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass$2("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass$2("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass$2("DBWrongPassword"); - var DBNotReset = createCustomErrorClass$2("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$2(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); } - TransportError$2.prototype = new Error(); - addCustomErrorDeserializer$2("TransportError", function (e) { return new TransportError$2(e.message, e.id); }); - var StatusCodes$2 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$2(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); } + + var id$2 = 0; + var subscribers$1 = []; /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type */ - function TransportStatusError$2(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$2).find(function (k) { return StatusCodes$2[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$2(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$2.prototype = new Error(); - addCustomErrorDeserializer$2("TransportStatusError", function (e) { return new TransportStatusError$2(e.statusCode); }); - - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass$2, - addCustomErrorDeserializer: addCustomErrorDeserializer$2, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice$1, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation$1, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled$1, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable$1, - TransportRaceCondition: TransportRaceCondition$1, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired$1, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError$2, - StatusCodes: StatusCodes$2, - getAltStatusMessage: getAltStatusMessage$2, - TransportStatusError: TransportStatusError$2 - }); - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$m.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$m.alloc(0), - dataLength: 0, - sequence: 0 + var log$1 = function (type, message, data) { + var obj = { + type: type, + id: String(++id$2), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch$1(obj); }; /** - * + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$m.concat([ - data, - Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$m.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$m.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$m.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } + var listen$1 = function (cb) { + subscribers$1.push(cb); + return function () { + var i = subscribers$1.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; + subscribers$1.pop(); } }; }; - exports["default"] = createHIDframing; - - }(hidFraming$1)); - - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); - - var re$5 = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; - - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; - - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; - - const debug$3 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$3; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; + function dispatch$1(log) { + for (var i = 0; i < subscribers$1.length; i++) { + try { + subscribers$1[i](log); + } + catch (e) { + console.error(e); + } + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen$1; + } - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log$1, + listen: listen$1 + }); - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; - - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; - - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); } + } - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; } - debug$2('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + var browser = invariant; - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$l.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$l.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ + transaction.version, + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$l.from([0x00]) + : Buffer$l.alloc(0); + data = Buffer$l.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$l.concat([ + output.amount, + isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$l.concat(endData); + extraPart = isDecred + ? data + : Buffer$l.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$l.concat([ + transaction.version, + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$l.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$l.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$l.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$l.from([0x00]); + } + } + data = Buffer$l.concat([ + prefix, + inputValue, + isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$l.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$l.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); } - return this.version - } + hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } - toString () { - return this.version - } + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$l.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } - compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$l.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$l.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([sigHashType]), + ]) + : Buffer$l.concat([ + pathsBuffer, + Buffer$l.from([0x00]), + lockTimeBuffer, + Buffer$l.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$l.concat([buffer, expiryHeight]); } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } - if (other.version === this.version) { - return 0 + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$l.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$l.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log$1("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$l.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$l.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$l.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$l.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$l.concat([ + Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$l.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$l.concat([ + Buffer$l.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$l.alloc(1); + keySize = Buffer$l.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$l.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$l.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$l.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$l.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$l.concat([ + Buffer$l.from("02", "hex"), + Buffer$l.from([signatures[i].length]), + signatures[i], + Buffer$l.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$l.concat([witness, tmpScriptData]); + } + result = Buffer$l.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$l.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$l.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$l.alloc(0), + targetTransaction.extraData || Buffer$l.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$l.concat([ + decredWitness_1, + Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0xff, 0xff, 0xff, 0xff]), + Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$l.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$l.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$l.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$l.from(trustedInput, "hex") + : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$l.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } + }); + }); } - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; - - var parse_1 = parse$5; - - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; - - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; - - const SemVer$c = semver$1; - - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - - const parse$2 = parse_1; - const eq$1 = eq_1; - - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - } - } - return defaultResult // may be undefined - } - }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; - - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; - - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; - - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + return t; + }; + return __assign$1.apply(this, arguments); }; - var prerelease_1 = prerelease; - - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; - - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var compareBuild_1 = compareBuild$2; - - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; - - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; - - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; - - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; - - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; - - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; - - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; - - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; - - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt$2(a, b, loose) - - case '>=': - return gte$1(a, b, loose) - - case '<': - return lt$1(a, b, loose) - - case '<=': - return lte$1(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$l.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$l.concat([ + Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$l.concat([ + asBufferUInt32BE(version), + Buffer$l.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } - if (match === null) - return null + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$l.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - var coerce_1 = coerce; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } + finally { if (e) throw e.error; } } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false - } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$l.from(request.subarray(1))); + this.progressCallback(); + return Buffer$l.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$l.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$l.from([known_preimage[i]])); + } + } + return Buffer$l.concat([ + preimage_len_varint, + Buffer$l.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$l.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$l.from([proof.length]), + Buffer$l.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$l.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$l.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$l.concat(__spreadArray$1([ + Buffer$l.from([n_returned_elements]), + Buffer$l.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } } - return false - } - } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); - return comp }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$1('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - - debug$1('tilde return', ret); - return ret - }) }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$1('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$1('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$1('caret return', ret); - return ret - }) - }; - - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$l.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$l.alloc(32, 0), + Buffer$l.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$l.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; + }); + }); + }; + return AppClient; + }()); - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$l.alloc(0); + var nExpiryHeight = Buffer$l.alloc(0); + var nVersionGroupId = Buffer$l.alloc(0); + var extraData = Buffer$l.alloc(0); + var isDecred = additionals.includes("decred"); + var isPeercoin = additionals.includes("peercoin"); + var transaction = Buffer$l.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + if (!isPeercoin || + (isPeercoin && oldpeercoin)) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; } - - debug$1('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; - - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$l.alloc(0); + var tree = Buffer$l.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; } - } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 - } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); } - - debug('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); } - - debug('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) + else { + locktime = transaction.slice(offset, offset + 4); } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); + if (hasExtraData) { + extraData = transaction.slice(offset); } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@backpacker69/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } + return false; } - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } - } - }); - return max + var errorClasses$1 = {}; + var deserializers$1 = {}; + var addCustomErrorDeserializer$1 = function (name, deserializer) { + deserializers$1[name] = deserializer; }; - var maxSatisfying_1 = maxSatisfying; - - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); - } - } - }); - return min + var createCustomErrorClass$1 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$1[name] = C; + return C; }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers$1[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass$1(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } } - } - return true - }; - - var outside_1 = outside$2; + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; + var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); + var AmountRequired = createCustomErrorClass$1("AmountRequired"); + var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass$1("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass$1("NetworkDown"); + var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); + var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass$1("FeeRequired"); + var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); + var SyncError = createCustomErrorClass$1("SyncError"); + var PairingFailed = createCustomErrorClass$1("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); + var DBNotReset = createCustomErrorClass$1("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$1(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); + var StatusCodes$1 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage$1(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$1(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$1(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass$1, + addCustomErrorDeserializer: addCustomErrorDeserializer$1, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition$1, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError$1, + StatusCodes: StatusCodes$1, + getAltStatusMessage: getAltStatusMessage$1, + TransportStatusError: TransportStatusError$1 + }); - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport$1 = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$l.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$l.concat([ + Buffer$l.from([cla, ins, p1, p2]), + Buffer$l.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError$1(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); + }; + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); + }; + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); + }; + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + }; + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } + } + }; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + var hidFraming$1 = {}; - return true - }; + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$l.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$l.alloc(0), + dataLength: 0, + sequence: 0 }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$l.concat([ + data, + Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$l.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$l.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$l.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; }; + exports["default"] = createHIDframing; - var subset_1 = subset; + }(hidFraming$1)); - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -40793,216 +41798,6 @@ window.Buffer = buffer.Buffer; } } - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses$1 = {}; - var deserializers$1 = {}; - var addCustomErrorDeserializer$1 = function (name, deserializer) { - deserializers$1[name] = deserializer; - }; - var createCustomErrorClass$1 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$1[name] = C; - return C; - }; - - createCustomErrorClass$1("AccountNameRequired"); - createCustomErrorClass$1("AccountNotSupported"); - createCustomErrorClass$1("AmountRequired"); - createCustomErrorClass$1("BluetoothRequired"); - createCustomErrorClass$1("BtcUnmatchedApp"); - createCustomErrorClass$1("CantOpenDevice"); - createCustomErrorClass$1("CashAddrNotSupported"); - createCustomErrorClass$1("CurrencyNotSupported"); - createCustomErrorClass$1("DeviceAppVerifyNotSupported"); - createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); - createCustomErrorClass$1("DeviceNotGenuine"); - createCustomErrorClass$1("DeviceOnDashboardExpected"); - createCustomErrorClass$1("DeviceOnDashboardUnexpected"); - createCustomErrorClass$1("DeviceInOSUExpected"); - createCustomErrorClass$1("DeviceHalted"); - createCustomErrorClass$1("DeviceNameInvalid"); - createCustomErrorClass$1("DeviceSocketFail"); - createCustomErrorClass$1("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); - createCustomErrorClass$1("EnpointConfig"); - createCustomErrorClass$1("EthAppPleaseEnableContractData"); - createCustomErrorClass$1("FeeEstimationFailed"); - createCustomErrorClass$1("FirmwareNotRecognized"); - createCustomErrorClass$1("HardResetFail"); - createCustomErrorClass$1("InvalidXRPTag"); - createCustomErrorClass$1("InvalidAddress"); - createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); - createCustomErrorClass$1("LatestMCUInstalledError"); - createCustomErrorClass$1("UnknownMCU"); - createCustomErrorClass$1("LedgerAPIError"); - createCustomErrorClass$1("LedgerAPIErrorWithMessage"); - createCustomErrorClass$1("LedgerAPINotAvailable"); - createCustomErrorClass$1("ManagerAppAlreadyInstalled"); - createCustomErrorClass$1("ManagerAppRelyOnBTC"); - createCustomErrorClass$1("ManagerAppDepInstallRequired"); - createCustomErrorClass$1("ManagerAppDepUninstallRequired"); - createCustomErrorClass$1("ManagerDeviceLocked"); - createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); - createCustomErrorClass$1("ManagerNotEnoughSpace"); - createCustomErrorClass$1("ManagerUninstallBTCDep"); - createCustomErrorClass$1("NetworkDown"); - createCustomErrorClass$1("NoAddressesFound"); - createCustomErrorClass$1("NotEnoughBalance"); - createCustomErrorClass$1("NotEnoughBalanceToDelegate"); - createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); - createCustomErrorClass$1("NotEnoughSpendableBalance"); - createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); - createCustomErrorClass$1("NoAccessToCamera"); - createCustomErrorClass$1("NotEnoughGas"); - createCustomErrorClass$1("NotSupportedLegacyAddress"); - createCustomErrorClass$1("GasLessThanEstimate"); - createCustomErrorClass$1("PasswordsDontMatch"); - createCustomErrorClass$1("PasswordIncorrect"); - createCustomErrorClass$1("RecommendSubAccountsToEmpty"); - createCustomErrorClass$1("RecommendUndelegation"); - createCustomErrorClass$1("TimeoutTagged"); - createCustomErrorClass$1("UnexpectedBootloader"); - createCustomErrorClass$1("MCUNotGenuineToDashboard"); - createCustomErrorClass$1("RecipientRequired"); - createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); - createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); - createCustomErrorClass$1("UpdateFetchFileFail"); - createCustomErrorClass$1("UpdateIncorrectHash"); - createCustomErrorClass$1("UpdateIncorrectSig"); - createCustomErrorClass$1("UpdateYourApp"); - createCustomErrorClass$1("UserRefusedDeviceNameChange"); - createCustomErrorClass$1("UserRefusedAddress"); - createCustomErrorClass$1("UserRefusedFirmwareUpdate"); - createCustomErrorClass$1("UserRefusedAllowManager"); - createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); - createCustomErrorClass$1("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); - createCustomErrorClass$1("DeviceShouldStayInApp"); - createCustomErrorClass$1("WebsocketConnectionError"); - createCustomErrorClass$1("WebsocketConnectionFailed"); - createCustomErrorClass$1("WrongDeviceForAccount"); - createCustomErrorClass$1("WrongAppForCurrency"); - createCustomErrorClass$1("ETHAddressNonEIP"); - createCustomErrorClass$1("CantScanQRCode"); - createCustomErrorClass$1("FeeNotLoaded"); - createCustomErrorClass$1("FeeRequired"); - createCustomErrorClass$1("FeeTooHigh"); - createCustomErrorClass$1("SyncError"); - createCustomErrorClass$1("PairingFailed"); - createCustomErrorClass$1("GenuineCheckFailed"); - createCustomErrorClass$1("LedgerAPI4xx"); - createCustomErrorClass$1("LedgerAPI5xx"); - createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - createCustomErrorClass$1("NoDBPathGiven"); - createCustomErrorClass$1("DBWrongPassword"); - createCustomErrorClass$1("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$1(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); - var StatusCodes$1 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$1(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$1(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$1(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -41321,7 +42116,7 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$m.from(r.data.buffer); + buffer = Buffer$l.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -42325,12 +43120,12 @@ window.Buffer = buffer.Buffer; this.deviceModel = null; this._events = new EventEmitter$1(); - this.send = async (cla, ins, p1, p2, data = Buffer$m.alloc(0), statusList = [StatusCodes.OK]) => { + this.send = async (cla, ins, p1, p2, data = Buffer$l.alloc(0), statusList = [StatusCodes.OK]) => { if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - const response = await this.exchange(Buffer$m.concat([Buffer$m.from([cla, ins, p1, p2]), Buffer$m.from([data.length]), data])); + const response = await this.exchange(Buffer$l.concat([Buffer$l.from([cla, ins, p1, p2]), Buffer$l.from([data.length]), data])); const sw = response.readUInt16BE(response.length - 2); if (!statusList.some(s => s === sw)) { @@ -42593,7 +43388,7 @@ window.Buffer = buffer.Buffer; } function wrapApdu(apdu, key) { - const result = Buffer$m.alloc(apdu.length); + const result = Buffer$l.alloc(apdu.length); for (let i = 0; i < apdu.length; i++) { result[i] = apdu[i] ^ key[i % key.length]; @@ -42610,7 +43405,7 @@ window.Buffer = buffer.Buffer; function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$m.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const challenge = Buffer$l.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); const signRequest = { version: "U2F_V2", keyHandle: webSafe64(keyHandle.toString("base64")), @@ -42624,7 +43419,7 @@ window.Buffer = buffer.Buffer; } = response; if (typeof signatureData === "string") { - const data = Buffer$m.from(normal64(signatureData), "base64"); + const data = Buffer$l.from(normal64(signatureData), "base64"); let result; if (!unwrap) { @@ -42710,7 +43505,7 @@ window.Buffer = buffer.Buffer; setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$m.from(scrambleKey, "ascii"); + this.scrambleKey = Buffer$l.from(scrambleKey, "ascii"); } /** */ From c86b6505e52c8097803a0a640df750ef16ea51c6 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 25 Jan 2022 18:59:08 +1100 Subject: [PATCH 40/78] real new version --- js/ledger.js | 12037 ++++++++++++++++++++++--------------------------- 1 file changed, 5405 insertions(+), 6632 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index ad61cb7f..b3c91027 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1003,7 +1003,7 @@ window.Buffer = buffer.Buffer; var toString = {}.toString; - var isArray$1 = Array.isArray || function (arr) { + var isArray$3 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1033,12 +1033,12 @@ window.Buffer = buffer.Buffer; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$l.TYPED_ARRAY_SUPPORT + return Buffer$k.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1047,14 +1047,14 @@ window.Buffer = buffer.Buffer; if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$l(length); + that = new Buffer$k(length); } that.length = length; } @@ -1072,9 +1072,9 @@ window.Buffer = buffer.Buffer; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$l (arg, encodingOrOffset, length) { - if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { - return new Buffer$l(arg, encodingOrOffset, length) + function Buffer$k (arg, encodingOrOffset, length) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { + return new Buffer$k(arg, encodingOrOffset, length) } // Common case. @@ -1086,18 +1086,18 @@ window.Buffer = buffer.Buffer; } return allocUnsafe(this, arg) } - return from$1(this, arg, encodingOrOffset, length) + return from(this, arg, encodingOrOffset, length) } - Buffer$l.poolSize = 8192; // not used by this implementation + Buffer$k.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$l._augment = function (arr) { - arr.__proto__ = Buffer$l.prototype; + Buffer$k._augment = function (arr) { + arr.__proto__ = Buffer$k.prototype; return arr }; - function from$1 (that, value, encodingOrOffset, length) { + function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1121,13 +1121,13 @@ window.Buffer = buffer.Buffer; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$l.from = function (value, encodingOrOffset, length) { - return from$1(null, value, encodingOrOffset, length) + Buffer$k.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) }; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { - Buffer$l.prototype.__proto__ = Uint8Array.prototype; - Buffer$l.__proto__ = Uint8Array; + if (Buffer$k.TYPED_ARRAY_SUPPORT) { + Buffer$k.prototype.__proto__ = Uint8Array.prototype; + Buffer$k.__proto__ = Uint8Array; } function assertSize (size) { @@ -1158,14 +1158,14 @@ window.Buffer = buffer.Buffer; * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$l.alloc = function (size, fill, encoding) { + Buffer$k.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1176,13 +1176,13 @@ window.Buffer = buffer.Buffer; /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$l.allocUnsafe = function (size) { + Buffer$k.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$l.allocUnsafeSlow = function (size) { + Buffer$k.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1191,7 +1191,7 @@ window.Buffer = buffer.Buffer; encoding = 'utf8'; } - if (!Buffer$l.isEncoding(encoding)) { + if (!Buffer$k.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1238,10 +1238,10 @@ window.Buffer = buffer.Buffer; array = new Uint8Array(array, byteOffset, length); } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1271,7 +1271,7 @@ window.Buffer = buffer.Buffer; return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$1(obj.data)) { + if (obj.type === 'Buffer' && isArray$3(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1288,12 +1288,12 @@ window.Buffer = buffer.Buffer; } return length | 0 } - Buffer$l.isBuffer = isBuffer; + Buffer$k.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$l.compare = function compare (a, b) { + Buffer$k.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1316,7 +1316,7 @@ window.Buffer = buffer.Buffer; return 0 }; - Buffer$l.isEncoding = function isEncoding (encoding) { + Buffer$k.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1335,13 +1335,13 @@ window.Buffer = buffer.Buffer; } }; - Buffer$l.concat = function concat (list, length) { - if (!isArray$1(list)) { + Buffer$k.concat = function concat (list, length) { + if (!isArray$3(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$l.alloc(0) + return Buffer$k.alloc(0) } var i; @@ -1352,7 +1352,7 @@ window.Buffer = buffer.Buffer; } } - var buffer = Buffer$l.allocUnsafe(length); + var buffer = Buffer$k.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1408,7 +1408,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$l.byteLength = byteLength$1; + Buffer$k.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1482,7 +1482,7 @@ window.Buffer = buffer.Buffer; // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$l.prototype._isBuffer = true; + Buffer$k.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1490,7 +1490,7 @@ window.Buffer = buffer.Buffer; b[m] = i; } - Buffer$l.prototype.swap16 = function swap16 () { + Buffer$k.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1501,7 +1501,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.swap32 = function swap32 () { + Buffer$k.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1513,7 +1513,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.swap64 = function swap64 () { + Buffer$k.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1527,20 +1527,20 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$l.prototype.toString = function toString () { + Buffer$k.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$l.prototype.equals = function equals (b) { + Buffer$k.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$l.compare(this, b) === 0 + return Buffer$k.compare(this, b) === 0 }; - Buffer$l.prototype.inspect = function inspect () { + Buffer$k.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1550,7 +1550,7 @@ window.Buffer = buffer.Buffer; return '' }; - Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1649,7 +1649,7 @@ window.Buffer = buffer.Buffer; // Normalize val if (typeof val === 'string') { - val = Buffer$l.from(val, encoding); + val = Buffer$k.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1661,7 +1661,7 @@ window.Buffer = buffer.Buffer; return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$l.TYPED_ARRAY_SUPPORT && + if (Buffer$k.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1731,15 +1731,15 @@ window.Buffer = buffer.Buffer; return -1 } - Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1790,7 +1790,7 @@ window.Buffer = buffer.Buffer; return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$l.prototype.write = function write (string, offset, length, encoding) { + Buffer$k.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1862,7 +1862,7 @@ window.Buffer = buffer.Buffer; } }; - Buffer$l.prototype.toJSON = function toJSON () { + Buffer$k.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2015,7 +2015,7 @@ window.Buffer = buffer.Buffer; return res } - Buffer$l.prototype.slice = function slice (start, end) { + Buffer$k.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2037,12 +2037,12 @@ window.Buffer = buffer.Buffer; if (end < start) end = start; var newBuf; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$l.prototype; + newBuf.__proto__ = Buffer$k.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$l(sliceLen, undefined); + newBuf = new Buffer$k(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2059,7 +2059,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2074,7 +2074,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2090,22 +2090,22 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2114,7 +2114,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] * 0x1000000) }; - Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2123,7 +2123,7 @@ window.Buffer = buffer.Buffer; this[offset + 3]) }; - Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2141,7 +2141,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2159,25 +2159,25 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2186,7 +2186,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] << 24) }; - Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2195,22 +2195,22 @@ window.Buffer = buffer.Buffer; (this[offset + 3]) }; - Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2221,7 +2221,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2240,7 +2240,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2259,11 +2259,11 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2276,11 +2276,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2289,11 +2289,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2309,11 +2309,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2324,11 +2324,11 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2339,7 +2339,7 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2362,7 +2362,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2385,21 +2385,21 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2408,11 +2408,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2421,11 +2421,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2436,12 +2436,12 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$l.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$k.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; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2465,11 +2465,11 @@ window.Buffer = buffer.Buffer; return offset + 4 } - Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2481,16 +2481,16 @@ window.Buffer = buffer.Buffer; return offset + 8 } - Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2522,7 +2522,7 @@ window.Buffer = buffer.Buffer; for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2542,7 +2542,7 @@ window.Buffer = buffer.Buffer; // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$l.prototype.fill = function fill (val, start, end, encoding) { + Buffer$k.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2562,7 +2562,7 @@ window.Buffer = buffer.Buffer; if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2591,7 +2591,7 @@ window.Buffer = buffer.Buffer; } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$l(val, encoding).toString()); + : utf8ToBytes(new Buffer$k(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5025,8 +5025,6 @@ window.Buffer = buffer.Buffer; }; }(safeBuffer, safeBuffer.exports)); - var readableBrowser = {exports: {}}; - // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5162,23 +5160,23 @@ window.Buffer = buffer.Buffer; }; var title = 'browser'; var platform = 'browser'; - var browser$6 = true; + var browser$5 = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config$1 = {}; + var config = {}; - function noop$2() {} + function noop() {} - var on = noop$2; - var addListener = noop$2; - var once$3 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; + var on = noop; + var addListener = noop; + var once$1 = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); @@ -5226,14 +5224,14 @@ window.Buffer = buffer.Buffer; var process = { nextTick: nextTick, title: title, - browser: browser$6, + browser: browser$5, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, - once: once$3, + once: once$1, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -5245,10 +5243,12 @@ window.Buffer = buffer.Buffer; hrtime: hrtime, platform: platform, release: release, - config: config$1, + config: config, uptime: uptime }; + var readable = {exports: {}}; + var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; @@ -5284,7 +5284,7 @@ window.Buffer = buffer.Buffer; EventEmitter.init.call(this); } events.exports = EventEmitter; - events.exports.once = once$2; + events.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; @@ -5676,7 +5676,7 @@ window.Buffer = buffer.Buffer; return ret; } - function once$2(emitter, name) { + function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); @@ -5727,6696 +5727,5490 @@ window.Buffer = buffer.Buffer; var EventEmitter$1 = events.exports; - var streamBrowser = events.exports.EventEmitter; - - var _nodeResolve_empty = {}; - - var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': _nodeResolve_empty - }); - - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - var _require$2 = buffer, - Buffer$k = _require$2.Buffer; - - var _require2 = require$$3, - inspect$1 = _require2.inspect; - - var custom = inspect$1 && inspect$1.custom || 'inspect'; - - function copyBuffer(src, target, offset) { - Buffer$k.prototype.copy.call(src, target, offset); + var inherits$h; + if (typeof Object.create === 'function'){ + inherits$h = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$h = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; } + var inherits$i = inherits$h; - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$k.alloc(0); - var ret = Buffer$k.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$k.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; + 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]'; } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect$1(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); + default: + return x; } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); - } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull$1(x) || !isObject$1(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); } + } + return str; + } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined$1(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); - } else { - nextTick(emitCloseNT, _this); + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); - } else { - nextTick(emitCloseNT, _this); + warned = true; } - }); + return fn.apply(this, arguments); + } - return this; + return deprecated; } - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined$1(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; } - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); + /** + * 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$1(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined$1(ctx.depth)) ctx.depth = 2; + if (isUndefined$1(ctx.colors)) ctx.colors = false; + if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + // 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] + }; - 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; + // 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 emitErrorNT(self, err) { - self.emit('error', err); - } - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + function stylizeNoColor(str, styleType) { + return str; } - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - var errorsBrowser = {}; + function arrayToHash(array) { + var hash = {}; - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + array.forEach(function(val, idx) { + hash[val] = true; + }); - var codes = {}; + return hash; + } - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); + 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$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== 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$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); } + return ret; } - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError$1(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate$1(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError$1(value)) { + return formatError(value); } - } else { - return "of ".concat(thing, " ").concat(String(expected)); } - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + var base = '', array = false, braces = ['{', '}']; - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; + // Make Array say that they are Array + if (isArray$2(value)) { + array = true; + braces = ['[', ']']; } - return str.substring(this_len - search.length, this_len) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + // Make RegExps say that they are RegExps + if (isRegExp$1(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; + // Make dates with properties first say the date + if (isDate$1(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; + // Make error with message first say the error + if (isError$1(value)) { + base = ' ' + formatError(value); } - } - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; + if (recurseTimes < 0) { + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } } - var msg; + ctx.seen.push(value); - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); } - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg; - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - errorsBrowser.codes = codes; - - var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + ctx.seen.pop(); - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + return reduceToSingleString(output, base, braces); } - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } // Default value + function formatPrimitive(ctx, value) { + if (isUndefined$1(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber$1(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean$1(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull$1(value)) + return ctx.stylize('null', 'null'); + } - return state.objectMode ? 16 : 16 * 1024; + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } - var state = { - getHighWaterMark: getHighWaterMark$2 - }; - - /** - * Module exports. - */ - var browser$5 = deprecate$1; + 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; + } - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - function deprecate$1 (fn, msg) { - if (config('noDeprecation')) { - return fn; + 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'); + } } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull$1(recurseTimes)) { + str = formatValue(ctx, desc.value, null); } else { - console.warn(msg); + str = formatValue(ctx, desc.value, recurseTimes - 1); } - warned = true; + 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'); } - return fn.apply(this, arguments); } - - return deprecated; - } - - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!commonjsGlobal.localStorage) return false; - } catch (_) { - return false; + if (isUndefined$1(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'); + } } - var val = commonjsGlobal.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; - } - var _stream_writable = Writable$2; - // there will be only 2 of these for each stream + return name + ': ' + str; + } - function CorkedRequest$1(state) { - var _this = this; + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - this.next = null; - this.entry = null; + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - this.finish = function () { - onCorkedFinish(_this, state); - }; + 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()`. + function isArray$2(ar) { + return Array.isArray(ar); + } - var Duplex$4; - /**/ + function isBoolean$1(arg) { + return typeof arg === 'boolean'; + } - Writable$2.WritableState = WritableState$1; - /**/ + function isNull$1(arg) { + return arg === null; + } - var internalUtil = { - deprecate: browser$5 - }; - /**/ + function isNumber$1(arg) { + return typeof arg === 'number'; + } - /**/ + function isString$1(arg) { + return typeof arg === 'string'; + } - var Stream$2 = streamBrowser; - /**/ + function isUndefined$1(arg) { + return arg === void 0; + } + function isRegExp$1(re) { + return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; + } - var Buffer$j = buffer.Buffer; + function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; + } - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + function isDate$1(d) { + return isObject$1(d) && objectToString$1(d) === '[object Date]'; + } - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$j.from(chunk); + function isError$1(e) { + return isObject$1(e) && + (objectToString$1(e) === '[object Error]' || e instanceof Error); } - function _isUint8Array$1(obj) { - return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + function isFunction$1(arg) { + return typeof arg === 'function'; } - var destroyImpl$1 = destroy_1; + function objectToString$1(o) { + return Object.prototype.toString.call(o); + } - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$1(add)) return origin; - var _require$codes$3 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + 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 errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - inherits_browser.exports(Writable$2, Stream$2); + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - function nop$1() {} + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - function WritableState$1(options, stream, isDuplex) { - Duplex$4 = Duplex$4 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - this.needDrain = false; // at the start of calling end() + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; - this.ending = false; // when end() has been called, and returned + var string_decoder = {}; - this.ended = false; // when 'finish' is emitted + var StringDecoder_1; + // 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. - this.finished = false; // has it been destroyed + var Buffer$j = buffer.Buffer; - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + var isBufferEncoding = Buffer$j.isEncoding + || function(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; + } + }; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } - this.length = 0; // a flag to see when we're in the middle of a write. + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } - this.writing = false; // when true all writes will be buffered until .uncork() call + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$j(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$2.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } - this.onwrite = function (er) { - onwrite$1(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - this.writecb = null; // the amount that is being written when _write is called. + charStr += buffer.toString(this.encoding, 0, end); - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams + // or just emit the charStr + return charStr; + }; - this.prefinished = false; // True if the error was already emitted and should not be thrown again + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + // See http://en.wikipedia.org/wiki/UTF-8#Description - this.autoDestroy = !!options.autoDestroy; // count buffered requests + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - this.corkedRequestsFree = new CorkedRequest$1(this); - } + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; - WritableState$1.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + StringDecoder$2.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - while (current) { - out.push(current); - current = current.next; + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); } - return out; + return res; }; - (function () { - try { - Object.defineProperty(WritableState$1.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. - + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } - var realHasInstance; + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$2, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$2) return false; - return object && object._writableState instanceof WritableState$1; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } - function Writable$2(options) { - Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$4; - if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); - this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + Readable$2.ReadableState = ReadableState$1; - this.writable = true; + var debug$4 = debuglog('stream'); + inherits$i(Readable$2, EventEmitter$1); - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState$1(options, stream) { - Stream$2.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. - + options = options || {}; - Writable$2.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - function writeAfterEnd$1(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - function validChunk$1(stream, state, chunk, cb) { - var er; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - return true; - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - var isBuf = !state.objectMode && _isUint8Array$1(chunk); + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - if (isBuf && !Buffer$j.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; } + } + function Readable$2(options) { - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop$1; - if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; + if (!(this instanceof Readable$2)) return new Readable$2(options); - Writable$2.prototype.cork = function () { - this._writableState.corked++; - }; + this._readableState = new ReadableState$1(options, this); - Writable$2.prototype.uncork = function () { - var state = this._writableState; + // legacy + this.readable = true; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + if (options && typeof options.read === 'function') this._read = options.read; - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; + EventEmitter$1.call(this); + } - Object.defineProperty(Writable$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$2.prototype.push = function (chunk, encoding) { + var state = this._readableState; - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$j.from(chunk, encoding); + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$k.from(chunk, encoding); + encoding = ''; + } } - return chunk; - } + return readableAddChunk$1(this, state, chunk, encoding, false); + }; - Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. + // Unshift should *always* be something directly out of read() + Readable$2.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk$1(this, state, chunk, '', true); + }; - function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk$1(state, chunk, encoding); + Readable$2.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } + function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid$1(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + if (!addToFront) state.reading = false; - if (!ret) state.needDrain = true; + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + if (state.needReadable) emitReadable$1(stream); + } + } - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + maybeReadMore$1(stream, state); } - - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); + } else if (!addToFront) { + state.reading = false; } - return ret; + return needMoreData$1(state); } - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData$1(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error + // backwards compatibility. + Readable$2.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; + }; - nextTick(finishMaybe$1, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); + // Don't raise the hwm > 8MB + var MAX_HWM$1 = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM$1) { + n = MAX_HWM$1; } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe$1(stream, state); + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } + return n; } - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } - - if (sync) { - nextTick(afterWrite$1, stream, state, finished, cb); - } else { - afterWrite$1(stream, state, finished, cb); - } + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; } + return state.length; } - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. + // you can override either this method, or the async _read(n) below. + Readable$2.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; } - } // if there's something in the buffer waiting, then process it + n = howMuchToRead$1(n, state); - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); - buffer.allBuffers = allBuffers; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } - state.pendingcb++; - state.lastBufferedRequest = null; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest$1(state); - } + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - state.bufferedRequestCount = 0; + if (ret === null) { + state.needReadable = true; + n = 0; } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + state.length -= n; + } - if (state.writing) { - break; - } - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - if (entry === null) state.lastBufferedRequest = null; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable$1(this); } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + if (ret !== null) this.emit('data', ret); - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + return ret; }; - Writable$2.prototype._writev = null; - - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable$1(this, state, cb); - return this; - }; - - Object.defineProperty(Writable$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + function chunkInvalid$1(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - }); - - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + return er; } - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy$1(stream, err); + function onEofChunk$1(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } + } + state.ended = true; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe$1(stream, state); - }); + // emit 'readable' now to make sure it gets picked up. + emitReadable$1(stream); } - function prefinish$2(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable$1(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); } } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - - if (need) { - prefinish$2(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; + function emitReadable_$1(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow$1(stream); } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); } - - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; } - Object.defineProperty(Writable$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; + function maybeReadMore_$1(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } - }); - Writable$2.prototype.destroy = destroyImpl$1.destroy; - Writable$2.prototype._undestroy = destroyImpl$1.undestroy; + state.readingMore = false; + } - Writable$2.prototype._destroy = function (err, cb) { - cb(err); + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$2.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); }; - /**/ - - var objectKeys = Object.keys || function (obj) { - var keys = []; + Readable$2.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - for (var key in obj) { - keys.push(key); + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - return keys; - }; - /**/ + var doEnd = (!pipeOpts || pipeOpts.end !== false); + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - var _stream_duplex = Duplex$3; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } - var Readable$2 = _stream_readable; + function onend() { + debug$4('onend'); + dest.end(); + } - var Writable$1 = _stream_writable; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); - inherits_browser.exports(Duplex$3, Readable$2); + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - { - // Allow the keys array to be GC'ed. - var keys$1 = objectKeys(Writable$1.prototype); + cleanedUp = true; - for (var v$1 = 0; v$1 < keys$1.length; v$1++) { - var method$1 = keys$1[v$1]; - if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - } - - function Duplex$3(options) { - if (!(this instanceof Duplex$3)) return new Duplex$3(options); - Readable$2.call(this, options); - Writable$1.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend$1); + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); } } - } - Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); } - }); - Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - }); - Object.defineProperty(Duplex$3.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); } - }); // the no-half-open enforcer - - function onend$1() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + dest.once('finish', onfinish); - nextTick(onEndNT$1, this); - } + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - function onEndNT$1(self) { - self.end(); - } + // tell the dest that it's being piped to + dest.emit('pipe', src); - Object.defineProperty(Duplex$3.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + return dest; + }; + function pipeOnDrain$1(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow$1(src); + } + }; + } - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); + Readable$2.prototype.unpipe = function (dest) { + var state = this._readableState; - var string_decoder = {}; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - /**/ + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var Buffer$i = safeBuffer.exports.Buffer; - /**/ + if (!dest) dest = state.pipes; - var isEncoding = Buffer$i.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; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; } - }; - 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$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; - } + // slow case. multiple pipe destinations. - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. - var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(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$i.allocUnsafe(nb); - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - StringDecoder$2.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; + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; - }; - StringDecoder$2.prototype.end = utf8End; + // try to find the right one. + var i = indexOf$1(state.pipes, dest); + if (i === -1) return this; - // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.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; - }; + dest.emit('unpipe', this); - // 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; - } + return this; + }; - // 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; - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$2.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - // 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'; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable$1(this); } } } - } - - // 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); - 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); - } + return res; + }; + Readable$2.prototype.addListener = Readable$2.prototype.on; - // 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; + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); } - // 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; + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$2.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); - } + return this; + }; - // 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); + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); } - 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]; + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); } - 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; + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); } - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); - } + Readable$2.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; + function flow$1(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } - var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$2.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); } - callback.apply(this, args); - }; - } - - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } - - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; + self.push(null); + }); - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - var writableEnded = stream._writableState && stream._writableState.finished; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - var readableEnded = stream._readableState && stream._readableState.endEmitted; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$2(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - var onerror = function onerror(err) { - callback.call(stream, err); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } }; - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } + return self; + }; - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; + // exposed for testing purposes only. + Readable$2._fromList = fromList$1; - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + return ret; } - var endOfStream = eos$1; - - var _Object$setPrototypeO; - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var finished = endOfStream; - - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); - - function createIterResult(value, done) { - return { - value: value, - done: done - }; + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } + ++c; } + list.length -= c; + return ret; } - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } - - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$k.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); + break; } + ++c; + } + list.length -= c; + return ret; + } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; + function endReadable$1(stream) { + var state = stream._readableState; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } - promise = new Promise(this[kHandlePromise]); - } + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } - this[kLastPromise] = promise; - return promise; + function forEach$2(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; + } - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } + // A bit simpler than readable streams. + Writable$2.WritableState = WritableState$1; + inherits$i(Writable$2, events.exports.EventEmitter); - var resolve = iterator[kLastResolve]; + function nop() {} - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + function WriteReq$1(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } - iterator[kEnded] = true; + function WritableState$1(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; + options = options || {}; - var async_iterator = createReadableStreamAsyncIterator$1; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - var fromBrowser = function () { - throw new Error('Readable.from is not available in the browser') - }; + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; - var _stream_readable = Readable$1; - /**/ + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - var Duplex$2; - /**/ + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - Readable$1.ReadableState = ReadableState$1; - /**/ + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - events.exports.EventEmitter; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - /**/ + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + // a flag to see when we're in the middle of a write. + this.writing = false; - var Stream$1 = streamBrowser; - /**/ + // when true all writes will be buffered until .uncork() call + this.corked = 0; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var Buffer$h = buffer.Buffer; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite$1(stream, er); + }; - function _uint8ArrayToBuffer(chunk) { - return Buffer$h.from(chunk); - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - function _isUint8Array(obj) { - return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - var debugUtil = require$$3; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - var debug$5; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - if (debugUtil && debugUtil.debuglog) { - debug$5 = debugUtil.debuglog('stream'); - } else { - debug$5 = function debug() {}; - } - /**/ + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + // count buffered requests + this.bufferedRequestCount = 0; - var BufferList$1 = buffer_list; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - var destroyImpl = destroy_1; + WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable$2(options) { - var _require = state, - getHighWaterMark = _require.getHighWaterMark; + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); - var _require$codes$2 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + this._writableState = new WritableState$1(options, this); + // legacy. + this.writable = true; - var StringDecoder$1; - var createReadableStreamAsyncIterator; - var from; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - inherits_browser.exports(Readable$1, Stream$1); + if (typeof options.writev === 'function') this._writev = options.writev; + } - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + events.exports.EventEmitter.call(this); + } - function prependListener$1(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + // Otherwise people can pipe Writable streams, which is just wrong. + Writable$2.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + function writeAfterEnd$1(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); } - function ReadableState$1(options, stream, isDuplex) { - Duplex$2 = Duplex$2 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk$1(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - this.buffer = new BufferList$1(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + if (typeof cb !== 'function') cb = nop; - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, chunk, encoding, cb); + } - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + return ret; + }; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + Writable$2.prototype.cork = function () { + var state = this._writableState; - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + state.corked++; + }; - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + Writable$2.prototype.uncork = function () { + var state = this._writableState; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + if (state.corked) { + state.corked--; - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; - this.readingMore = false; - this.decoder = null; - this.encoding = null; + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); } + return chunk; } - function Readable$1(options) { - Duplex$2 = Duplex$2 || _stream_duplex; - if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer$1(stream, state, chunk, encoding, cb) { + chunk = decodeChunk$1(state, chunk, encoding); - var isDuplex = this instanceof Duplex$2; - this._readableState = new ReadableState$1(options, this, isDuplex); // legacy + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - this.readable = true; + state.length += len; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); } - Stream$1.call(this); + return ret; } - Object.defineProperty(Readable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - this._readableState.destroyed = value; - } - }); - Readable$1.prototype.destroy = destroyImpl.destroy; - Readable$1.prototype._undestroy = destroyImpl.undestroy; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - Readable$1.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + onwriteStateUpdate$1(state); - Readable$1.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state); - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - if (encoding !== state.encoding) { - chunk = Buffer$h.from(chunk, encoding); - encoding = ''; + if (sync) { + /**/ + nextTick(afterWrite$1, stream, state, finished, cb); + /**/ + } else { + afterWrite$1(stream, state, finished, cb); } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; } + } - return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } - Readable$1.prototype.unshift = function (chunk) { - return readableAddChunk$1(this, chunk, null, true, false); - }; + // if there's something in the buffer waiting, then process it + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$5('readableAddChunk', chunk); - var state = stream._readableState; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); - } else { - addChunk(stream, state, chunk, false); - } + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; } - } else if (!addToFront) { - state.reading = false; - maybeReadMore$1(stream, state); } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable$1(stream); + if (entry === null) state.lastBufferedRequest = null; } - maybeReadMore$1(stream, state); + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; } - function chunkInvalid$1(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - return er; - } + Writable$2.prototype._writev = null; - Readable$1.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - while (p !== null) { - content += decoder.write(p.data); - p = p.next; + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable$1(this, state, cb); + }; + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } - var MAX_HWM$1 = 0x40000000; + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } - function computeNewHighWaterMark$1(n) { - if (n >= MAX_HWM$1) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM$1; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } } + return need; + } - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + this.next = null; + this.entry = null; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + inherits$i(Duplex$2, Readable$2); - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); - if (n <= state.length) return n; // Don't have enough + var keys = Object.keys(Writable$2.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; + } + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); - if (!state.ended) { - state.needReadable = true; - return 0; - } + Readable$2.call(this, options); + Writable$2.call(this, options); - return state.length; - } // you can override either this method, or the async _read(n) below. + if (options && options.readable === false) this.readable = false; + if (options && options.writable === false) this.writable = false; - Readable$1.prototype.read = function (n) { - debug$5('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$5('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; - } + this.once('end', onend$1); + } - n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. + // the no-half-open enforcer + function onend$1() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + function onEndNT(self) { + self.end(); + } - var doRead = state.needReadable; - debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + // a transform stream is a readable/writable stream where you do + inherits$i(Transform$4, Duplex$2); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$5('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + function TransformState$1(stream) { + this.afterTransform = function (er, data) { + return afterTransform$1(stream, er, data); + }; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } - if (state.ended || state.reading) { - doRead = false; - debug$5('reading or ended', doRead); - } else if (doRead) { - debug$5('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + function afterTransform$1(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - if (state.length === 0) state.needReadable = true; // call internal read method + var cb = ts.writecb; - this._read(state.highWaterMark); + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + ts.writechunk = null; + ts.writecb = null; - if (!state.reading) n = howMuchToRead$1(nOrig, state); - } + if (data !== null && data !== undefined) stream.push(data); - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + cb(er); - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } + } + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + Duplex$2.call(this, options); - if (nOrig !== n && state.ended) endReadable$1(this); - } + this._transformState = new TransformState$1(this); - if (ret !== null) this.emit('data', ret); - return ret; - }; + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function onEofChunk$1(stream, state) { - debug$5('onEofChunk'); - if (state.ended) return; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - if (state.decoder) { - var chunk = state.decoder.end(); + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; } - state.ended = true; + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done$1(stream, er); + });else done$1(stream); + }); + } - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable$1(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$2.prototype.push.call(this, chunk, encoding); + }; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_$1(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$4.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - function emitReadable$1(stream) { - var state = stream._readableState; - debug$5('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - if (!state.emittedReadable) { - debug$5('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_$1, stream); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - } - - function emitReadable_$1(stream) { - var state = stream._readableState; - debug$5('emitReadable_', state.destroyed, state.length, state.ended); + }; - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + function done$1(stream, er) { + if (er) return stream.emit('error', er); + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow$1(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); - } + return stream.push(null); } - function maybeReadMore_$1(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug$5('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. + inherits$i(PassThrough$1, Transform$4); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform$4.call(this, options); + } - Readable$1.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; - Readable$1.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + inherits$i(Stream$2, EventEmitter$1); + Stream$2.Readable = Readable$2; + Stream$2.Writable = Writable$2; + Stream$2.Duplex = Duplex$2; + Stream$2.Transform = Transform$4; + Stream$2.PassThrough = PassThrough$1; - case 1: - state.pipes = [state.pipes, dest]; - break; + // Backwards-compat with node 0.4.x + Stream$2.Stream = Stream$2; - default: - state.pipes.push(dest); - break; - } + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - state.pipesCount += 1; - debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); + function Stream$2() { + EventEmitter$1.call(this); + } - function onunpipe(readable, unpipeInfo) { - debug$5('onunpipe'); + Stream$2.prototype.pipe = function(dest, options) { + var source = this; - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); } } } - function onend() { - debug$5('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. + source.on('data', ondata); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - var ondrain = pipeOnDrain$1(src); dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug$5('cleanup'); // cleanup event handlers once the pipe is broken + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + dest.end(); } - src.on('data', ondata); - function ondata(chunk) { - debug$5('ondata'); - var ret = dest.write(chunk); - debug$5('dest.write', ret); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$5('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + if (typeof dest.destroy === 'function') dest.destroy(); + } - src.pause(); + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - + } - function onerror(er) { - debug$5('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + source.on('error', onerror); + dest.on('error', onerror); + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + source.removeListener('end', onend); + source.removeListener('close', onclose); - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - dest.once('close', onclose); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - function onfinish() { - debug$5('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + dest.removeListener('close', cleanup); } - dest.once('finish', onfinish); - - function unpipe() { - debug$5('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - + source.on('end', cleanup); + source.on('close', cleanup); - dest.emit('pipe', src); // start the flow if it hasn't been started already. + dest.on('close', cleanup); - if (!state.flowing) { - debug$5('pipe resume'); - src.resume(); - } + dest.emit('pipe', source); + // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; - function pipeOnDrain$1(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug$5('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream$2, + Readable: Readable$2, + Writable: Writable$2, + Duplex: Duplex$2, + Transform: Transform$4, + PassThrough: PassThrough$1, + Stream: Stream$2 + }); - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow$1(src); - } - }; - } + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); - Readable$1.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + var isarray = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; + }; - if (state.pipesCount === 0) return this; // just one destination. most common case. + var util$5 = {}; - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + // 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. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$1(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; + } + util$5.isArray = isArray$1; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + util$5.isBoolean = isBoolean; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + function isNull(arg) { + return arg === null; + } + util$5.isNull = isNull; - return this; - } // try to find the right one. + function isNullOrUndefined(arg) { + return arg == null; + } + util$5.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === 'number'; + } + util$5.isNumber = isNumber; - var index = indexOf$1(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something + function isString(arg) { + return typeof arg === 'string'; + } + util$5.isString = isString; + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + util$5.isSymbol = isSymbol; - Readable$1.prototype.on = function (ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); - var state = this._readableState; + function isUndefined(arg) { + return arg === void 0; + } + util$5.isUndefined = isUndefined; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + util$5.isRegExp = isRegExp; - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug$5('on readable', state.length, state.reading); + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + util$5.isObject = isObject; - if (state.length) { - emitReadable$1(this); - } else if (!state.reading) { - nextTick(nReadingNextTick$1, this); - } - } - } - - return res; - }; - - Readable$1.prototype.addListener = Readable$1.prototype.on; - - Readable$1.prototype.removeListener = function (ev, fn) { - var res = Stream$1.prototype.removeListener.call(this, ev, fn); + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + util$5.isDate = isDate; - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + util$5.isError = isError; - return res; - }; + function isFunction(arg) { + return typeof arg === 'function'; + } + util$5.isFunction = isFunction; - Readable$1.prototype.removeAllListeners = function (ev) { - var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + util$5.isPrimitive = isPrimitive; - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + util$5.isBuffer = buffer.Buffer.isBuffer; - return res; - }; + function objectToString(o) { + return Object.prototype.toString.call(o); + } - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + // 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. - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } - } + var _stream_readable = Readable$1; - function nReadingNextTick$1(self) { - debug$5('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + /**/ + var isArray = isarray; + /**/ - Readable$1.prototype.resume = function () { - var state = this._readableState; + /**/ + var Buffer$i = buffer.Buffer; + /**/ - if (!state.flowing) { - debug$5('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + Readable$1.ReadableState = ReadableState; - state.flowing = !state.readableListening; - resume$1(this, state); - } + var EE = events.exports.EventEmitter; - state.paused = false; - return this; + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; }; + /**/ - function resume$1(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_$1, stream, state); - } - } + var Stream$1 = require$$1; - function resume_$1(stream, state) { - debug$5('resume', state.reading); + /**/ + var util$4 = util$5; + util$4.inherits = inherits_browser.exports; + /**/ - if (!state.reading) { - stream.read(0); - } + var StringDecoder$1; - state.resumeScheduled = false; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); - } + util$4.inherits(Readable$1, Stream$1); - Readable$1.prototype.pause = function () { - debug$5('call pause flowing=%j', this._readableState.flowing); + function ReadableState(options, stream) { + options = options || {}; - if (this._readableState.flowing !== false) { - debug$5('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - this._readableState.paused = true; - return this; - }; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - function flow$1(stream) { - var state = stream._readableState; - debug$5('flow', state.flowing); + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - Readable$1.prototype.wrap = function (stream) { - var _this = this; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug$5('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - _this.push(null); - }); - stream.on('data', function (chunk) { - debug$5('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - var ret = _this.push(chunk); + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } + } + function Readable$1(options) { + if (!(this instanceof Readable$1)) + return new Readable$1(options); - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + this._readableState = new ReadableState(options, this); + // legacy + this.readable = true; - this._read = function (n) { - debug$5('wrapped _read', n); + Stream$1.call(this); + } - if (paused) { - paused = false; - stream.resume(); + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$1.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer$i(chunk, encoding); + encoding = ''; } - }; + } - return this; + return readableAddChunk(this, state, chunk, encoding, false); }; - if (typeof Symbol === 'function') { - Readable$1.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } + // Unshift should *always* be something directly out of read() + Readable$1.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; - return createReadableStreamAsyncIterator(this); - }; - } + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); - Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); // exposed for testing purposes only. + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } - Readable$1._fromList = fromList$1; - Object.defineProperty(Readable$1.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. + if (state.needReadable) + emitReadable(stream); - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; } - return ret; - } - - function endReadable$1(stream) { - var state = stream._readableState; - debug$5('endReadable', state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT$1, state, stream); - } + return needMoreData(state); } - function endReadableNT$1(state, stream) { - debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); } - if (typeof Symbol === 'function') { - Readable$1.from = function (iterable, opts) { - if (from === undefined) { - from = fromBrowser; - } - - return from(Readable$1, iterable, opts); - }; - } + // backwards compatibility. + Readable$1.prototype.setEncoding = function(enc) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this._readableState.decoder = new StringDecoder$1(enc); + this._readableState.encoding = enc; + }; - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + // Don't raise the hwm > 128MB + var MAX_HWM = 0x800000; + function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; } - - return -1; + return n; } - var _stream_transform = Transform$4; + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; - var _require$codes$1 = errorsBrowser.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + if (state.objectMode) + return n === 0 ? 0 : 1; - var Duplex$1 = _stream_duplex; + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } - inherits_browser.exports(Transform$4, Duplex$1); + if (n <= 0) + return 0; - function afterTransform$1(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } + return n; } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); - Duplex$1.call(this, options); - this._transformState = { - afterTransform: afterTransform$1.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + // you can override either this method, or the async _read(n) below. + Readable$1.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; - this._readableState.sync = false; + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + n = howMuchToRead(n, state); - this.on('prefinish', prefinish$1); - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } - function prefinish$1() { - var _this = this; + if (state.length === 0) + endReadable(this); - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done$1(_this, er, data); - }); - } else { - done$1(this, null, null); + return ret; } - } - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$1.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - Transform$4.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); - }; + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; + if (n > 0) + ret = fromList(n, state); + else + ret = null; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + if (ret === null) { + state.needReadable = true; + n = 0; } - }; - - Transform$4.prototype._destroy = function (err, cb) { - Duplex$1.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; - function done$1(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } + state.length -= n; - var _stream_passthrough = PassThrough$1; + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; - var Transform$3 = _stream_transform; + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); - inherits_browser.exports(PassThrough$1, Transform$3); + return ret; + }; - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$3.call(this, options); + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer$i.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - var eos; + function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); } - var _require$codes = errorsBrowser.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; + state.emittedReadable = true; + if (state.sync) + nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; + function emitReadable_(stream) { + stream.emit('readable'); } - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(function() { + maybeReadMore_(stream, state); + }); + } } - function call(fn) { - fn(); + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; } - function pipe(from, to) { - return from.pipe(to); - } + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$1.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); + }; - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); - } + Readable$1.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } + state.pipesCount += 1; - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + nextTick(endFn); + else + src.once('end', endFn); - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } - var pipeline_1 = pipeline; + function onend() { + dest.end(); + } - (function (module, exports) { - exports = module.exports = _stream_readable; - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - }(readableBrowser, readableBrowser.exports)); + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - var Buffer$g = safeBuffer.exports.Buffer; - var Transform$2 = readableBrowser.exports.Transform; - var inherits$i = inherits_browser.exports; + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); } - } - - function HashBase$2 (blockSize) { - Transform$2.call(this); - this._block = Buffer$g.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; - this._finalized = false; - } - inherits$i(HashBase$2, Transform$2); - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - - callback(error); - }; - - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); } + dest.once('finish', onfinish); - callback(error); - }; + function unpipe() { + src.unpipe(dest); + } - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + // tell the dest that it's being piped to + dest.emit('pipe', src); - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; + state.flowing = true; + nextTick(function() { + flow(src); + }); } - return this + return dest; }; - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; + } - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + while (state.pipesCount && null !== (chunk = src.read())) { - return digest - }; + if (state.pipesCount === 1) + write(state.pipes); + else + forEach$1(state.pipes, write); - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + src.emit('data', chunk); - var hashBase = HashBase$2; + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } - var inherits$h = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; - var ARRAY16$1 = new Array(16); + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } - function MD5$2 () { - HashBase$1.call(this, 64); + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; + } - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; + function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } } - inherits$h(MD5$2, HashBase$1); - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + Readable$1.prototype.unpipe = function(dest) { + var state = this._readableState; - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + if (!dest) + dest = state.pipes; - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + // slow case. multiple pipe destinations. - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; - // produce result - var buffer = Buffer$f.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } + dest.emit('unpipe', this); - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } + return this; + }; - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$1.prototype.on = function(ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this); + } + } + } - var md5_js = MD5$2; + return res; + }; + Readable$1.prototype.addListener = Readable$1.prototype.on; - var Buffer$e = buffer.Buffer; - var inherits$g = inherits_browser.exports; - var HashBase = hashBase; + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$1.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); + }; - var ARRAY16 = new Array(16); + Readable$1.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); + }; - var zl = [ - 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 - ]; + function emitDataEvents(stream, startPaused) { + var state = stream._readableState; - var zr = [ - 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 - ]; + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } - var sl = [ - 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 paused = startPaused || false; + var readable = false; - var sr = [ - 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 - ]; + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream$1.prototype.pipe; + stream.on = stream.addListener = Stream$1.prototype.on; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + stream.on('readable', function() { + readable = true; - function RIPEMD160$3 () { - HashBase.call(this, 64); + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); - inherits$g(RIPEMD160$3, HashBase); + stream.pause = function() { + paused = true; + this.emit('pause'); + }; - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + stream.resume = function() { + paused = false; + if (readable) + nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + // now make it start, just in case it hadn't already. + stream.emit('readable'); + } - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$1.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); } - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; + self.push(null); + }); - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; - } + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$1(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer - }; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } + return self; + }; - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } + // exposed for testing purposes only. + Readable$1._fromList = fromList; - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } + // nothing in the list, definitely empty. + if (list.length === 0) + return null; - var ripemd160$2 = RIPEMD160$3; + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer$i.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer$i(n); - var sha_js = {exports: {}}; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); - var Buffer$d = safeBuffer.exports.Buffer; + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); + c += cpy; + } + } } - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; + return ret; + } - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + function endReadable(stream) { + var state = stream._readableState; - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); - accum += remainder; - offset += remainder; + if (!state.endEmitted && state.calledRead) { + state.ended = true; + nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } + } - if ((accum % blockSize) === 0) { - this._update(block); - } + function forEach$1 (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } + } - this._len += length; - return this - }; + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + // 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. - this._block[rem] = 0x80; + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + var _stream_duplex = Duplex$1; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; + /**/ - var bits = this._len * 8; - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + /**/ + var util$3 = util$5; + util$3.inherits = inherits_browser.exports; + /**/ - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + var Readable = _stream_readable; + var Writable$1 = _stream_writable; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + util$3.inherits(Duplex$1, Readable); - this._update(this._block); - var hash = this._hash(); + forEach(objectKeys(Writable$1.prototype), function(method) { + if (!Duplex$1.prototype[method]) + Duplex$1.prototype[method] = Writable$1.prototype[method]; + }); - return enc ? hash.toString(enc) : hash - }; + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) + return new Duplex$1(options); - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + Readable.call(this, options); + Writable$1.call(this, options); - var hash$3 = Hash$7; + if (options && options.readable === false) + this.readable = false; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + if (options && options.writable === false) + this.writable = false; - var inherits$f = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + this.once('end', onend); + } - var W$5 = new Array(80); + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; - function Sha () { - this.init(); - this._w = W$5; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(this.end.bind(this)); + } - Hash$6.call(this, 64, 56); + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } - inherits$f(Sha, Hash$6); + // 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. - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. - return this - }; + var _stream_writable = Writable; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + /**/ + var Buffer$h = buffer.Buffer; + /**/ - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } + Writable.WritableState = WritableState; - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } - Sha.prototype._update = function (M) { - var W = this._w; + /**/ + var util$2 = util$5; + util$2.inherits = inherits_browser.exports; + /**/ - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + var Stream = require$$1; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + util$2.inherits(Writable, Stream); - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } + function WritableState(options, stream) { + options = options || {}; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - return H - }; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - var sha$4 = Sha; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var inherits$e = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // a flag to see when we're in the middle of a write. + this.writing = false; - var W$4 = new Array(80); + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - function Sha1 () { - this.init(); - this._w = W$4; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - Hash$5.call(this, 64, 56); - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; - inherits$e(Sha1, Hash$5); + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + // the amount that is being written when _write is called. + this.writelen = 0; - return this - }; + this.buffer = []; - function rotl1 (num) { - return (num << 1) | (num >>> 31) + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; } - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } + function Writable(options) { + var Duplex = _stream_duplex; - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + this._writableState = new WritableState(options, this); - Sha1.prototype._update = function (M) { - var W = this._w; + // legacy. + this.writable = true; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + Stream.call(this); + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); + }; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer$h.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + valid = false; } + return valid; + } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; - return H - }; + if (typeof cb !== 'function') + cb = function() {}; - var sha1$1 = Sha1; + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + return ret; + }; - var inherits$d = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer$h(chunk, encoding); + } + return chunk; + } - var K$2 = [ - 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 - ]; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - var W$3 = new Array(64); + state.length += len; - function Sha256$1 () { - this.init(); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; - this._w = W$3; // new Array(64) + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - Hash$4.call(this, 64, 56); + return ret; } - inherits$d(Sha256$1, Hash$4); - - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - return this - }; + function onwriteError(stream, state, sync, er, cb) { + if (sync) + nextTick(function() { + cb(er); + }); + else + cb(er); - function ch (x, y, z) { - return z ^ (x & (y ^ z)) + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } } - Sha256$1.prototype._update = function (M) { - var W = this._w; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + doWrite(stream, state, len, chunk, encoding, cb); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; + } - return H + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); }; - var sha256$2 = Sha256$1; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - var inherits$c = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); - var W$2 = new Array(64); + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; - function Sha224 () { - this.init(); - this._w = W$2; // new Array(64) + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); + } - Hash$3.call(this, 64, 56); + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; } - inherits$c(Sha224, Sha256); + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; + } - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; - - return this - }; + // 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. - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. - return H - }; + var _stream_transform = Transform$3; - var sha224 = Sha224; + var Duplex = _stream_duplex; - var inherits$b = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + /**/ + var util$1 = util$5; + util$1.inherits = inherits_browser.exports; + /**/ - var K$1 = [ - 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 - ]; + util$1.inherits(Transform$3, Duplex); - var W$1 = new Array(160); - function Sha512 () { - this.init(); - this._w = W$1; + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - Hash$2.call(this, 128, 112); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; } - inherits$b(Sha512, Hash$2); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + var cb = ts.writecb; - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); - return this - }; + ts.writechunk = null; + ts.writecb = null; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + if (data !== null && data !== undefined) + stream.push(data); - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + if (cb) + cb(er); - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + function Transform$3(options) { + if (!(this instanceof Transform$3)) + return new Transform$3(options); - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + Duplex.call(this, options); - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + this._transformState = new TransformState(options, this); - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } - Sha512.prototype._update = function (M) { - var W = this._w; + Transform$3.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$3.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); + }; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + Transform$3.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } + }; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$3.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + }; - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + function done(stream, er) { + if (er) + return stream.emit('error', er); - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + stream._readableState; + var ts = stream._transformState; - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); - W[i] = Wih; - W[i + 1] = Wil; - } + if (ts.transforming) + throw new Error('calling transform done when still transforming'); - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + return stream.push(null); + } - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + // 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 sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + var _stream_passthrough = PassThrough; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + var Transform$2 = _stream_transform; - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + /**/ + var util = util$5; + util.inherits = inherits_browser.exports; + /**/ - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + util.inherits(PassThrough, Transform$2); - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + Transform$2.call(this, options); + } - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + (function (module, exports) { + var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify + exports = module.exports = _stream_readable; + exports.Stream = Stream; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + }(readable, readable.exports)); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$g = inherits_browser.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } + } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); + function HashBase$2 (blockSize) { + Transform$1.call(this); - return H - }; + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - var sha512 = Sha512; + this._finalized = false; + } - var inherits$a = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; + inherits$g(HashBase$2, Transform$1); - var W = new Array(160); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } - function Sha384 () { - this.init(); - this._w = W; + callback(error); + }; - Hash$1.call(this, 128, 112); - } + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - inherits$a(Sha384, SHA512$2); + callback(error); + }; - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } return this }; - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - return H - }; + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - var sha384 = Sha384; + return digest + }; - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + var hashBase = HashBase$2; - return new Algorithm() - }; + var inherits$f = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + var ARRAY16$1 = new Array(16); - var sha$3 = sha_js.exports; + function MD5$2 () { + HashBase$1.call(this, 64); - var inherits$8; - if (typeof Object.create === 'function'){ - inherits$8 = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$8 = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; } - var inherits$9 = inherits$8; - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + inherits$f(MD5$2, HashBase$1); - 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - } - - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, 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 - _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); - } - - // 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 !== 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 length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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()`. - function isArray(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - - function isNull(arg) { - return arg === null; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isString(arg) { - return typeof arg === 'string'; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - function _extend(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); - } - - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - Readable.ReadableState = ReadableState; - - var debug$4 = debuglog('stream'); - inherits$9(Readable, EventEmitter$1); - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState(options, stream) { - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options && typeof options.read === 'function') this._read = options.read; - - EventEmitter$1.call(this); - } - - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$l.from(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); - }; - - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; - - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } - - if (!addToFront) state.reading = false; - - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); - } - - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } - - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; - }; - - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } - - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; - } - - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$4('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - if (ret !== null) this.emit('data', ret); + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - return ret; + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; }; - function chunkInvalid(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - return er; - } - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); - } + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) } - function emitReadable_(stream) { - debug$4('emit readable'); - stream.emit('readable'); - flow(stream); + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 } - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false); - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$4('onunpipe'); - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug$4('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug$4('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - - cleanedUp = true; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + var md5_js = MD5$2; - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$4('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + var Buffer$e = buffer.Buffer; + var inherits$e = inherits_browser.exports; + var HashBase = hashBase; - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } + var ARRAY16 = new Array(16); - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + var zl = [ + 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 + ]; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + var zr = [ + 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 + ]; - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); - } + var sl = [ + 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 + ]; - // tell the dest that it's being piped to - dest.emit('pipe', src); + var sr = [ + 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 + ]; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); - } + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - return dest; - }; + function RIPEMD160$3 () { + HashBase.call(this, 64); - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; } - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + inherits$e(RIPEMD160$3, HashBase); - dest.emit('unpipe', this); + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - return this; - }; + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); } - } - - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); - } - - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$4('resume'); - state.flowing = true; - resume(this, state); - } - return this; - }; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } - } + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - function resume_(stream, state) { - if (!state.reading) { - debug$4('resume read 0'); - stream.read(0); + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; }; - function flow(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} - } - - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$4('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - return self; + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer }; - // exposed for testing purposes only. - Readable._fromList = fromList; - - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - return ret; + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$l.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - function endReadable(stream) { - var state = stream._readableState; + var ripemd160$2 = RIPEMD160$3; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + var sha_js = {exports: {}}; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } + var Buffer$d = safeBuffer.exports.Buffer; - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; } - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); } - } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + + accum += remainder; + offset += remainder; + + if ((accum % blockSize) === 0) { + this._update(block); + } } - return -1; - } - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$9(Writable, events.exports.EventEmitter); + this._len += length; + return this + }; - function nop() {} + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + this._block[rem] = 0x80; - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + var bits = this._len * 8; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + this._update(this._block); + var hash = this._hash(); - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + return enc ? hash.toString(enc) : hash + }; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - // a flag to see when we're in the middle of a write. - this.writing = false; + var hash$3 = Hash$7; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var inherits$d = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + var W$5 = new Array(80); - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + function Sha () { + this.init(); + this._w = W$5; - // the amount that is being written when _write is called. - this.writelen = 0; + Hash$6.call(this, 64, 56); + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + inherits$d(Sha, Hash$6); - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + return this + }; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } - // count buffered requests - this.bufferedRequestCount = 0; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + Sha.prototype._update = function (M) { + var W = this._w; + + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; } - return out; + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - this._writableState = new WritableState(options, this); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - // legacy. - this.writable = true; + return H + }; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + var sha$4 = Sha; - if (typeof options.writev === 'function') this._writev = options.writev; - } + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - events.exports.EventEmitter.call(this); - } + var inherits$c = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } + var W$4 = new Array(80); - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); } - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + inherits$c(Sha1, Hash$5); - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + return this + }; - if (typeof cb !== 'function') cb = nop; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - return ret; - }; + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - Writable.prototype.cork = function () { - var state = this._writableState; + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - state.corked++; - }; + Sha1.prototype._update = function (M) { + var W = this._w; - Writable.prototype.uncork = function () { - var state = this._writableState; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - if (state.corked) { - state.corked--; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; } - }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); - } - return chunk; - } + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + return H + }; - state.length += len; + var sha1$1 = Sha1; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + var inherits$b = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - return ret; - } + var K$2 = [ + 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 doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + var W$3 = new Array(64); - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + function Sha256$1 () { + this.init(); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + this._w = W$3; // new Array(64) - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + Hash$4.call(this, 64, 56); } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + inherits$b(Sha256$1, Hash$4); - onwriteStateUpdate(state); + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + return this + }; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) } - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + Sha256$1.prototype._update = function (M) { + var W = this._w; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - if (entry === null) state.lastBufferedRequest = null; + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; }; - Writable.prototype._writev = null; - - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); + return H }; - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + var sha256$2 = Sha256$1; - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; - } + var inherits$a = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; - } + var W$2 = new Array(64); - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + function Sha224 () { + this.init(); - this.next = null; - this.entry = null; + this._w = W$2; // new Array(64) - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; + Hash$3.call(this, 64, 56); } - inherits$9(Duplex, Readable); - - var keys = Object.keys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + inherits$a(Sha224, Sha256); - Readable.call(this, options); - Writable.call(this, options); + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - if (options && options.readable === false) this.readable = false; + return this + }; - if (options && options.writable === false) this.writable = false; + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); - this.once('end', onend); - } + return H + }; - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + var sha224 = Sha224; - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } + var inherits$9 = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - function onEndNT(self) { - self.end(); - } + var K$1 = [ + 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 + ]; - // a transform stream is a readable/writable stream where you do - inherits$9(Transform$1, Duplex); + var W$1 = new Array(160); - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; + function Sha512 () { + this.init(); + this._w = W$1; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; + Hash$2.call(this, 128, 112); } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + inherits$9(Sha512, Hash$2); - ts.writechunk = null; - ts.writecb = null; + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; - if (data !== null && data !== undefined) stream.push(data); + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; - cb(er); + return this + }; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } - function Transform$1(options) { - if (!(this instanceof Transform$1)) return new Transform$1(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - if (typeof options.flush === 'function') this._flush = options.flush; - } + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) } - Transform$1.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$1.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - Transform$1.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$1.prototype._read = function (n) { - var ts = this._transformState; + Sha512.prototype._update = function (M) { + var W = this._w; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - function done(stream, er) { - if (er) return stream.emit('error', er); + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - return stream.push(null); - } + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - inherits$9(PassThrough, Transform$1); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - Transform$1.call(this, options); - } + W[i] = Wih; + W[i + 1] = Wil; + } - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - inherits$9(Stream, EventEmitter$1); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform$1; - Stream.PassThrough = PassThrough; + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - function Stream() { - EventEmitter$1.call(this); - } + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - Stream.prototype.pipe = function(dest, options) { - var source = this; + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; } - source.on('data', ondata); + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; - dest.on('drain', ondrain); + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - dest.end(); - } + return H + }; + var sha512 = Sha512; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + var inherits$8 = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - if (typeof dest.destroy === 'function') dest.destroy(); - } + var W = new Array(160); - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } + function Sha384 () { + this.init(); + this._w = W; - source.on('error', onerror); - dest.on('error', onerror); + Hash$1.call(this, 128, 112); + } - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + inherits$8(Sha384, SHA512$2); - source.removeListener('end', onend); - source.removeListener('close', onclose); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + return this + }; - dest.removeListener('close', cleanup); + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - source.on('end', cleanup); - source.on('close', cleanup); + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); - dest.on('close', cleanup); + return H + }; - dest.emit('pipe', source); + var sha384 = Sha384; - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() }; - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream, - Readable: Readable, - Writable: Writable, - Duplex: Duplex, - Transform: Transform$1, - PassThrough: PassThrough, - Stream: Stream - }); + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + var sha$3 = sha_js.exports; var Buffer$6 = safeBuffer.exports.Buffer; var Transform = require$$1.Transform; @@ -12738,7 +11532,7 @@ window.Buffer = buffer.Buffer; var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$l.alloc(1 + paths.length * 4); + var buffer = Buffer$k.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -24451,16 +23245,16 @@ window.Buffer = buffer.Buffer; const createHmac = browser$2; - const ONE1 = Buffer$l.alloc(1, 1); - const ZERO1 = Buffer$l.alloc(1, 0); + const ONE1 = Buffer$k.alloc(1, 1); + const ZERO1 = Buffer$k.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$l.alloc(32, 0); - let v = Buffer$l.alloc(32, 1); + let k = Buffer$k.alloc(32, 0); + let v = Buffer$k.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -24517,9 +23311,9 @@ window.Buffer = buffer.Buffer; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$l.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$k.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -24591,9 +23385,9 @@ window.Buffer = buffer.Buffer; } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -24725,7 +23519,7 @@ window.Buffer = buffer.Buffer; s = n.sub(s); } - const buffer = Buffer$l.allocUnsafe(64); + const buffer = Buffer$k.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -25310,7 +24104,7 @@ window.Buffer = buffer.Buffer; } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$l(compressed ? 34 : 33); + var result = new Buffer$k(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -25429,7 +24223,7 @@ window.Buffer = buffer.Buffer; const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$l.allocUnsafe(78); + const buffer = Buffer$k.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -25463,7 +24257,7 @@ window.Buffer = buffer.Buffer; derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$l.allocUnsafe(37); + const data = Buffer$k.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -25543,7 +24337,7 @@ window.Buffer = buffer.Buffer; } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$k.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -25635,7 +24429,7 @@ window.Buffer = buffer.Buffer; if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -25742,7 +24536,7 @@ window.Buffer = buffer.Buffer; function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$l.allocUnsafe(size); + const buffer = Buffer$k.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -25937,18 +24731,18 @@ window.Buffer = buffer.Buffer; const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$l.alloc(1, 0); + const ZERO$1 = Buffer$k.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$l.alloc(32, 0); + const buffer = Buffer$k.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -25962,7 +24756,7 @@ window.Buffer = buffer.Buffer; const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$l.concat([r, s], 64); + const signature = Buffer$k.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -25977,11 +24771,11 @@ window.Buffer = buffer.Buffer; const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$l.allocUnsafe(1); + const hashTypeBuffer = Buffer$k.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -26370,7 +25164,7 @@ window.Buffer = buffer.Buffer; // opcode return accum + 1; }, 0.0); - const buffer = Buffer$l.allocUnsafe(bufferSize); + const buffer = Buffer$k.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -26455,7 +25249,7 @@ window.Buffer = buffer.Buffer; if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$l.from(chunkStr, 'hex'); + return Buffer$k.from(chunkStr, 'hex'); }), ); } @@ -26465,7 +25259,7 @@ window.Buffer = buffer.Buffer; typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -26873,7 +25667,7 @@ window.Buffer = buffer.Buffer; const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$k.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -26912,7 +25706,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$k.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27031,7 +25825,7 @@ window.Buffer = buffer.Buffer; // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$k.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -27067,7 +25861,7 @@ window.Buffer = buffer.Buffer; return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$k.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27343,7 +26137,7 @@ window.Buffer = buffer.Buffer; const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$l.alloc(0); + const EMPTY_BUFFER$1 = Buffer$k.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -27371,7 +26165,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$k.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -27411,7 +26205,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$k.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27475,7 +26269,7 @@ window.Buffer = buffer.Buffer; const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$l.alloc(0); + const EMPTY_BUFFER = Buffer$k.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -27525,7 +26319,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$k.from(data), }; }); const _rchunks = lazy.value(() => { @@ -27590,7 +26384,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$k.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27713,13 +26507,13 @@ window.Buffer = buffer.Buffer; return { version: result.words[0], prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$k.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$k.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -27875,7 +26669,7 @@ window.Buffer = buffer.Buffer; return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$k.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -28077,7 +26871,7 @@ window.Buffer = buffer.Buffer; } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$l.allocUnsafe(buffer.length); + const clone = Buffer$k.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -28200,17 +26994,17 @@ window.Buffer = buffer.Buffer; }, 0) ); } - const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$l.from( + const ZERO = Buffer$k.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$l.from( + const ONE = Buffer$k.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -28272,7 +27066,7 @@ window.Buffer = buffer.Buffer; return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -28432,7 +27226,7 @@ window.Buffer = buffer.Buffer; txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -28442,13 +27236,13 @@ window.Buffer = buffer.Buffer; types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$l.from([]); + let tbuffer = Buffer$k.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -28461,7 +27255,7 @@ window.Buffer = buffer.Buffer; (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -28475,7 +27269,7 @@ window.Buffer = buffer.Buffer; const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$l.allocUnsafe(txOutsSize); + tbuffer = Buffer$k.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -28487,13 +27281,13 @@ window.Buffer = buffer.Buffer; inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -28511,7 +27305,7 @@ window.Buffer = buffer.Buffer; } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -28533,7 +27327,7 @@ window.Buffer = buffer.Buffer; this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -28595,7 +27389,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$l.concat([left, right]); + var data = Buffer$k.concat([left, right]); results[j] = digestFn(data); } @@ -28662,12 +27456,12 @@ window.Buffer = buffer.Buffer; return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$l.from(hex, 'hex')); + return Block.fromBuffer(Buffer$k.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$l.alloc(32, 0); + const target = Buffer$k.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -28682,7 +27476,7 @@ window.Buffer = buffer.Buffer; const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -28694,18 +27488,18 @@ window.Buffer = buffer.Buffer; // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$l && result.length === 32)) return null; + if (!(result instanceof Buffer$k && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$l && + this.witnessCommit instanceof Buffer$k && this.witnessCommit.length === 32 ) return true; @@ -28741,7 +27535,7 @@ window.Buffer = buffer.Buffer; } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -28918,10 +27712,10 @@ window.Buffer = buffer.Buffer; } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$l.concat([head, data.extendedPubkey]); + const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$k.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28970,7 +27764,7 @@ window.Buffer = buffer.Buffer; const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -28991,7 +27785,7 @@ window.Buffer = buffer.Buffer; } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -29023,7 +27817,7 @@ window.Buffer = buffer.Buffer; } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -29058,7 +27852,7 @@ window.Buffer = buffer.Buffer; nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -29101,9 +27895,9 @@ window.Buffer = buffer.Buffer; } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$l.concat([head, pSig.pubkey]), + key: Buffer$k.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -29155,10 +27949,10 @@ window.Buffer = buffer.Buffer; } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$l.from(data, 'utf8'), + value: Buffer$k.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -29187,8 +27981,8 @@ window.Buffer = buffer.Buffer; } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$l.allocUnsafe(4); + const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$k.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -29221,7 +28015,7 @@ window.Buffer = buffer.Buffer; } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -29307,8 +28101,8 @@ window.Buffer = buffer.Buffer; tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$l.from([0])); - return Buffer$l.concat(buffers); + buffers.push(Buffer$k.from([0])); + return Buffer$k.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -29316,7 +28110,7 @@ window.Buffer = buffer.Buffer; const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$l.allocUnsafe( + const buffer = Buffer$k.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -29380,12 +28174,12 @@ window.Buffer = buffer.Buffer; function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -29441,10 +28235,10 @@ window.Buffer = buffer.Buffer; return data; } function encode(data) { - const head = Buffer$l.from([TYPE_BYTE]); - const key = Buffer$l.concat([head, data.pubkey]); + const head = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$k.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -29524,7 +28318,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$k.from([TYPE_BYTE]); return { key, value: data, @@ -29561,7 +28355,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$k.from([TYPE_BYTE]); return { key, value: data, @@ -29770,7 +28564,7 @@ window.Buffer = buffer.Buffer; } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$l.from([keyNum]))) { + if (!keyBuf.equals(Buffer$k.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -29989,13 +28783,13 @@ window.Buffer = buffer.Buffer; const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$l.from([0])] + ? [Buffer$k.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$l.allocUnsafe(5); + const header = Buffer$k.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$l.concat( + return Buffer$k.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -30289,11 +29083,11 @@ window.Buffer = buffer.Buffer; }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$k.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$k.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -30513,11 +29307,11 @@ window.Buffer = buffer.Buffer; dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$k.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$k.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -31041,7 +29835,7 @@ window.Buffer = buffer.Buffer; * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -31066,7 +29860,7 @@ window.Buffer = buffer.Buffer; } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -31241,7 +30035,7 @@ window.Buffer = buffer.Buffer; } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -31605,14 +30399,14 @@ window.Buffer = buffer.Buffer; return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$l.allocUnsafe(0); + let buffer = Buffer$k.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); + buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); + buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -32121,7 +30915,7 @@ window.Buffer = buffer.Buffer; const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$l.from('aa21a9ed', 'hex'); + const HEADER = Buffer$k.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -32137,7 +30931,7 @@ window.Buffer = buffer.Buffer; }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$l.allocUnsafe(36); + const buffer = Buffer$k.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -32413,7 +31207,7 @@ window.Buffer = buffer.Buffer; // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -36153,7 +34947,7 @@ window.Buffer = buffer.Buffer; this.bufs = []; } BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$l.alloc(alloc); + var b = Buffer$k.alloc(alloc); fn(b); this.bufs.push(b); }; @@ -36173,14 +34967,14 @@ window.Buffer = buffer.Buffer; this.bufs.push(varuintBitcoin.encode(i)); }; BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$l.from(slice)); + this.bufs.push(Buffer$k.from(slice)); }; BufferWriter.prototype.writeVarSlice = function (slice) { this.writeVarInt(slice.length); this.writeSlice(slice); }; BufferWriter.prototype.buffer = function () { - return Buffer$l.concat(this.bufs); + return Buffer$k.concat(this.bufs); }; return BufferWriter; }()); @@ -36322,9 +35116,9 @@ window.Buffer = buffer.Buffer; p2pkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); + buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); return { scriptPubKey: buf.buffer() }; }; p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { @@ -36351,7 +35145,7 @@ window.Buffer = buffer.Buffer; var xonlyPubkey = pubkey.slice(1); // x-only pubkey var buf = new BufferWriter(); var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen buf.writeSlice(outputKey); return { scriptPubKey: buf.buffer() }; }; @@ -36374,8 +35168,8 @@ window.Buffer = buffer.Buffer; p2tr.prototype.hashTapTweak = function (x) { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$l.concat([h, h, x])); + var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$k.concat([h, h, x])); }; /** * Calculates a taproot output key from an internal key. This output key will be @@ -36394,13 +35188,13 @@ window.Buffer = buffer.Buffer; // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$l.concat([ - Buffer$l.from([0x02]), + var evenEcdsaPubkey = Buffer$k.concat([ + Buffer$k.from([0x02]), internalPubkey, ]); var tweak = this.hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. var outputSchnorrKey = outputEcdsaKey.slice(1); // Create address @@ -36417,7 +35211,7 @@ window.Buffer = buffer.Buffer; var buf = new BufferWriter(); var redeemScript = this.createRedeemScript(pubkey); var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; @@ -36447,7 +35241,7 @@ window.Buffer = buffer.Buffer; }; p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { var pubkeyHash = hashPublicKey(pubkey); - return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); + return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); }; return p2wpkhWrapped; }(SingleKeyAccount)); @@ -36459,7 +35253,7 @@ window.Buffer = buffer.Buffer; p2wpkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); + buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); buf.writeSlice(pubkeyHash); return { scriptPubKey: buf.buffer() }; }; @@ -36540,7 +35334,7 @@ window.Buffer = buffer.Buffer; var n = leaves.length; if (n == 0) { return { - root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), + root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), leaves: [] }; } @@ -36560,16 +35354,16 @@ window.Buffer = buffer.Buffer; return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; }; Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); + return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); }; return Merkle; }()); function hashLeaf(buf, hashFunction) { if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$l.from([0]), buf, hashFunction); + return hashConcat(Buffer$k.from([0]), buf, hashFunction); } function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$l.concat([bufA, bufB])); + return hashFunction(Buffer$k.concat([bufA, bufB])); } var Node = /** @class */ (function () { function Node(left, right, hash) { @@ -36634,13 +35428,13 @@ window.Buffer = buffer.Buffer; }; WalletPolicy.prototype.serialize = function () { var keyBuffers = this.keys.map(function (k) { - return Buffer$l.from(k, "ascii"); + return Buffer$k.from(k, "ascii"); }); var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); var buf = new BufferWriter(); buf.writeUInt8(0x01); // wallet type (policy map) buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); + buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); return buf.buffer(); }; @@ -36663,7 +35457,7 @@ window.Buffer = buffer.Buffer; tx.writeUInt32(psbt.getGlobalTxVersion()); var isSegwit = !!psbt.getInputWitnessUtxo(0); if (isSegwit) { - tx.writeSlice(Buffer$l.from([0, 1])); + tx.writeSlice(Buffer$k.from([0, 1])); } var inputCount = psbt.getGlobalInputCount(); tx.writeVarInt(inputCount); @@ -36671,7 +35465,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < inputCount; i++) { tx.writeSlice(psbt.getInputPreviousTxid(i)); tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); tx.writeUInt32(psbt.getInputSequence(i)); if (isSegwit) { witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); @@ -36747,7 +35541,7 @@ window.Buffer = buffer.Buffer; psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { __extends$3(NoSuchEntry, _super); function NoSuchEntry() { @@ -36973,11 +35767,11 @@ window.Buffer = buffer.Buffer; }); }; PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); + from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); }; PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); + buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); serializeMap(buf, this.globalMap); this.inputMaps.forEach(function (map) { serializeMap(buf, map); @@ -37021,17 +35815,17 @@ window.Buffer = buffer.Buffer; var result = []; map.forEach(function (_v, k) { if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$l.from(k.substring(2), "hex")); + result.push(Buffer$k.from(k.substring(2), "hex")); } }); return result; }; PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); + var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); return keyTypes.some(function (k) { return k == keyType; }); }; PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$l.from([])); + var key = new Key(keyType, Buffer$k.from([])); this.globalMap.set(key.toString(), value); }; PsbtV2.prototype.getGlobal = function (keyType) { @@ -37117,7 +35911,7 @@ window.Buffer = buffer.Buffer; throw new NoSuchEntry(key.toString()); } // Make sure to return a copy, to protect the underlying data. - return Buffer$l.from(value); + return Buffer$k.from(value); } var Key = /** @class */ (function () { function Key(keyType, keyData) { @@ -37156,25 +35950,25 @@ window.Buffer = buffer.Buffer; function serializeMap(buf, map) { for (var k in map.keys) { var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); + var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); keyPair.serialize(buf); } buf.writeUInt8(0); } function b() { - return Buffer$l.from([]); + return Buffer$k.from([]); } function set(map, keyType, keyData, value) { var key = new Key(keyType, keyData); map.set(key.toString(), value); } function uint32LE(n) { - var b = Buffer$l.alloc(4); + var b = Buffer$k.alloc(4); b.writeUInt32LE(n, 0); return b; } function uint64LE(n) { - var b = Buffer$l.alloc(8); + var b = Buffer$k.alloc(8); b.writeBigUInt64LE(BigInt(n), 0); return b; } @@ -37309,7 +36103,7 @@ window.Buffer = buffer.Buffer; } else if (data.length <= 256 * 256) { buf.writeUInt8(77); - var b = Buffer$l.alloc(2); + var b = Buffer$k.alloc(2); b.writeUInt16LE(data.length, 0); buf.writeSlice(b); } @@ -37336,18 +36130,18 @@ window.Buffer = buffer.Buffer; } function createVarint(value) { if (value < 0xfd) { - var buffer_1 = Buffer$l.alloc(1); + var buffer_1 = Buffer$k.alloc(1); buffer_1[0] = value; return buffer_1; } if (value <= 0xffff) { - var buffer_2 = Buffer$l.alloc(3); + var buffer_2 = Buffer$k.alloc(3); buffer_2[0] = 0xfd; buffer_2[1] = value & 0xff; buffer_2[2] = (value >> 8) & 0xff; return buffer_2; } - var buffer = Buffer$l.alloc(5); + var buffer = Buffer$k.alloc(5); buffer[0] = 0xfe; buffer[1] = value & 0xff; buffer[2] = (value >> 8) & 0xff; @@ -37363,11 +36157,11 @@ window.Buffer = buffer.Buffer; */ function serializeTransactionOutputs(_a) { var outputs = _a.outputs; - var outputBuffer = Buffer$l.alloc(0); + var outputBuffer = Buffer$k.alloc(0); if (typeof outputs !== "undefined") { - outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); + outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); outputs.forEach(function (output) { - outputBuffer = Buffer$l.concat([ + outputBuffer = Buffer$k.concat([ outputBuffer, output.amount, createVarint(output.script.length), @@ -37381,18 +36175,18 @@ window.Buffer = buffer.Buffer; if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$l.alloc(0); + var inputBuffer = Buffer$k.alloc(0); var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; transaction.inputs.forEach(function (input) { inputBuffer = isDecred || isBech32 - ? Buffer$l.concat([ + ? Buffer$k.concat([ inputBuffer, input.prevout, - Buffer$l.from([0x00]), + Buffer$k.from([0x00]), input.sequence, ]) - : Buffer$l.concat([ + : Buffer$k.concat([ inputBuffer, input.prevout, createVarint(input.script.length), @@ -37403,19 +36197,19 @@ window.Buffer = buffer.Buffer; var outputBuffer = serializeTransactionOutputs(transaction); if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$l.concat([ + outputBuffer = Buffer$k.concat([ outputBuffer, - (useWitness && transaction.witness) || Buffer$l.alloc(0), + (useWitness && transaction.witness) || Buffer$k.alloc(0), transaction.locktime, - transaction.nExpiryHeight || Buffer$l.alloc(0), - transaction.extraData || Buffer$l.alloc(0), + transaction.nExpiryHeight || Buffer$k.alloc(0), + transaction.extraData || Buffer$k.alloc(0), ]); } - return Buffer$l.concat([ + return Buffer$k.concat([ transaction.version, - timestamp ? timestamp : Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), + timestamp ? timestamp : Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), createVarint(transaction.inputs.length), inputBuffer, outputBuffer, @@ -37553,7 +36347,7 @@ window.Buffer = buffer.Buffer; case 2: address = _c.sent(); components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); + uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); return [2 /*return*/, { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, @@ -37596,7 +36390,7 @@ window.Buffer = buffer.Buffer; masterFingerprint = _a.sent(); policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; } }); }); @@ -37665,7 +36459,7 @@ window.Buffer = buffer.Buffer; i++; return [3 /*break*/, 2]; case 7: - outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); + outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); outputsBufferReader = new BufferReader(outputsConcat); outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); @@ -37761,7 +36555,7 @@ window.Buffer = buffer.Buffer; case 0: inputTx = input[0]; spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; + redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; sequence = input[3]; if (sequence) { psbt.setInputSequence(i, sequence); @@ -37805,7 +36599,7 @@ window.Buffer = buffer.Buffer; var sigs; return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; case 1: sigs = _a.sent(); sigs.forEach(function (v, k) { @@ -38074,270 +36868,6 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$7 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$l.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$l.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ - transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$l.from([0x00]) - : Buffer$l.alloc(0); - data = Buffer$l.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$l.concat([ - output.amount, - isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$l.concat(endData); - extraPart = isDecred - ? data - : Buffer$l.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; var __values$6 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); @@ -38349,6 +36879,270 @@ window.Buffer = buffer.Buffer; }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$k.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$k.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$6(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ + transaction.version, + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$6(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$k.from([0x00]) + : Buffer$k.alloc(0); + data = Buffer$k.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$6(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$k.concat([ + output.amount, + isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$k.concat(endData); + extraPart = isDecred + ? data + : Buffer$k.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { if (bip143 === void 0) { bip143 = false; } if (overwinter === void 0) { overwinter = false; } @@ -38375,10 +37169,10 @@ window.Buffer = buffer.Buffer; return __generator$b(this, function (_e) { switch (_e.label) { case 0: - data = Buffer$l.concat([ + data = Buffer$k.concat([ transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), createVarint(transaction.inputs.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; @@ -38389,7 +37183,7 @@ window.Buffer = buffer.Buffer; _e.label = 2; case 2: _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); + _a = __values$5(transaction.inputs), _b = _a.next(); _e.label = 3; case 3: if (!!_b.done) return [3 /*break*/, 14]; @@ -38398,24 +37192,24 @@ window.Buffer = buffer.Buffer; inputValue = inputs[i].value; if (bip143) { if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputValue.length]); + prefix = Buffer$k.from([0x01, inputValue.length]); } else { - prefix = Buffer$l.from([0x02]); + prefix = Buffer$k.from([0x02]); } } else { if (inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputs[i].value.length]); + prefix = Buffer$k.from([0x01, inputs[i].value.length]); } else { - prefix = Buffer$l.from([0x00]); + prefix = Buffer$k.from([0x00]); } } - data = Buffer$l.concat([ + data = Buffer$k.concat([ prefix, inputValue, - isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), + isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), createVarint(input.script.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; @@ -38435,7 +37229,7 @@ window.Buffer = buffer.Buffer; scriptBlocks.push(input.script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$l.concat([ + scriptBlocks.push(Buffer$k.concat([ input.script.slice(offset, offset + blockSize), input.sequence, ])); @@ -38446,7 +37240,7 @@ window.Buffer = buffer.Buffer; _e.label = 5; case 5: _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + scriptBlocks_1 = (e_1 = void 0, __values$5(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); _e.label = 6; case 6: if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; @@ -38504,7 +37298,7 @@ window.Buffer = buffer.Buffer; var hash = sha$3("sha256") .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) .digest(); - var data = Buffer$l.alloc(4); + var data = Buffer$k.alloc(4); data.writeUInt32LE(indexLookup, 0); var outputs = transaction.outputs, locktime = transaction.locktime; if (!outputs || !locktime) { @@ -38513,38 +37307,38 @@ window.Buffer = buffer.Buffer; if (!outputs[indexLookup]) { throw new Error("getTrustedInputBIP143: wrong index"); } - hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); + hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); return hash.toString("hex"); } function compressPublicKey(publicKey) { var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$l.alloc(1); + var prefixBuffer = Buffer$k.alloc(1); prefixBuffer[0] = prefix; - return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$l.alloc(4); + var lockTimeBuffer = Buffer$k.alloc(4); lockTimeBuffer.writeUInt32BE(lockTime, 0); var buffer = isDecred - ? Buffer$l.concat([ + ? Buffer$k.concat([ pathsBuffer, lockTimeBuffer, - expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([sigHashType]), + expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([sigHashType]), ]) - : Buffer$l.concat([ + : Buffer$k.concat([ pathsBuffer, - Buffer$l.from([0x00]), + Buffer$k.from([0x00]), lockTimeBuffer, - Buffer$l.from([sigHashType]), + Buffer$k.from([sigHashType]), ]); if (expiryHeight && !isDecred) { - buffer = Buffer$l.concat([buffer, expiryHeight]); + buffer = Buffer$k.concat([buffer, expiryHeight]); } return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { if (result.length > 0) { @@ -38746,7 +37540,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$5 = (undefined && undefined.__values) || function(o) { + var __values$4 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38819,9 +37613,9 @@ window.Buffer = buffer.Buffer; additionals.includes("gold") || additionals.includes("bip143"))) || (!!expiryHeight && !isDecred); - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST @@ -38836,17 +37630,17 @@ window.Buffer = buffer.Buffer; targetTransaction = { inputs: [], version: defaultVersion, - timestamp: Buffer$l.alloc(0) + timestamp: Buffer$k.alloc(0) }; getTrustedInputCall = useBip143 && !useTrustedInputForSegwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); + outputScript = Buffer$k.from(outputScriptHex, "hex"); notify(0, 0); _b.label = 5; case 5: _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); _b.label = 6; case 6: if (!!inputs_1_1.done) return [3 /*break*/, 10]; @@ -38856,13 +37650,13 @@ window.Buffer = buffer.Buffer; case 7: trustedInput = _b.sent(); log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$l.alloc(4); + sequence = Buffer$k.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: true, - value: Buffer$l.from(trustedInput, "hex"), + value: Buffer$k.from(trustedInput, "hex"), sequence: sequence }); _b.label = 8; @@ -38873,11 +37667,11 @@ window.Buffer = buffer.Buffer; regularOutputs.push(outputs[index]); } if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); targetTransaction.nExpiryHeight = expiryHeight; // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$l.from(sapling + targetTransaction.extraData = Buffer$k.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); } @@ -38901,7 +37695,7 @@ window.Buffer = buffer.Buffer; return [7 /*endfinally*/]; case 13: targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$l.alloc(4); + var sequence = Buffer$k.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); @@ -38930,12 +37724,12 @@ window.Buffer = buffer.Buffer; return [3 /*break*/, 14]; case 17: for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); + publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); } _b.label = 18; case 18: if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$l.alloc(4); + targetTransaction.timestamp = Buffer$k.alloc(4); targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); } onDeviceSignatureRequested(); @@ -38967,13 +37761,13 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 34]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") + ? Buffer$k.from(input[2], "hex") : !segwit ? regularOutputs[i].script - : Buffer$l.concat([ - Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), + : Buffer$k.concat([ + Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), hashPublicKey(publicKeys[i]), - Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), + Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), ]); pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; @@ -39018,20 +37812,20 @@ window.Buffer = buffer.Buffer; // Populate the final input scripts for (i = 0; i < inputs.length; i++) { if (segwit) { - targetTransaction.witness = Buffer$l.alloc(0); + targetTransaction.witness = Buffer$k.alloc(0); if (!bech32) { - targetTransaction.inputs[i].script = Buffer$l.concat([ - Buffer$l.from("160014", "hex"), + targetTransaction.inputs[i].script = Buffer$k.concat([ + Buffer$k.from("160014", "hex"), hashPublicKey(publicKeys[i]), ]); } } else { - signatureSize = Buffer$l.alloc(1); - keySize = Buffer$l.alloc(1); + signatureSize = Buffer$k.alloc(1); + keySize = Buffer$k.alloc(1); signatureSize[0] = signatures[i].length; keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$l.concat([ + targetTransaction.inputs[i].script = Buffer$k.concat([ signatureSize, signatures[i], keySize, @@ -39041,51 +37835,51 @@ window.Buffer = buffer.Buffer; offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); } - lockTimeBuffer = Buffer$l.alloc(4); + lockTimeBuffer = Buffer$k.alloc(4); lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$l.concat([ + result = Buffer$k.concat([ serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript, ]); if (segwit && !isDecred) { - witness = Buffer$l.alloc(0); + witness = Buffer$k.alloc(0); for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$l.concat([ - Buffer$l.from("02", "hex"), - Buffer$l.from([signatures[i].length]), + tmpScriptData = Buffer$k.concat([ + Buffer$k.from("02", "hex"), + Buffer$k.from([signatures[i].length]), signatures[i], - Buffer$l.from([publicKeys[i].length]), + Buffer$k.from([publicKeys[i].length]), publicKeys[i], ]); - witness = Buffer$l.concat([witness, tmpScriptData]); + witness = Buffer$k.concat([witness, tmpScriptData]); } - result = Buffer$l.concat([result, witness]); + result = Buffer$k.concat([result, witness]); } // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here // and it should not break other coins because expiryHeight is false for them. // Don't know about Decred though. - result = Buffer$l.concat([result, lockTimeBuffer]); + result = Buffer$k.concat([result, lockTimeBuffer]); if (expiryHeight) { - result = Buffer$l.concat([ + result = Buffer$k.concat([ result, - targetTransaction.nExpiryHeight || Buffer$l.alloc(0), - targetTransaction.extraData || Buffer$l.alloc(0), + targetTransaction.nExpiryHeight || Buffer$k.alloc(0), + targetTransaction.extraData || Buffer$k.alloc(0), ]); } if (isDecred) { - decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); + decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$l.concat([ + decredWitness_1 = Buffer$k.concat([ decredWitness_1, - Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0xff, 0xff, 0xff, 0xff]), - Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), + Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0xff, 0xff, 0xff, 0xff]), + Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script, ]); }); - result = Buffer$l.concat([result, decredWitness_1]); + result = Buffer$k.concat([result, decredWitness_1]); } return [2 /*return*/, result.toString("hex")]; } @@ -39137,7 +37931,7 @@ window.Buffer = buffer.Buffer; switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$l.from(messageHex, "hex"); + message = Buffer$k.from(messageHex, "hex"); offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; @@ -39150,7 +37944,7 @@ window.Buffer = buffer.Buffer; chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach(function (element, index) { @@ -39177,7 +37971,7 @@ window.Buffer = buffer.Buffer; case 2: _b.sent(); return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; case 4: res = _b.sent(); v = res[0] - 0x30; @@ -39249,7 +38043,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$4 = (undefined && undefined.__values) || function(o) { + var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -39274,9 +38068,9 @@ window.Buffer = buffer.Buffer; switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); defaultVersion.writeUInt32LE(transactionVersion, 0); trustedInputs = []; regularOutputs = []; @@ -39288,11 +38082,11 @@ window.Buffer = buffer.Buffer; version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); + outputScript = Buffer$k.from(outputScriptHex, "hex"); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); _c.label = 2; case 2: if (!!inputs_1_1.done) return [3 /*break*/, 6]; @@ -39301,15 +38095,15 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; case 3: trustedInput = _c.sent(); - sequence = Buffer$l.alloc(4); + sequence = Buffer$k.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: false, value: segwit - ? Buffer$l.from(trustedInput, "hex") - : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), + ? Buffer$k.from(trustedInput, "hex") + : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), sequence: sequence }); _c.label = 4; @@ -39337,7 +38131,7 @@ window.Buffer = buffer.Buffer; case 9: // Pre-build the target transaction for (i = 0; i < inputs.length; i++) { - sequence = Buffer$l.alloc(4); + sequence = Buffer$k.alloc(4); sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); @@ -39362,7 +38156,7 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 19]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") + ? Buffer$k.from(input[2], "hex") : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; @@ -39493,8 +38287,8 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.derivatePath(path)]; case 2: accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); return [2 /*return*/, xpub]; } }); @@ -39612,29 +38406,29 @@ window.Buffer = buffer.Buffer; return hash160(compressedPubKey).slice(0, 4); } function asBufferUInt32BE(n) { - var buf = Buffer$l.allocUnsafe(4); + var buf = Buffer$k.allocUnsafe(4); buf.writeUInt32BE(n, 0); return buf; } var compressPublicKeySECP256 = function (publicKey) { - return Buffer$l.concat([ - Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), + return Buffer$k.concat([ + Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), publicKey.slice(1, 33), ]); }; function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { var indexBuffer = asBufferUInt32BE(index); indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$l.concat([ + var extendedKeyBytes = Buffer$k.concat([ asBufferUInt32BE(version), - Buffer$l.from([depth]), + Buffer$k.from([depth]), parentFingerprint, indexBuffer, chainCode, pubKey, ]); var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); + return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); } function sha256(buffer) { return sha$3("sha256").update(buffer).digest(); @@ -39681,7 +38475,7 @@ window.Buffer = buffer.Buffer; } MerkleMap.prototype.commitment = function () { // returns a buffer between 65 and 73 (included) bytes long - return Buffer$l.concat([ + return Buffer$k.concat([ createVarint(this.keys.length), this.keysTree.getRoot(), this.valuesTree.getRoot(), @@ -39779,7 +38573,7 @@ window.Buffer = buffer.Buffer; } return v; }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); var merkleMap = new MerkleMap(sortedKeys, values); return merkleMap; }; @@ -39826,7 +38620,7 @@ window.Buffer = buffer.Buffer; } return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$3 = (undefined && undefined.__values) || function(o) { + var __values$2 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -39860,9 +38654,9 @@ window.Buffer = buffer.Buffer; return _this; } YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$l.from(request.subarray(1))); + this.results.push(Buffer$k.from(request.subarray(1))); this.progressCallback(); - return Buffer$l.from(""); + return Buffer$k.from(""); }; return YieldCommand; }(ClientCommand)); @@ -39885,7 +38679,7 @@ window.Buffer = buffer.Buffer; throw new Error("Unsupported request, the first byte should be 0"); } // read the hash - var hash = Buffer$l.alloc(32); + var hash = Buffer$k.alloc(32); for (var i = 0; i < 32; i++) { hash[i] = req[1 + i]; } @@ -39899,12 +38693,12 @@ window.Buffer = buffer.Buffer; var payload_size = Math.min(max_payload_size, known_preimage.length); if (payload_size < known_preimage.length) { for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$l.from([known_preimage[i]])); + this.queue.push(Buffer$k.from([known_preimage[i]])); } } - return Buffer$l.concat([ + return Buffer$k.concat([ preimage_len_varint, - Buffer$l.from([payload_size]), + Buffer$k.from([payload_size]), known_preimage.subarray(0, payload_size), ]); } @@ -39956,10 +38750,10 @@ window.Buffer = buffer.Buffer; if (n_leftover_elements > 0) { (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); } - return Buffer$l.concat(__spreadArray$1([ + return Buffer$k.concat(__spreadArray$1([ mt.getLeafHash(leaf_index), - Buffer$l.from([proof.length]), - Buffer$l.from([n_response_elements]) + Buffer$k.from([proof.length]), + Buffer$k.from([n_response_elements]) ], __read$1(proof.slice(0, n_response_elements)), false)); }; return GetMerkleLeafProofCommand; @@ -39978,13 +38772,13 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid request, unexpected trailing data"); } // read the root hash - var root_hash = Buffer$l.alloc(32); + var root_hash = Buffer$k.alloc(32); for (var i = 0; i < 32; i++) { root_hash[i] = req.readUInt8(i); } var root_hash_hex = root_hash.toString("hex"); // read the leaf hash - var leef_hash = Buffer$l.alloc(32); + var leef_hash = Buffer$k.alloc(32); for (var i = 0; i < 32; i++) { leef_hash[i] = req.readUInt8(32 + i); } @@ -40002,7 +38796,7 @@ window.Buffer = buffer.Buffer; break; } } - return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); + return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); }; return GetMerkleLeafIndexCommand; }(ClientCommand)); @@ -40029,9 +38823,9 @@ window.Buffer = buffer.Buffer; var max_elements = Math.floor(253 / element_len); var n_returned_elements = Math.min(max_elements, this.queue.length); var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$l.concat(__spreadArray$1([ - Buffer$l.from([n_returned_elements]), - Buffer$l.from([element_len]) + return Buffer$k.concat(__spreadArray$1([ + Buffer$k.from([n_returned_elements]), + Buffer$k.from([element_len]) ], __read$1(returned_elements), false)); }; return GetMoreElementsCommand; @@ -40067,7 +38861,7 @@ window.Buffer = buffer.Buffer; new GetMoreElementsCommand(this.queue), ]; try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + for (var commands_1 = __values$2(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { var cmd = commands_1_1.value; if (this.commands.has(cmd.code)) { throw new Error("Multiple commands with code " + cmd.code); @@ -40092,9 +38886,9 @@ window.Buffer = buffer.Buffer; ClientCommandInterpreter.prototype.addKnownList = function (elements) { var e_2, _a; try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + for (var elements_1 = __values$2(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { var el = elements_1_1.value; - var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); + var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); this.addKnownPreimage(preimage); } } @@ -40162,7 +38956,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$2 = (undefined && undefined.__values) || function(o) { + var __values$1 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -40233,8 +39027,8 @@ window.Buffer = buffer.Buffer; if (pathElements.length > 6) { throw new Error("Path too long. At most 6 levels allowed."); } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), pathElementsToBuffer(pathElements), ]))]; case 1: @@ -40258,15 +39052,15 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid HMAC length"); } clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$l.alloc(4); + addressIndexBuffer = Buffer$k.alloc(4); addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), - Buffer$l.from([change]), + walletHMAC || Buffer$k.alloc(32, 0), + Buffer$k.from([change]), addressIndexBuffer, ]), clientInterpreter)]; case 1: @@ -40289,11 +39083,11 @@ window.Buffer = buffer.Buffer; } clientInterpreter = new ClientCommandInterpreter(progressCallback); // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + for (_a = __values$1(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { map = _b.value; clientInterpreter.addKnownMapping(map); } @@ -40306,7 +39100,7 @@ window.Buffer = buffer.Buffer; finally { if (e_1) throw e_1.error; } } try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + for (_c = __values$1(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { map = _d.value; clientInterpreter.addKnownMapping(map); } @@ -40322,21 +39116,21 @@ window.Buffer = buffer.Buffer; inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ merkelizedPsbt.getGlobalKeysValuesRoot(), createVarint(merkelizedPsbt.getGlobalInputCount()), inputMapsRoot, createVarint(merkelizedPsbt.getGlobalOutputCount()), outputMapsRoot, walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), + walletHMAC || Buffer$k.alloc(32, 0), ]), clientInterpreter)]; case 1: _h.sent(); yielded = clientInterpreter.getYielded(); ret = new Map(); try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + for (yielded_1 = __values$1(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { inputAndSig = yielded_1_1.value; ret.set(inputAndSig[0], inputAndSig.slice(1)); } @@ -40356,7 +39150,7 @@ window.Buffer = buffer.Buffer; AppClient.prototype.getMasterFingerprint = function () { return __awaiter$4(this, void 0, void 0, function () { return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; }); }); }; @@ -40409,18 +39203,18 @@ window.Buffer = buffer.Buffer; var outputs = []; var witness = false; var offset = 0; - var timestamp = Buffer$l.alloc(0); - var nExpiryHeight = Buffer$l.alloc(0); - var nVersionGroupId = Buffer$l.alloc(0); - var extraData = Buffer$l.alloc(0); + var timestamp = Buffer$k.alloc(0); + var nExpiryHeight = Buffer$k.alloc(0); + var nVersionGroupId = Buffer$k.alloc(0); + var extraData = Buffer$k.alloc(0); var isDecred = additionals.includes("decred"); var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$l.from(transactionHex, "hex"); + var transaction = Buffer$k.from(transactionHex, "hex"); var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); + var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$k.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$k.from([0x02, 0x00, 0x00, 0x00])); offset += 4; if (!hasTimestamp && isSegwitSupported && @@ -40446,8 +39240,8 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < numberInputs; i++) { var prevout = transaction.slice(offset, offset + 36); offset += 36; - var script = Buffer$l.alloc(0); - var tree = Buffer$l.alloc(0); + var script = Buffer$k.alloc(0); + var tree = Buffer$k.alloc(0); //No script for decred, it has a witness if (!isDecred) { varint = getVarint(transaction, offset); @@ -40864,422 +39658,401 @@ window.Buffer = buffer.Buffer; 'default': Btc }); - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses$1 = {}; - var deserializers$1 = {}; - var addCustomErrorDeserializer$1 = function (name, deserializer) { - deserializers$1[name] = deserializer; - }; - var createCustomErrorClass$1 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$1[name] = C; - return C; - }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers$1[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass$1(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); - var AmountRequired = createCustomErrorClass$1("AmountRequired"); - var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass$1("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass$1("NetworkDown"); - var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); - var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass$1("FeeRequired"); - var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); - var SyncError = createCustomErrorClass$1("SyncError"); - var PairingFailed = createCustomErrorClass$1("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); - var DBNotReset = createCustomErrorClass$1("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$1(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); - var StatusCodes$1 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage$1(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$1(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$1(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$1.prototype = new Error(); + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var errorClasses$1 = {}; + var deserializers$1 = {}; + var addCustomErrorDeserializer$1 = function (name, deserializer) { + deserializers$1[name] = deserializer; + }; + var createCustomErrorClass$1 = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses$1[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers$1[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass$1(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var to = {}; + seen.push(from); + for (var _i = 0, _a = Object.keys(from); _i < _a.length; _i++) { + var key = _a[_i]; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); + var AmountRequired = createCustomErrorClass$1("AmountRequired"); + var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass$1("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass$1("NetworkDown"); + var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); + var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass$1("FeeRequired"); + var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); + var SyncError = createCustomErrorClass$1("SyncError"); + var PairingFailed = createCustomErrorClass$1("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); + var DBNotReset = createCustomErrorClass$1("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError$1(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError$1.prototype = new Error(); + addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); + var StatusCodes$1 = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa, + }; + function getAltStatusMessage$1(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError$1(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage$1(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError$1.prototype = new Error(); addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - var libEs = /*#__PURE__*/Object.freeze({ + var dist = /*#__PURE__*/Object.freeze({ __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass$1, - addCustomErrorDeserializer: addCustomErrorDeserializer$1, AccountNameRequiredError: AccountNameRequiredError, AccountNotSupported: AccountNotSupported, AmountRequired: AmountRequired, BluetoothRequired: BluetoothRequired, BtcUnmatchedApp: BtcUnmatchedApp, CantOpenDevice: CantOpenDevice, + CantScanQRCode: CantScanQRCode, CashAddrNotSupported: CashAddrNotSupported, CurrencyNotSupported: CurrencyNotSupported, + DBNotReset: DBNotReset, + DBWrongPassword: DBWrongPassword, DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceHalted: DeviceHalted, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceNameInvalid: DeviceNameInvalid, DeviceNotGenuineError: DeviceNotGenuineError, DeviceOnDashboardExpected: DeviceOnDashboardExpected, DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, + DeviceShouldStayInApp: DeviceShouldStayInApp, DeviceSocketFail: DeviceSocketFail, DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, DisconnectedDevice: DisconnectedDevice, DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + ETHAddressNonEIP: ETHAddressNonEIP, EnpointConfigError: EnpointConfigError, EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, FeeEstimationFailed: FeeEstimationFailed, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, FirmwareNotRecognized: FirmwareNotRecognized, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + GasLessThanEstimate: GasLessThanEstimate, + GenuineCheckFailed: GenuineCheckFailed, HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, InvalidAddress: InvalidAddress, InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + InvalidXRPTag: InvalidXRPTag, LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, LedgerAPIError: LedgerAPIError, LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, LedgerAPINotAvailable: LedgerAPINotAvailable, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, ManagerDeviceLockedError: ManagerDeviceLockedError, ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, ManagerUninstallBTCDep: ManagerUninstallBTCDep, NetworkDown: NetworkDown, + NoAccessToCamera: NoAccessToCamera, NoAddressesFound: NoAddressesFound, + NoDBPathGiven: NoDBPathGiven, NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, NotEnoughGas: NotEnoughGas, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, + PairingFailed: PairingFailed, PasswordIncorrectError: PasswordIncorrectError, + PasswordsDontMatchError: PasswordsDontMatchError, + RecipientRequired: RecipientRequired, RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, RecommendUndelegation: RecommendUndelegation, + StatusCodes: StatusCodes$1, + SyncError: SyncError, TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, + TransportError: TransportError$1, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportRaceCondition: TransportRaceCondition$1, + TransportStatusError: TransportStatusError$1, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UnexpectedBootloader: UnexpectedBootloader, + UnknownMCU: UnknownMCU, UpdateFetchFileFail: UpdateFetchFileFail, UpdateIncorrectHash: UpdateIncorrectHash, UpdateIncorrectSig: UpdateIncorrectSig, UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition$1, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, WebsocketConnectionError: WebsocketConnectionError, WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError$1, - StatusCodes: StatusCodes$1, + WrongDeviceForAccount: WrongDeviceForAccount, + addCustomErrorDeserializer: addCustomErrorDeserializer$1, + createCustomErrorClass: createCustomErrorClass$1, + deserializeError: deserializeError, getAltStatusMessage: getAltStatusMessage$1, - TransportStatusError: TransportStatusError$1 + serializeError: serializeError }); var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -41377,7 +40150,7 @@ window.Buffer = buffer.Buffer; * @return a Promise of response buffer */ this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$l.alloc(0); } + if (data === void 0) { data = Buffer$k.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } return __awaiter$2(_this, void 0, void 0, function () { var response, sw; @@ -41387,9 +40160,9 @@ window.Buffer = buffer.Buffer; if (data.length >= 256) { throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - return [4 /*yield*/, this.exchange(Buffer$l.concat([ - Buffer$l.from([cla, ins, p1, p2]), - Buffer$l.from([data.length]), + return [4 /*yield*/, this.exchange(Buffer$k.concat([ + Buffer$k.from([cla, ins, p1, p2]), + Buffer$k.from([data.length]), data, ]))]; case 1: @@ -41603,19 +40376,19 @@ window.Buffer = buffer.Buffer; var hidFraming$1 = {}; - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + var require$$0 = /*@__PURE__*/getAugmentedNamespace(dist); (function (exports) { exports.__esModule = true; var errors_1 = require$$0; var Tag = 0x05; function asUInt16BE(value) { - var b = Buffer$l.alloc(2); + var b = Buffer$k.alloc(2); b.writeUInt16BE(value, 0); return b; } var initialAcc = { - data: Buffer$l.alloc(0), + data: Buffer$k.alloc(0), dataLength: 0, sequence: 0 }; @@ -41625,21 +40398,21 @@ window.Buffer = buffer.Buffer; var createHIDframing = function (channel, packetSize) { return { makeBlocks: function (apdu) { - var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); + var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); var blockSize = packetSize - 5; var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$l.concat([ + data = Buffer$k.concat([ data, - Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), ]); var blocks = []; for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$l.alloc(5); + var head = Buffer$k.alloc(5); head.writeUInt16BE(channel, 0); head.writeUInt8(Tag, 2); head.writeUInt16BE(i, 3); var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$l.concat([head, chunk])); + blocks.push(Buffer$k.concat([head, chunk])); } return blocks; }, @@ -41659,7 +40432,7 @@ window.Buffer = buffer.Buffer; } sequence++; var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$l.concat([data, chunkData]); + data = Buffer$k.concat([data, chunkData]); if (data.length > dataLength) { data = data.slice(0, dataLength); } @@ -42116,7 +40889,7 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$l.from(r.data.buffer); + buffer = Buffer$k.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -43120,12 +41893,12 @@ window.Buffer = buffer.Buffer; this.deviceModel = null; this._events = new EventEmitter$1(); - this.send = async (cla, ins, p1, p2, data = Buffer$l.alloc(0), statusList = [StatusCodes.OK]) => { + this.send = async (cla, ins, p1, p2, data = Buffer$k.alloc(0), statusList = [StatusCodes.OK]) => { if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - const response = await this.exchange(Buffer$l.concat([Buffer$l.from([cla, ins, p1, p2]), Buffer$l.from([data.length]), data])); + const response = await this.exchange(Buffer$k.concat([Buffer$k.from([cla, ins, p1, p2]), Buffer$k.from([data.length]), data])); const sw = response.readUInt16BE(response.length - 2); if (!statusList.some(s => s === sw)) { @@ -43388,7 +42161,7 @@ window.Buffer = buffer.Buffer; } function wrapApdu(apdu, key) { - const result = Buffer$l.alloc(apdu.length); + const result = Buffer$k.alloc(apdu.length); for (let i = 0; i < apdu.length; i++) { result[i] = apdu[i] ^ key[i % key.length]; @@ -43405,7 +42178,7 @@ window.Buffer = buffer.Buffer; function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$l.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); + const challenge = Buffer$k.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); const signRequest = { version: "U2F_V2", keyHandle: webSafe64(keyHandle.toString("base64")), @@ -43419,7 +42192,7 @@ window.Buffer = buffer.Buffer; } = response; if (typeof signatureData === "string") { - const data = Buffer$l.from(normal64(signatureData), "base64"); + const data = Buffer$k.from(normal64(signatureData), "base64"); let result; if (!unwrap) { @@ -43505,7 +42278,7 @@ window.Buffer = buffer.Buffer; setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$l.from(scrambleKey, "ascii"); + this.scrambleKey = Buffer$k.from(scrambleKey, "ascii"); } /** */ From b367d9d55fcbe0d4f1ce3a209ab29600d0ca4d27 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 25 Jan 2022 19:18:26 +1100 Subject: [PATCH 41/78] real new version --- js/ledger.js | 13476 ++++++++++++++++++++++++------------------------- 1 file changed, 6679 insertions(+), 6797 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index b3c91027..93806e2d 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1003,7 +1003,7 @@ window.Buffer = buffer.Buffer; var toString = {}.toString; - var isArray$3 = Array.isArray || function (arr) { + var isArray$1 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1033,12 +1033,12 @@ window.Buffer = buffer.Buffer; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$k.TYPED_ARRAY_SUPPORT + return Buffer$l.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1047,14 +1047,14 @@ window.Buffer = buffer.Buffer; if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$k(length); + that = new Buffer$l(length); } that.length = length; } @@ -1072,9 +1072,9 @@ window.Buffer = buffer.Buffer; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$k (arg, encodingOrOffset, length) { - if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { - return new Buffer$k(arg, encodingOrOffset, length) + function Buffer$l (arg, encodingOrOffset, length) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { + return new Buffer$l(arg, encodingOrOffset, length) } // Common case. @@ -1086,18 +1086,18 @@ window.Buffer = buffer.Buffer; } return allocUnsafe(this, arg) } - return from(this, arg, encodingOrOffset, length) + return from$1(this, arg, encodingOrOffset, length) } - Buffer$k.poolSize = 8192; // not used by this implementation + Buffer$l.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$k._augment = function (arr) { - arr.__proto__ = Buffer$k.prototype; + Buffer$l._augment = function (arr) { + arr.__proto__ = Buffer$l.prototype; return arr }; - function from (that, value, encodingOrOffset, length) { + function from$1 (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1121,13 +1121,13 @@ window.Buffer = buffer.Buffer; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$k.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) + Buffer$l.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { - Buffer$k.prototype.__proto__ = Uint8Array.prototype; - Buffer$k.__proto__ = Uint8Array; + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + Buffer$l.prototype.__proto__ = Uint8Array.prototype; + Buffer$l.__proto__ = Uint8Array; } function assertSize (size) { @@ -1158,14 +1158,14 @@ window.Buffer = buffer.Buffer; * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$k.alloc = function (size, fill, encoding) { + Buffer$l.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1176,13 +1176,13 @@ window.Buffer = buffer.Buffer; /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$k.allocUnsafe = function (size) { + Buffer$l.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$k.allocUnsafeSlow = function (size) { + Buffer$l.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1191,7 +1191,7 @@ window.Buffer = buffer.Buffer; encoding = 'utf8'; } - if (!Buffer$k.isEncoding(encoding)) { + if (!Buffer$l.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1238,10 +1238,10 @@ window.Buffer = buffer.Buffer; array = new Uint8Array(array, byteOffset, length); } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1271,7 +1271,7 @@ window.Buffer = buffer.Buffer; return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$3(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1288,12 +1288,12 @@ window.Buffer = buffer.Buffer; } return length | 0 } - Buffer$k.isBuffer = isBuffer; + Buffer$l.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$k.compare = function compare (a, b) { + Buffer$l.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1316,7 +1316,7 @@ window.Buffer = buffer.Buffer; return 0 }; - Buffer$k.isEncoding = function isEncoding (encoding) { + Buffer$l.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1335,13 +1335,13 @@ window.Buffer = buffer.Buffer; } }; - Buffer$k.concat = function concat (list, length) { - if (!isArray$3(list)) { + Buffer$l.concat = function concat (list, length) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$k.alloc(0) + return Buffer$l.alloc(0) } var i; @@ -1352,7 +1352,7 @@ window.Buffer = buffer.Buffer; } } - var buffer = Buffer$k.allocUnsafe(length); + var buffer = Buffer$l.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1408,7 +1408,7 @@ window.Buffer = buffer.Buffer; } } } - Buffer$k.byteLength = byteLength$1; + Buffer$l.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1482,7 +1482,7 @@ window.Buffer = buffer.Buffer; // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$k.prototype._isBuffer = true; + Buffer$l.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1490,7 +1490,7 @@ window.Buffer = buffer.Buffer; b[m] = i; } - Buffer$k.prototype.swap16 = function swap16 () { + Buffer$l.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1501,7 +1501,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$k.prototype.swap32 = function swap32 () { + Buffer$l.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1513,7 +1513,7 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$k.prototype.swap64 = function swap64 () { + Buffer$l.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1527,20 +1527,20 @@ window.Buffer = buffer.Buffer; return this }; - Buffer$k.prototype.toString = function toString () { + Buffer$l.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$k.prototype.equals = function equals (b) { + Buffer$l.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$k.compare(this, b) === 0 + return Buffer$l.compare(this, b) === 0 }; - Buffer$k.prototype.inspect = function inspect () { + Buffer$l.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1550,7 +1550,7 @@ window.Buffer = buffer.Buffer; return '' }; - Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1649,7 +1649,7 @@ window.Buffer = buffer.Buffer; // Normalize val if (typeof val === 'string') { - val = Buffer$k.from(val, encoding); + val = Buffer$l.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1661,7 +1661,7 @@ window.Buffer = buffer.Buffer; return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$k.TYPED_ARRAY_SUPPORT && + if (Buffer$l.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1731,15 +1731,15 @@ window.Buffer = buffer.Buffer; return -1 } - Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1790,7 +1790,7 @@ window.Buffer = buffer.Buffer; return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$k.prototype.write = function write (string, offset, length, encoding) { + Buffer$l.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1862,7 +1862,7 @@ window.Buffer = buffer.Buffer; } }; - Buffer$k.prototype.toJSON = function toJSON () { + Buffer$l.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2015,7 +2015,7 @@ window.Buffer = buffer.Buffer; return res } - Buffer$k.prototype.slice = function slice (start, end) { + Buffer$l.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2037,12 +2037,12 @@ window.Buffer = buffer.Buffer; if (end < start) end = start; var newBuf; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$k.prototype; + newBuf.__proto__ = Buffer$l.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$k(sliceLen, undefined); + newBuf = new Buffer$l(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2059,7 +2059,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2074,7 +2074,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2090,22 +2090,22 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2114,7 +2114,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] * 0x1000000) }; - Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2123,7 +2123,7 @@ window.Buffer = buffer.Buffer; this[offset + 3]) }; - Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2141,7 +2141,7 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2159,25 +2159,25 @@ window.Buffer = buffer.Buffer; return val }; - Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2186,7 +2186,7 @@ window.Buffer = buffer.Buffer; (this[offset + 3] << 24) }; - Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2195,22 +2195,22 @@ window.Buffer = buffer.Buffer; (this[offset + 3]) }; - Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2221,7 +2221,7 @@ window.Buffer = buffer.Buffer; if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2240,7 +2240,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2259,11 +2259,11 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2276,11 +2276,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2289,11 +2289,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2309,11 +2309,11 @@ window.Buffer = buffer.Buffer; } } - Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2324,11 +2324,11 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2339,7 +2339,7 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2362,7 +2362,7 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2385,21 +2385,21 @@ window.Buffer = buffer.Buffer; return offset + byteLength }; - Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2408,11 +2408,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2421,11 +2421,11 @@ window.Buffer = buffer.Buffer; return offset + 2 }; - Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2436,12 +2436,12 @@ window.Buffer = buffer.Buffer; return offset + 4 }; - Buffer$k.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$l.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; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2465,11 +2465,11 @@ window.Buffer = buffer.Buffer; return offset + 4 } - Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2481,16 +2481,16 @@ window.Buffer = buffer.Buffer; return offset + 8 } - Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2522,7 +2522,7 @@ window.Buffer = buffer.Buffer; for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2542,7 +2542,7 @@ window.Buffer = buffer.Buffer; // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$k.prototype.fill = function fill (val, start, end, encoding) { + Buffer$l.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2562,7 +2562,7 @@ window.Buffer = buffer.Buffer; if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2591,7 +2591,7 @@ window.Buffer = buffer.Buffer; } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$k(val, encoding).toString()); + : utf8ToBytes(new Buffer$l(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5025,6 +5025,8 @@ window.Buffer = buffer.Buffer; }; }(safeBuffer, safeBuffer.exports)); + var readableBrowser = {exports: {}}; + // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5160,23 +5162,23 @@ window.Buffer = buffer.Buffer; }; var title = 'browser'; var platform = 'browser'; - var browser$5 = true; + var browser$6 = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config = {}; + var config$1 = {}; - function noop() {} + function noop$2() {} - var on = noop; - var addListener = noop; - var once$1 = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; + var on = noop$2; + var addListener = noop$2; + var once$3 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; function binding(name) { throw new Error('process.binding is not supported'); @@ -5224,14 +5226,14 @@ window.Buffer = buffer.Buffer; var process = { nextTick: nextTick, title: title, - browser: browser$5, + browser: browser$6, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, - once: once$1, + once: once$3, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -5243,12 +5245,10 @@ window.Buffer = buffer.Buffer; hrtime: hrtime, platform: platform, release: release, - config: config, + config: config$1, uptime: uptime }; - var readable = {exports: {}}; - var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; @@ -5284,7 +5284,7 @@ window.Buffer = buffer.Buffer; EventEmitter.init.call(this); } events.exports = EventEmitter; - events.exports.once = once; + events.exports.once = once$2; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; @@ -5676,7 +5676,7 @@ window.Buffer = buffer.Buffer; return ret; } - function once(emitter, name) { + function once$2(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); @@ -5727,5490 +5727,6696 @@ window.Buffer = buffer.Buffer; var EventEmitter$1 = events.exports; - var inherits$h; - if (typeof Object.create === 'function'){ - inherits$h = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$h = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + var streamBrowser = events.exports.EventEmitter; + + var _nodeResolve_empty = {}; + + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); + + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + + 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } + + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + var _require$2 = buffer, + Buffer$k = _require$2.Buffer; + + var _require2 = require$$3, + inspect$1 = _require2.inspect; + + var custom = inspect$1 && inspect$1.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$k.prototype.copy.call(src, target, offset); } - var inherits$i = inherits$h; - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString$1(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; } - 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]'; + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$k.alloc(0); + var ret = Buffer$k.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull$1(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$k.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect$1(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); } - } - 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined$1(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } + return BufferList; + }(); - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); } - warned = true; } - return fn.apply(this, arguments); - } - return deprecated; - } + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined$1(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); } else { - debugs[set] = function() {}; + nextTick(emitCloseNT, _this); } - } - 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$1(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined$1(ctx.depth)) ctx.depth = 2; - if (isUndefined$1(ctx.colors)) ctx.colors = false; - if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); + return this; } - // 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 emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); + } - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + 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(self, err) { + self.emit('error', err); + } - function stylizeNoColor(str, styleType) { - return str; + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - function arrayToHash(array) { - var hash = {}; + var errorsBrowser = {}; - array.forEach(function(val, idx) { - hash[val] = true; - }); + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - return hash; - } + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } - 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$1(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== 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$1(ret)) { - ret = formatValue(ctx, ret, recurseTimes); + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); } - return ret; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + return NodeError; + }(Base); - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError$1(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction$1(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate$1(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError$1(value)) { - return formatError(value); + + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); } + } else { + return "of ".concat(thing, " ").concat(String(expected)); } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - var base = '', array = false, braces = ['{', '}']; - // Make Array say that they are Array - if (isArray$2(value)) { - array = true; - braces = ['[', ']']; - } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - // Make functions say that they are functions - if (isFunction$1(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - // Make RegExps say that they are RegExps - if (isRegExp$1(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - // Make dates with properties first say the date - if (isDate$1(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + return str.substring(this_len - search.length, this_len) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - // Make error with message first say the error - if (isError$1(value)) { - base = ' ' + formatError(value); + + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; } + } - if (recurseTimes < 0) { - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; } - ctx.seen.push(value); + var msg; - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } - ctx.seen.pop(); + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + errorsBrowser.codes = codes; - return reduceToSingleString(output, base, braces); + var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - function formatPrimitive(ctx, value) { - if (isUndefined$1(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber$1(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean$1(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull$1(value)) - return ctx.stylize('null', 'null'); - } + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } // Default value - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + + return state.objectMode ? 16 : 16 * 1024; } + var state = { + getHighWaterMark: getHighWaterMark$2 + }; - 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; - } + /** + * Module exports. + */ + var browser$5 = deprecate$1; - 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 + ']'; + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + + function deprecate$1 (fn, msg) { + if (config('noDeprecation')) { + return fn; } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull$1(recurseTimes)) { - str = formatValue(ctx, desc.value, null); + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); } 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'); - } + console.warn(msg); } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined$1(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'); + warned = true; } + return fn.apply(this, arguments); } - return name + ': ' + str; + return deprecated; } + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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]; + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } + var _stream_writable = Writable$2; + // there will be only 2 of these for each stream - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$2(ar) { - return Array.isArray(ar); - } - function isBoolean$1(arg) { - return typeof arg === 'boolean'; - } + function CorkedRequest$1(state) { + var _this = this; - function isNull$1(arg) { - return arg === null; - } + this.next = null; + this.entry = null; - function isNumber$1(arg) { - return typeof arg === 'number'; + this.finish = function () { + onCorkedFinish(_this, state); + }; } + /* */ - function isString$1(arg) { - return typeof arg === 'string'; - } + /**/ - function isUndefined$1(arg) { - return arg === void 0; - } - function isRegExp$1(re) { - return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; - } + var Duplex$4; + /**/ - function isObject$1(arg) { - return typeof arg === 'object' && arg !== null; - } + Writable$2.WritableState = WritableState$1; + /**/ - function isDate$1(d) { - return isObject$1(d) && objectToString$1(d) === '[object Date]'; - } + var internalUtil = { + deprecate: browser$5 + }; + /**/ - function isError$1(e) { - return isObject$1(e) && - (objectToString$1(e) === '[object Error]' || e instanceof Error); - } + /**/ - function isFunction$1(arg) { - return typeof arg === 'function'; - } + var Stream$2 = streamBrowser; + /**/ - function objectToString$1(o) { - return Object.prototype.toString.call(o); - } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; + var Buffer$j = buffer.Buffer; - 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 OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$j.from(chunk); } - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; + function _isUint8Array$1(obj) { + return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; } - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + var destroyImpl$1 = destroy_1; - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + inherits_browser.exports(Writable$2, Stream$2); - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; + function nop$1() {} - var string_decoder = {}; + function WritableState$1(options, stream, isDuplex) { + Duplex$4 = Duplex$4 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - var StringDecoder_1; - // 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. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - var Buffer$j = buffer.Buffer; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - var isBufferEncoding = Buffer$j.isEncoding - || function(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; - } - }; + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + this.finalCalled = false; // drain event flag. - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } + this.needDrain = false; // at the start of calling end() - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + this.ending = false; // when end() has been called, and returned - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$j(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; + this.ended = false; // when 'finish' is emitted + this.finished = false; // has it been destroyed - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$2.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + this.length = 0; // a flag to see when we're in the middle of a write. - charStr += buffer.toString(this.encoding, 0, end); + this.writing = false; // when true all writes will be buffered until .uncork() call - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - // or just emit the charStr - return charStr; - }; + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // See http://en.wikipedia.org/wiki/UTF-8#Description - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + this.writecb = null; // the amount that is being written when _write is called. - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - StringDecoder$2.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + this.prefinished = false; // True if the error was already emitted and should not be thrown again - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - return res; - }; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } + this.autoDestroy = !!options.autoDestroy; // count buffered requests - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; + this.corkedRequestsFree = new CorkedRequest$1(this); } - Readable$2.ReadableState = ReadableState$1; - - var debug$4 = debuglog('stream'); - inherits$i(Readable$2, EventEmitter$1); + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; + while (current) { + out.push(current); + current = current.next; } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState$1(options, stream) { - options = options || {}; + return out; + }; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + (function () { + try { + Object.defineProperty(WritableState$1.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var realHasInstance; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$2, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$2) return false; + return object && object._writableState instanceof WritableState$1; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + function Writable$2(options) { + Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$4; + if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); + this._writableState = new WritableState$1(options, this, isDuplex); // legacy. - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + this.writable = true; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + Stream$2.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + Writable$2.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable$2(options) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. - if (!(this instanceof Readable$2)) return new Readable$2(options); - this._readableState = new ReadableState$1(options, this); + function validChunk$1(stream, state, chunk, cb) { + var er; - // legacy - this.readable = true; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); + } - if (options && typeof options.read === 'function') this._read = options.read; + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } - EventEmitter$1.call(this); + return true; } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$2.prototype.push = function (chunk, encoding) { - var state = this._readableState; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$k.from(chunk, encoding); - encoding = ''; - } + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$j.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return readableAddChunk$1(this, state, chunk, encoding, false); + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop$1; + if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); + } + return ret; }; - // Unshift should *always* be something directly out of read() - Readable$2.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk$1(this, state, chunk, '', true); + Writable$2.prototype.cork = function () { + this._writableState.corked++; }; - Readable$2.prototype.isPaused = function () { - return this._readableState.flowing === false; + Writable$2.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } }; - function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid$1(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - if (!addToFront) state.reading = false; + Object.defineProperty(Writable$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$j.from(chunk, encoding); + } - if (state.needReadable) emitReadable$1(stream); - } - } + return chunk; + } - maybeReadMore$1(stream, state); + Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk$1(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - } else if (!addToFront) { - state.reading = false; } - return needMoreData$1(state); + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); + } + + return ret; } - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData$1(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - // backwards compatibility. - Readable$2.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; - }; + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; - // Don't raise the hwm > 8MB - var MAX_HWM$1 = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM$1) { - n = MAX_HWM$1; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe$1, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe$1(stream, state); } - return n; } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - // you can override either this method, or the async _read(n) below. - Readable$2.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate$1(state); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state) || stream.destroyed; - if (n !== 0) state.emittedReadable = false; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; + if (sync) { + nextTick(afterWrite$1, stream, state, finished, cb); + } else { + afterWrite$1(stream, state, finished, cb); + } } + } + + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. - n = howMuchToRead$1(n, state); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } + } // if there's something in the buffer waiting, then process it - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$4('need readable', doRead); + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); - } + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead$1(nOrig, state); - } + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + buffer.allBuffers = allBuffers; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - if (ret === null) { - state.needReadable = true; - n = 0; + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } + + state.bufferedRequestCount = 0; } else { - state.length -= n; - } + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + if (state.writing) { + break; + } + } - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable$1(this); + if (entry === null) state.lastBufferedRequest = null; } - if (ret !== null) this.emit('data', ret); + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - return ret; + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); }; - function chunkInvalid$1(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + Writable$2.prototype._writev = null; + + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return er; + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable$1(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - function onEofChunk$1(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); } - } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable$1(stream); + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable$1(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); + function prefinish$2(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } } - function emitReadable_$1(stream) { - debug$4('emit readable'); - stream.emit('readable'); - flow$1(stream); - } + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); + if (need) { + prefinish$2(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } } + + return need; } - function maybeReadMore_$1(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } - state.readingMore = false; - } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$2.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; + state.ended = true; + stream.writable = false; + } - Readable$2.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - var doEnd = (!pipeOpts || pipeOpts.end !== false); - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + state.corkedRequestsFree.next = corkReq; + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$4('onunpipe'); - if (readable === src) { - cleanup(); + Object.defineProperty(Writable$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; } - } - function onend() { - debug$4('onend'); - dest.end(); + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; } + }); + Writable$2.prototype.destroy = destroyImpl$1.destroy; + Writable$2.prototype._undestroy = destroyImpl$1.undestroy; - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); + Writable$2.prototype._destroy = function (err, cb) { + cb(err); + }; - var cleanedUp = false; - function cleanup() { - debug$4('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + /**/ - cleanedUp = true; + var objectKeys = Object.keys || function (obj) { + var keys = []; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + for (var key in obj) { + keys.push(key); } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$4('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + return keys; + }; + /**/ - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + var _stream_duplex = Duplex$3; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + var Readable$2 = _stream_readable; - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); - } + var Writable$1 = _stream_writable; - // tell the dest that it's being piped to - dest.emit('pipe', src); + inherits_browser.exports(Duplex$3, Readable$2); - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Writable$1.prototype); + + for (var v$1 = 0; v$1 < keys$1.length; v$1++) { + var method$1 = keys$1[v$1]; + if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; } + } - return dest; - }; + function Duplex$3(options) { + if (!(this instanceof Duplex$3)) return new Duplex$3(options); + Readable$2.call(this, options); + Writable$1.call(this, options); + this.allowHalfOpen = true; - function pipeOnDrain$1(src) { - return function () { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow$1(src); + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend$1); } - }; + } } - Readable$2.prototype.unpipe = function (dest) { - var state = this._readableState; + Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + function onend$1() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + nextTick(onEndNT$1, this); + } - if (!dest) dest = state.pipes; + function onEndNT$1(self) { + self.end(); + } - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; + Object.defineProperty(Duplex$3.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; } + }); - // slow case. multiple pipe destinations. + var string_decoder = {}; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + /**/ - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; + var Buffer$i = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$i.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; } + }; - // try to find the right one. - var i = indexOf$1(state.pipes, dest); - if (i === -1) return this; + 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$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$i.allocUnsafe(nb); + } - dest.emit('unpipe', this); + StringDecoder$2.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 || ''; + }; - return this; + StringDecoder$2.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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; }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$2.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + // 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; + } - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable$1(this); + // 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'; } } } + } - return res; - }; - Readable$2.prototype.addListener = Readable$2.prototype.on; + // 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); + 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; + } - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); + // 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); } - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$2.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$4('resume'); - state.flowing = true; - resume(this, state); + // 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; } - return this; - }; + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + // 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 resume_(stream, state) { - if (!state.reading) { - debug$4('resume read 0'); - stream.read(0); + 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); + } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); + 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; } - Readable$2.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; - }; + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } - function flow$1(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$2.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - var self = this; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - self.push(null); - }); + callback.apply(this, args); + }; + } - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + function noop$1() {} - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$2(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + var writableEnded = stream._writableState && stream._writableState.finished; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$4('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); }; - return self; - }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // exposed for testing purposes only. - Readable$2._fromList = fromList$1; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; + var onerror = function onerror(err) { + callback.call(stream, err); + }; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - return ret; + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; } - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } - ++c; } - list.length -= c; - return ret; } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$k.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; } - break; - } - ++c; - } - list.length -= c; - return ret; + + iter[kHandlePromise](resolve, reject); + }, reject); + }; } - function endReadable$1(stream) { - var state = stream._readableState; + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + next: function next() { + var _this = this; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } + if (error !== null) { + return Promise.reject(error); + } - function forEach$2(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - // A bit simpler than readable streams. - Writable$2.WritableState = WritableState$1; - inherits$i(Writable$2, events.exports.EventEmitter); - function nop() {} + var lastPromise = this[kLastPromise]; + var promise; - function WriteReq$1(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); - function WritableState$1(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); }); - options = options || {}; + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var resolve = iterator[kLastResolve]; - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + var async_iterator = createReadableStreamAsyncIterator$1; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') + }; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + var _stream_readable = Readable$1; + /**/ - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + var Duplex$2; + /**/ - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + Readable$1.ReadableState = ReadableState$1; + /**/ - // a flag to see when we're in the middle of a write. - this.writing = false; + events.exports.EventEmitter; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + /**/ - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite$1(stream, er); - }; + var Stream$1 = streamBrowser; + /**/ - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - // the amount that is being written when _write is called. - this.writelen = 0; + var Buffer$h = buffer.Buffer; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); + } - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - // count buffered requests - this.bufferedRequestCount = 0; + var debugUtil = require$$3; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + var debug$5; + + if (debugUtil && debugUtil.debuglog) { + debug$5 = debugUtil.debuglog('stream'); + } else { + debug$5 = function debug() {}; } + /**/ - WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable$2(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); + var BufferList$1 = buffer_list; - this._writableState = new WritableState$1(options, this); + var destroyImpl = destroy_1; - // legacy. - this.writable = true; + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - if (typeof options.writev === 'function') this._writev = options.writev; - } - events.exports.EventEmitter.call(this); - } + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable$2.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + inherits_browser.exports(Readable$1, Stream$1); - function writeAfterEnd$1(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk$1(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; + function prependListener$1(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + function ReadableState$1(options, stream, isDuplex) { + Duplex$2 = Duplex$2 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - if (typeof cb !== 'function') cb = nop; + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, chunk, encoding, cb); - } + this.buffer = new BufferList$1(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - return ret; - }; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - Writable$2.prototype.cork = function () { - var state = this._writableState; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - state.corked++; - }; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - Writable$2.prototype.uncork = function () { - var state = this._writableState; + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - if (state.corked) { - state.corked--; + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; } - return chunk; } - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer$1(stream, state, chunk, encoding, cb) { - chunk = decodeChunk$1(state, chunk, encoding); - - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + function Readable$1(options) { + Duplex$2 = Duplex$2 || _stream_duplex; + if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - state.length += len; + var isDuplex = this instanceof Duplex$2; + this._readableState = new ReadableState$1(options, this, isDuplex); // legacy - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + this.readable = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - return ret; + Stream$1.call(this); } - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + Object.defineProperty(Readable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + this._readableState.destroyed = value; + } + }); + Readable$1.prototype.destroy = destroyImpl.destroy; + Readable$1.prototype._undestroy = destroyImpl.undestroy; - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + Readable$1.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state); + Readable$1.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; - if (sync) { - /**/ - nextTick(afterWrite$1, stream, state, finished, cb); - /**/ - } else { - afterWrite$1(stream, state, finished, cb); + if (encoding !== state.encoding) { + chunk = Buffer$h.from(chunk, encoding); + encoding = ''; } - } - } - - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; } - } - // if there's something in the buffer waiting, then process it - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); + }; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$5('readableAddChunk', chunk); + var state = stream._readableState; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + var er; + if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); + } else { + addChunk(stream, state, chunk, false); + } } + } else if (!addToFront) { + state.reading = false; + maybeReadMore$1(stream, state); } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - if (entry === null) state.lastBufferedRequest = null; + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable$1(stream); } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; + maybeReadMore$1(stream, state); } - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + function chunkInvalid$1(state, chunk) { + var er; - Writable$2.prototype._writev = null; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + return er; + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable$1(this, state, cb); - }; + Readable$1.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } + var p = this._readableState.buffer.head; + var content = ''; - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } + while (p !== null) { + content += decoder.write(p.data); + p = p.next; } - return need; - } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; - } + this._readableState.buffer.clear(); - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } + var MAX_HWM$1 = 0x40000000; - inherits$i(Duplex$2, Readable$2); + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } - var keys = Object.keys(Writable$2.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; - } - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - Readable$2.call(this, options); - Writable$2.call(this, options); - if (options && options.readable === false) this.readable = false; + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - if (options && options.writable === false) this.writable = false; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend$1); - } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); + if (n <= state.length) return n; // Don't have enough - // the no-half-open enforcer - function onend$1() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + if (!state.ended) { + state.needReadable = true; + return 0; + } - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } + return state.length; + } // you can override either this method, or the async _read(n) below. - function onEndNT(self) { - self.end(); - } - // a transform stream is a readable/writable stream where you do - inherits$i(Transform$4, Duplex$2); + Readable$1.prototype.read = function (n) { + debug$5('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - function TransformState$1(stream) { - this.afterTransform = function (er, data) { - return afterTransform$1(stream, er, data); - }; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$5('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - function afterTransform$1(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + var doRead = state.needReadable; + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - ts.writechunk = null; - ts.writecb = null; + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$5('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - if (data !== null && data !== undefined) stream.push(data); - cb(er); + if (state.ended || state.reading) { + doRead = false; + debug$5('reading or ended', doRead); + } else if (doRead) { + debug$5('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); + if (state.length === 0) state.needReadable = true; // call internal read method - Duplex$2.call(this, options); + this._read(state.highWaterMark); - this._transformState = new TransformState$1(this); + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - // when the writable side finishes, then flush out anything remaining. - var stream = this; + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - if (typeof options.flush === 'function') this._flush = options.flush; + if (nOrig !== n && state.ended) endReadable$1(this); } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done$1(stream, er); - });else done$1(stream); - }); - } - - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$2.prototype.push.call(this, chunk, encoding); + if (ret !== null) this.emit('data', ret); + return ret; }; - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$4.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + function onEofChunk$1(stream, state) { + debug$5('onEofChunk'); + if (state.ended) return; - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } - }; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + state.ended = true; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable$1(stream); } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_$1(stream); + } } - }; + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. - function done$1(stream, er) { - if (er) return stream.emit('error', er); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + function emitReadable$1(stream) { + var state = stream._readableState; + debug$5('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (!state.emittedReadable) { + debug$5('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); + } + } - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + function emitReadable_$1(stream) { + var state = stream._readableState; + debug$5('emitReadable_', state.destroyed, state.length, state.ended); - return stream.push(null); - } + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + + + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow$1(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. - inherits$i(PassThrough$1, Transform$4); - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$4.call(this, options); + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + function maybeReadMore_$1(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$5('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable$1.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); }; - inherits$i(Stream$2, EventEmitter$1); - Stream$2.Readable = Readable$2; - Stream$2.Writable = Writable$2; - Stream$2.Duplex = Duplex$2; - Stream$2.Transform = Transform$4; - Stream$2.PassThrough = PassThrough$1; + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - // Backwards-compat with node 0.4.x - Stream$2.Stream = Stream$2; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + case 1: + state.pipes = [state.pipes, dest]; + break; - function Stream$2() { - EventEmitter$1.call(this); - } + default: + state.pipes.push(dest); + break; + } - Stream$2.prototype.pipe = function(dest, options) { - var source = this; + state.pipesCount += 1; + debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); + function onunpipe(readable, unpipeInfo) { + debug$5('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); } } } - source.on('data', ondata); + function onend() { + debug$5('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } + var ondrain = pipeOnDrain$1(src); dest.on('drain', ondrain); + var cleanedUp = false; - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } + function cleanup() { + debug$5('cleanup'); // cleanup event handlers once the pipe is broken - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - dest.end(); + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } + src.on('data', ondata); - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + function ondata(chunk) { + debug$5('ondata'); + var ret = dest.write(chunk); + debug$5('dest.write', ret); - if (typeof dest.destroy === 'function') dest.destroy(); - } + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$5('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + src.pause(); } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - source.removeListener('end', onend); - source.removeListener('close', onclose); - source.removeListener('error', onerror); + function onerror(er) { + debug$5('onerror', er); + unpipe(); dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - dest.removeListener('close', cleanup); + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - source.on('end', cleanup); - source.on('close', cleanup); + dest.once('close', onclose); - dest.on('close', cleanup); + function onfinish() { + debug$5('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } - dest.emit('pipe', source); + dest.once('finish', onfinish); - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + function unpipe() { + debug$5('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream$2, - Readable: Readable$2, - Writable: Writable$2, - Duplex: Duplex$2, - Transform: Transform$4, - PassThrough: PassThrough$1, - Stream: Stream$2 - }); - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + dest.emit('pipe', src); // start the flow if it hasn't been started already. - var isarray = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; + if (!state.flowing) { + debug$5('pipe resume'); + src.resume(); + } + + return dest; }; - var util$5 = {}; + function pipeOnDrain$1(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$5('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; - // 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. + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow$1(src); + } + }; + } - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - function isArray$1(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; - } - util$5.isArray = isArray$1; + if (state.pipesCount === 0) return this; // just one destination. most common case. - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - util$5.isBoolean = isBoolean; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - function isNull(arg) { - return arg === null; - } - util$5.isNull = isNull; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - function isNullOrUndefined(arg) { - return arg == null; - } - util$5.isNullOrUndefined = isNullOrUndefined; - function isNumber(arg) { - return typeof arg === 'number'; - } - util$5.isNumber = isNumber; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - function isString(arg) { - return typeof arg === 'string'; - } - util$5.isString = isString; + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - util$5.isSymbol = isSymbol; + return this; + } // try to find the right one. - function isUndefined(arg) { - return arg === void 0; - } - util$5.isUndefined = isUndefined; - function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; - } - util$5.isRegExp = isRegExp; + var index = indexOf$1(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - util$5.isObject = isObject; - function isDate(d) { - return objectToString(d) === '[object Date]'; - } - util$5.isDate = isDate; + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); + var state = this._readableState; - function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); - } - util$5.isError = isError; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - function isFunction(arg) { - return typeof arg === 'function'; - } - util$5.isFunction = isFunction; + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$5('on readable', state.length, state.reading); - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - util$5.isPrimitive = isPrimitive; + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } + } - util$5.isBuffer = buffer.Buffer.isBuffer; + return res; + }; - function objectToString(o) { - return Object.prototype.toString.call(o); - } + Readable$1.prototype.addListener = Readable$1.prototype.on; - // 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. + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$1.prototype.removeListener.call(this, ev, fn); - var _stream_readable = Readable$1; + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - /**/ - var isArray = isarray; - /**/ + return res; + }; + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); - /**/ - var Buffer$i = buffer.Buffer; - /**/ + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - Readable$1.ReadableState = ReadableState; + return res; + }; - var EE = events.exports.EventEmitter; + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - /**/ - if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } - var Stream$1 = require$$1; + function nReadingNextTick$1(self) { + debug$5('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. - /**/ - var util$4 = util$5; - util$4.inherits = inherits_browser.exports; - /**/ - var StringDecoder$1; + Readable$1.prototype.resume = function () { + var state = this._readableState; - util$4.inherits(Readable$1, Stream$1); + if (!state.flowing) { + debug$5('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - function ReadableState(options, stream) { - options = options || {}; + state.flowing = !state.readableListening; + resume$1(this, state); + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + state.paused = false; + return this; + }; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); + } + } - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; + function resume_$1(stream, state) { + debug$5('resume', state.reading); - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; + if (!state.reading) { + stream.read(0); + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; + Readable$1.prototype.pause = function () { + debug$5('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug$5('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + this._readableState.paused = true; + return this; + }; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function flow$1(stream) { + var state = stream._readableState; + debug$5('flow', state.flowing); - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + Readable$1.prototype.wrap = function (stream) { + var _this = this; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$5('wrapped end'); - function Readable$1(options) { - if (!(this instanceof Readable$1)) - return new Readable$1(options); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - this._readableState = new ReadableState(options, this); + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$5('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - // legacy - this.readable = true; + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - Stream$1.call(this); - } + var ret = _this.push(chunk); - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$1.prototype.push = function(chunk, encoding) { - var state = this._readableState; + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer$i(chunk, encoding); - encoding = ''; + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); } - } + } // proxy certain important events. - return readableAddChunk(this, state, chunk, encoding, false); - }; - // Unshift should *always* be something directly out of read() - Readable$1.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } + this._read = function (n) { + debug$5('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; - if (state.needReadable) - emitReadable(stream); + return this; + }; - maybeReadMore(stream, state); + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; } - } else if (!addToFront) { - state.reading = false; - } - return needMoreData(state); + return createReadableStreamAsyncIterator(this); + }; } + Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + Readable$1._fromList = fromList$1; + Object.defineProperty(Readable$1.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; } - // backwards compatibility. - Readable$1.prototype.setEncoding = function(enc) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this._readableState.decoder = new StringDecoder$1(enc); - this._readableState.encoding = enc; - }; + function endReadable$1(stream) { + var state = stream._readableState; + debug$5('endReadable', state.endEmitted); - // Don't raise the hwm > 128MB - var MAX_HWM = 0x800000; - function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); } - return n; } - function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; + function endReadableNT$1(state, stream) { + debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - if (state.objectMode) - return n === 0 ? 0 : 1; + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } } + } - if (n <= 0) - return 0; + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); + return from(Readable$1, iterable, opts); + }; + } - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - return n; + return -1; } - // you can override either this method, or the async _read(n) below. - Readable$1.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; + var _stream_transform = Transform$4; - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; + var _require$codes$1 = errorsBrowser.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } + var Duplex$1 = _stream_duplex; - n = howMuchToRead(n, state); + inherits_browser.exports(Transform$4, Duplex$1); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } + function afterTransform$1(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - if (state.length === 0) - endReadable(this); + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } - return ret; + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } + } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); + Duplex$1.call(this, options); + this._transformState = { + afterTransform: afterTransform$1.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; + this._readableState.sync = false; - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; + this.on('prefinish', prefinish$1); + } + + function prefinish$1() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done$1(_this, er, data); + }); + } else { + done$1(this, null, null); } + } + + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$1.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - if (n > 0) - ret = fromList(n, state); - else - ret = null; + Transform$4.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; - if (ret === null) { - state.needReadable = true; - n = 0; + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. - state.length -= n; - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; - return ret; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } }; - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer$i.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; + Transform$4.prototype._destroy = function (err, cb) { + Duplex$1.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done$1(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); } + var _stream_passthrough = PassThrough$1; - function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + var Transform$3 = _stream_transform; - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); + inherits_browser.exports(PassThrough$1, Transform$3); + + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform$3.call(this, options); } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - state.emittedReadable = true; - if (state.sync) - nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } + var eos; - function emitReadable_(stream) { - stream.emit('readable'); + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } + var _require$codes = errorsBrowser.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(function() { - maybeReadMore_(stream, state); - }); - } + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$1.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); - }; + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want - Readable$1.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; + function call(fn) { + fn(); + } - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + function pipe(from, to) { + return from.pipe(to); + } - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - nextTick(endFn); - else - src.once('end', endFn); + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; } - function onend() { - dest.end(); + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); + var pipeline_1 = pipeline; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } + (function (module, exports) { + exports = module.exports = _stream_readable; + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + }(readableBrowser, readableBrowser.exports)); - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$2 = readableBrowser.exports.Transform; + var inherits$i = inherits_browser.exports; + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } + } + function HashBase$2 (blockSize) { + Transform$2.call(this); - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - // tell the dest that it's being piped to - dest.emit('pipe', src); + this._finalized = false; + } - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); + inherits$i(HashBase$2, Transform$2); - state.flowing = true; - nextTick(function() { - flow(src); - }); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - return dest; + callback(error); }; - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; - } - - function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; } - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes); - else - forEach$1(state.pipes, write); + callback(error); + }; - src.emit('data', chunk); + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; } - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; - } - - function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } - } + return this + }; + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - Readable$1.prototype.unpipe = function(dest) { - var state = this._readableState; + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - if (!dest) - dest = state.pipes; + return digest + }; - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - // slow case. multiple pipe destinations. + var hashBase = HashBase$2; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; + var inherits$h = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } + var ARRAY16$1 = new Array(16); - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; + function MD5$2 () { + HashBase$1.call(this, 64); - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } - dest.emit('unpipe', this); + inherits$h(MD5$2, HashBase$1); - return this; - }; + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$1.prototype.on = function(ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this); - } - } - } + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - return res; - }; - Readable$1.prototype.addListener = Readable$1.prototype.on; + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$1.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); - }; + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - Readable$1.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; }; - function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream$1.prototype.pipe; - stream.on = stream.addListener = Stream$1.prototype.on; - - stream.on('readable', function() { - readable = true; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } - stream.pause = function() { - paused = true; - this.emit('pause'); - }; + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } - stream.resume = function() { - paused = false; - if (readable) - nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - // now make it start, just in case it hadn't already. - stream.emit('readable'); + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$1.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } + var md5_js = MD5$2; - self.push(null); - }); + var Buffer$e = buffer.Buffer; + var inherits$g = inherits_browser.exports; + var HashBase = hashBase; - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); + var ARRAY16 = new Array(16); - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; + var zl = [ + 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 ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + var zr = [ + 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 + ]; - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } + var sl = [ + 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 + ]; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$1(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + var sr = [ + 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 + ]; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - return self; - }; + function RIPEMD160$3 () { + HashBase.call(this, 64); + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } + inherits$g(RIPEMD160$3, HashBase); - // exposed for testing purposes only. - Readable$1._fromList = fromList; + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer$i.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer$i(n); + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - c += cpy; - } - } + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; - if (!state.endEmitted && state.calledRead) { - state.ended = true; - nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) } - function forEach$1 (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } - function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } - // 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. + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - // a duplex stream is just a stream that is both readable and writable. - // Since JS doesn't have multiple prototypal inheritance, this class - // prototypally inherits from Readable, and then parasitically from - // Writable. + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } - var _stream_duplex = Duplex$1; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } - /**/ - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; - }; - /**/ + var ripemd160$2 = RIPEMD160$3; + var sha_js = {exports: {}}; - /**/ - var util$3 = util$5; - util$3.inherits = inherits_browser.exports; - /**/ + var Buffer$d = safeBuffer.exports.Buffer; - var Readable = _stream_readable; - var Writable$1 = _stream_writable; + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } - util$3.inherits(Duplex$1, Readable); + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } - forEach(objectKeys(Writable$1.prototype), function(method) { - if (!Duplex$1.prototype[method]) - Duplex$1.prototype[method] = Writable$1.prototype[method]; - }); + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - function Duplex$1(options) { - if (!(this instanceof Duplex$1)) - return new Duplex$1(options); + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - Readable.call(this, options); - Writable$1.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); - } - - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(this.end.bind(this)); - } + accum += remainder; + offset += remainder; - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + if ((accum % blockSize) === 0) { + this._update(block); + } } - } - - // 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. - // A bit simpler than readable streams. - // Implement an async ._write(chunk, cb), and it'll handle all - // the drain event emission and buffering. - - var _stream_writable = Writable; - - /**/ - var Buffer$h = buffer.Buffer; - /**/ - - Writable.WritableState = WritableState; - - - /**/ - var util$2 = util$5; - util$2.inherits = inherits_browser.exports; - /**/ - - var Stream = require$$1; + this._len += length; + return this + }; - util$2.inherits(Writable, Stream); + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - } + this._block[rem] = 0x80; - function WritableState(options, stream) { - options = options || {}; + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var bits = this._len * 8; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + this._update(this._block); + var hash = this._hash(); - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + return enc ? hash.toString(enc) : hash + }; - // a flag to see when we're in the middle of a write. - this.writing = false; + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var hash$3 = Hash$7; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + var inherits$f = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - // the amount that is being written when _write is called. - this.writelen = 0; + var W$5 = new Array(80); - this.buffer = []; + function Sha () { + this.init(); + this._w = W$5; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + Hash$6.call(this, 64, 56); } - function Writable(options) { - var Duplex = _stream_duplex; - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; + inherits$f(Sha, Hash$6); - Stream.call(this); - } + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); + return this }; + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) + } - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(function() { - cb(er); - }); + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) } - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer$h.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + Sha.prototype._update = function (M) { + var W = this._w; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - if (typeof cb !== 'function') - cb = function() {}; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } - return ret; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer$h(chunk, encoding); - } - return chunk; - } + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - state.length += len; + return H + }; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + var sha$4 = Sha; - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - return ret; - } + var inherits$e = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - function onwriteError(stream, state, sync, er, cb) { - if (sync) - nextTick(function() { - cb(er); - }); - else - cb(er); + var W$4 = new Array(80); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + function Sha1 () { + this.init(); + this._w = W$4; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + Hash$5.call(this, 64, 56); } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + inherits$e(Sha1, Hash$5); - onwriteStateUpdate(state); + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); + return this + }; - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - if (sync) { - nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } + function rotl5 (num) { + return (num << 5) | (num >>> 27) } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); + function rotl30 (num) { + return (num << 30) | (num >>> 2) } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } + Sha1.prototype._update = function (M) { + var W = this._w; - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - doWrite(stream, state, len, chunk, encoding, cb); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; } - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } - - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); + return H }; + var sha1$1 = Sha1; - function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); - } - - function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; - } + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - // 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 inherits$d = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; + var K$2 = [ + 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 + ]; - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. + var W$3 = new Array(64); - var _stream_transform = Transform$3; + function Sha256$1 () { + this.init(); - var Duplex = _stream_duplex; + this._w = W$3; // new Array(64) - /**/ - var util$1 = util$5; - util$1.inherits = inherits_browser.exports; - /**/ + Hash$4.call(this, 64, 56); + } - util$1.inherits(Transform$3, Duplex); + inherits$d(Sha256$1, Hash$4); + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; + return this + }; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; + function ch (x, y, z) { + return z ^ (x & (y ^ z)) } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - if (data !== null && data !== undefined) - stream.push(data); + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } - if (cb) - cb(er); + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - function Transform$3(options) { - if (!(this instanceof Transform$3)) - return new Transform$3(options); + Sha256$1.prototype._update = function (M) { + var W = this._w; - Duplex.call(this, options); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - this._transformState = new TransformState(options, this); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - // when the writable side finishes, then flush out anything remaining. - var stream = this; + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); - } + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - Transform$3.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$3.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); + return H }; - Transform$3.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } + var sha256$2 = Sha256$1; + + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits$c = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; + + var W$2 = new Array(64); + + function Sha224 () { + this.init(); + + this._w = W$2; // new Array(64) + + Hash$3.call(this, 64, 56); + } + + inherits$c(Sha224, Sha256); + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; + + return this }; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$3.prototype._read = function(n) { - var ts = this._transformState; + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H }; + var sha224 = Sha224; - function done(stream, er) { - if (er) - return stream.emit('error', er); + var inherits$b = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - stream._readableState; - var ts = stream._transformState; + var K$1 = [ + 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 + ]; - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); + var W$1 = new Array(160); - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + function Sha512 () { + this.init(); + this._w = W$1; - return stream.push(null); + Hash$2.call(this, 128, 112); } - // 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. + inherits$b(Sha512, Hash$2); - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; - var _stream_passthrough = PassThrough; + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; - var Transform$2 = _stream_transform; + return this + }; - /**/ - var util = util$5; - util.inherits = inherits_browser.exports; - /**/ + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - util.inherits(PassThrough, Transform$2); + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - Transform$2.call(this, options); + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - (function (module, exports) { - var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify - exports = module.exports = _stream_readable; - exports.Stream = Stream; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - }(readable, readable.exports)); + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - var Buffer$g = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$g = inherits_browser.exports; + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) } - function HashBase$2 (blockSize) { - Transform$1.call(this); + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - this._block = Buffer$g.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + Sha512.prototype._update = function (M) { + var W = this._w; - this._finalized = false; - } + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - inherits$g(HashBase$2, Transform$1); + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - callback(error); - }; + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - callback(error); - }; + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; + W[i] = Wih; + W[i + 1] = Wil; } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - return this - }; + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - return digest + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } + + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; }; - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); + + return H }; - var hashBase = HashBase$2; + var sha512 = Sha512; - var inherits$f = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + var inherits$a = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - var ARRAY16$1 = new Array(16); + var W = new Array(160); - function MD5$2 () { - HashBase$1.call(this, 64); + function Sha384 () { + this.init(); + this._w = W; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; + Hash$1.call(this, 128, 112); } - inherits$f(MD5$2, HashBase$1); + inherits$a(Sha384, SHA512$2); - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + return this + }; - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H + }; + + var sha384 = Sha384; + + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() + }; + + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; + + var sha$3 = sha_js.exports; + + var inherits$8; + if (typeof Object.create === 'function'){ + inherits$8 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$8 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$9 = inherits$8; + + var formatRegExp = /%[sdj%]/g; + function format(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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, 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 + _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); + } + + // 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 !== 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 length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + 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()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(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); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + Readable.ReadableState = ReadableState; + + var debug$4 = debuglog('stream'); + inherits$9(Readable, EventEmitter$1); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter$1.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$l.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - // produce result - var buffer = Buffer$f.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); } - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } } - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + function emitReadable_(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow(stream); } - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } } - var md5_js = MD5$2; + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } - var Buffer$e = buffer.Buffer; - var inherits$e = inherits_browser.exports; - var HashBase = hashBase; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; - var ARRAY16 = new Array(16); + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var zl = [ - 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 - ]; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var zr = [ - 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 doEnd = (!pipeOpts || pipeOpts.end !== false); - var sl = [ - 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 endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - var sr = [ - 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 - ]; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + function onend() { + debug$4('onend'); + dest.end(); + } - function RIPEMD160$3 () { - HashBase.call(this, 64); + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; } - inherits$e(RIPEMD160$3, HashBase); + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + if (!dest) dest = state.pipes; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } } + } - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); } + return this; + }; - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; }; - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + function flow(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + return self; }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } + // exposed for testing purposes only. + Readable._fromList = fromList; - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + return ret; } - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - var ripemd160$2 = RIPEMD160$3; + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$l.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } - var sha_js = {exports: {}}; + function endReadable(stream) { + var state = stream._readableState; - var Buffer$d = safeBuffer.exports.Buffer; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); } + } - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - if ((accum % blockSize) === 0) { - this._update(block); - } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } + return -1; + } - this._len += length; - return this - }; + // A bit simpler than readable streams. + Writable.WritableState = WritableState; + inherits$9(Writable, events.exports.EventEmitter); - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + function nop() {} - this._block[rem] = 0x80; + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - var bits = this._len * 8; + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - this._update(this._block); - var hash = this._hash(); + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - return enc ? hash.toString(enc) : hash - }; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - var hash$3 = Hash$7; + // a flag to see when we're in the middle of a write. + this.writing = false; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + // when true all writes will be buffered until .uncork() call + this.corked = 0; - var inherits$d = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var W$5 = new Array(80); + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - function Sha () { - this.init(); - this._w = W$5; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - Hash$6.call(this, 64, 56); - } + // the amount that is being written when _write is called. + this.writelen = 0; - inherits$d(Sha, Hash$6); + this.bufferedRequest = null; + this.lastBufferedRequest = null; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - return this - }; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } + // count buffered requests + this.bufferedRequestCount = 0; - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); } - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + return out; }; + function Writable(options) { - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H - }; + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - var sha$4 = Sha; + this._writableState = new WritableState(options, this); - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + // legacy. + this.writable = true; - var inherits$c = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + if (typeof options.writev === 'function') this._writev = options.writev; + } - var W$4 = new Array(80); + events.exports.EventEmitter.call(this); + } - function Sha1 () { - this.init(); - this._w = W$4; + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; - Hash$5.call(this, 64, 56); + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); } - inherits$c(Sha1, Hash$5); + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - return this - }; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } + if (typeof cb !== 'function') cb = nop; - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + return ret; + }; - Sha1.prototype._update = function (M) { - var W = this._w; + Writable.prototype.cork = function () { + var state = this._writableState; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + state.corked++; + }; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + Writable.prototype.uncork = function () { + var state = this._writableState; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + if (state.corked) { + state.corked--; - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } - - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; }; - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; + } - return H - }; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); - var sha1$1 = Sha1; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + state.length += len; - var inherits$b = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - var K$2 = [ - 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 - ]; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - var W$3 = new Array(64); + return ret; + } - function Sha256$1 () { - this.init(); + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - this._w = W$3; // new Array(64) + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); - Hash$4.call(this, 64, 56); + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - inherits$b(Sha256$1, Hash$4); + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - return this - }; + onwriteStateUpdate(state); - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - Sha256$1.prototype._update = function (M) { - var W = this._w; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); }; - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); + Writable.prototype._writev = null; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - return H + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); }; - var sha256$2 = Sha256$1; + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } - var inherits$a = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } - var W$2 = new Array(64); + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } - function Sha224 () { - this.init(); + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - this._w = W$2; // new Array(64) + this.next = null; + this.entry = null; - Hash$3.call(this, 64, 56); + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; } - inherits$a(Sha224, Sha256); + inherits$9(Duplex, Readable); - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - return this - }; + Readable.call(this, options); + Writable.call(this, options); - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + if (options && options.readable === false) this.readable = false; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + if (options && options.writable === false) this.writable = false; - return H - }; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - var sha224 = Sha224; + this.once('end', onend); + } - var inherits$9 = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - var K$1 = [ - 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 - ]; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } - var W$1 = new Array(160); + function onEndNT(self) { + self.end(); + } - function Sha512 () { - this.init(); - this._w = W$1; + // a transform stream is a readable/writable stream where you do + inherits$9(Transform$1, Duplex); - Hash$2.call(this, 128, 112); + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; } - inherits$9(Sha512, Hash$2); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + var cb = ts.writecb; - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - return this - }; + ts.writechunk = null; + ts.writecb = null; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + if (data !== null && data !== undefined) stream.push(data); - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + cb(er); - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } + function Transform$1(options) { + if (!(this instanceof Transform$1)) return new Transform$1(options); - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + Duplex.call(this, options); - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + this._transformState = new TransformState(this); - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); } - Sha512.prototype._update = function (M) { - var W = this._w; + Transform$1.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$1.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + Transform$1.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$1.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + }; - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + function done(stream, er) { + if (er) return stream.emit('error', er); - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - W[i] = Wih; - W[i + 1] = Wil; - } + return stream.push(null); + } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + inherits$9(PassThrough, Transform$1); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + Transform$1.call(this, options); + } - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + inherits$9(Stream, EventEmitter$1); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform$1; + Stream.PassThrough = PassThrough; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + function Stream() { + EventEmitter$1.call(this); + } - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } } - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + source.on('data', ondata); - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + dest.on('drain', ondrain); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - var sha512 = Sha512; + dest.end(); + } - var inherits$8 = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; - var W = new Array(160); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - function Sha384 () { - this.init(); - this._w = W; + if (typeof dest.destroy === 'function') dest.destroy(); + } - Hash$1.call(this, 128, 112); - } + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - inherits$8(Sha384, SHA512$2); + source.on('error', onerror); + dest.on('error', onerror); - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + source.removeListener('end', onend); + source.removeListener('close', onclose); - return this - }; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + dest.removeListener('close', cleanup); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; + source.on('end', cleanup); + source.on('close', cleanup); - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + dest.on('close', cleanup); - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + dest.emit('pipe', source); - return new Algorithm() + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform$1, + PassThrough: PassThrough, + Stream: Stream + }); - var sha$3 = sha_js.exports; + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); var Buffer$6 = safeBuffer.exports.Buffer; var Transform = require$$1.Transform; @@ -11532,7 +12738,7 @@ window.Buffer = buffer.Buffer; var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$k.alloc(1 + paths.length * 4); + var buffer = Buffer$l.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -23245,16 +24451,16 @@ window.Buffer = buffer.Buffer; const createHmac = browser$2; - const ONE1 = Buffer$k.alloc(1, 1); - const ZERO1 = Buffer$k.alloc(1, 0); + const ONE1 = Buffer$l.alloc(1, 1); + const ZERO1 = Buffer$l.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$k.alloc(32, 0); - let v = Buffer$k.alloc(32, 1); + let k = Buffer$l.alloc(32, 0); + let v = Buffer$l.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -23311,9 +24517,9 @@ window.Buffer = buffer.Buffer; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$k.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$l.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -23385,9 +24591,9 @@ window.Buffer = buffer.Buffer; } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -23477,7 +24683,7 @@ window.Buffer = buffer.Buffer; return dt } - function sign$1 (hash, x) { + function sign (hash, x) { return __sign(hash, x) } @@ -23519,7 +24725,7 @@ window.Buffer = buffer.Buffer; s = n.sub(s); } - const buffer = Buffer$k.allocUnsafe(64); + const buffer = Buffer$l.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -23584,7 +24790,7 @@ window.Buffer = buffer.Buffer; pointMultiply, privateAdd, privateSub, - sign: sign$1, + sign, signWithEntropy, verify }; @@ -24104,7 +25310,7 @@ window.Buffer = buffer.Buffer; } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$k(compressed ? 34 : 33); + var result = new Buffer$l(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -24223,7 +25429,7 @@ window.Buffer = buffer.Buffer; const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$k.allocUnsafe(78); + const buffer = Buffer$l.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -24257,7 +25463,7 @@ window.Buffer = buffer.Buffer; derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$k.allocUnsafe(37); + const data = Buffer$l.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -24337,7 +25543,7 @@ window.Buffer = buffer.Buffer; } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$l.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -24429,7 +25635,7 @@ window.Buffer = buffer.Buffer; if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -24536,7 +25742,7 @@ window.Buffer = buffer.Buffer; function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$k.allocUnsafe(size); + const buffer = Buffer$l.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -24731,18 +25937,18 @@ window.Buffer = buffer.Buffer; const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$k.alloc(1, 0); + const ZERO$1 = Buffer$l.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$k.alloc(32, 0); + const buffer = Buffer$l.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -24756,7 +25962,7 @@ window.Buffer = buffer.Buffer; const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$k.concat([r, s], 64); + const signature = Buffer$l.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -24771,11 +25977,11 @@ window.Buffer = buffer.Buffer; const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$k.allocUnsafe(1); + const hashTypeBuffer = Buffer$l.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -25164,7 +26370,7 @@ window.Buffer = buffer.Buffer; // opcode return accum + 1; }, 0.0); - const buffer = Buffer$k.allocUnsafe(bufferSize); + const buffer = Buffer$l.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -25249,7 +26455,7 @@ window.Buffer = buffer.Buffer; if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$k.from(chunkStr, 'hex'); + return Buffer$l.from(chunkStr, 'hex'); }), ); } @@ -25259,7 +26465,7 @@ window.Buffer = buffer.Buffer; typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -25667,7 +26873,7 @@ window.Buffer = buffer.Buffer; const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -25706,7 +26912,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -25825,7 +27031,7 @@ window.Buffer = buffer.Buffer; // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -25861,7 +27067,7 @@ window.Buffer = buffer.Buffer; return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -26137,7 +27343,7 @@ window.Buffer = buffer.Buffer; const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$k.alloc(0); + const EMPTY_BUFFER$1 = Buffer$l.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -26165,7 +27371,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -26205,7 +27411,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26269,7 +27475,7 @@ window.Buffer = buffer.Buffer; const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$k.alloc(0); + const EMPTY_BUFFER = Buffer$l.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -26319,7 +27525,7 @@ window.Buffer = buffer.Buffer; return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; }); const _rchunks = lazy.value(() => { @@ -26384,7 +27590,7 @@ window.Buffer = buffer.Buffer; }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26507,13 +27713,13 @@ window.Buffer = buffer.Buffer; return { version: result.words[0], prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -26669,7 +27875,7 @@ window.Buffer = buffer.Buffer; return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$l.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -26871,7 +28077,7 @@ window.Buffer = buffer.Buffer; } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$k.allocUnsafe(buffer.length); + const clone = Buffer$l.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -26994,17 +28200,17 @@ window.Buffer = buffer.Buffer; }, 0) ); } - const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$k.from( + const ZERO = Buffer$l.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$k.from( + const ONE = Buffer$l.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -27066,7 +28272,7 @@ window.Buffer = buffer.Buffer; return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -27226,7 +28432,7 @@ window.Buffer = buffer.Buffer; txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -27236,13 +28442,13 @@ window.Buffer = buffer.Buffer; types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$k.from([]); + let tbuffer = Buffer$l.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -27255,7 +28461,7 @@ window.Buffer = buffer.Buffer; (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -27269,7 +28475,7 @@ window.Buffer = buffer.Buffer; const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$k.allocUnsafe(txOutsSize); + tbuffer = Buffer$l.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -27281,13 +28487,13 @@ window.Buffer = buffer.Buffer; inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -27305,7 +28511,7 @@ window.Buffer = buffer.Buffer; } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -27327,7 +28533,7 @@ window.Buffer = buffer.Buffer; this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -27389,7 +28595,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$k.concat([left, right]); + var data = Buffer$l.concat([left, right]); results[j] = digestFn(data); } @@ -27456,12 +28662,12 @@ window.Buffer = buffer.Buffer; return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$k.from(hex, 'hex')); + return Block.fromBuffer(Buffer$l.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$k.alloc(32, 0); + const target = Buffer$l.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -27476,7 +28682,7 @@ window.Buffer = buffer.Buffer; const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -27488,18 +28694,18 @@ window.Buffer = buffer.Buffer; // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$k && result.length === 32)) return null; + if (!(result instanceof Buffer$l && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$k && + this.witnessCommit instanceof Buffer$l && this.witnessCommit.length === 32 ) return true; @@ -27535,7 +28741,7 @@ window.Buffer = buffer.Buffer; } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -27712,10 +28918,10 @@ window.Buffer = buffer.Buffer; } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$k.concat([head, data.extendedPubkey]); + const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$l.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -27764,7 +28970,7 @@ window.Buffer = buffer.Buffer; const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -27785,7 +28991,7 @@ window.Buffer = buffer.Buffer; } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -27817,7 +29023,7 @@ window.Buffer = buffer.Buffer; } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -27852,7 +29058,7 @@ window.Buffer = buffer.Buffer; nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -27895,9 +29101,9 @@ window.Buffer = buffer.Buffer; } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$k.concat([head, pSig.pubkey]), + key: Buffer$l.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -27949,10 +29155,10 @@ window.Buffer = buffer.Buffer; } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$k.from(data, 'utf8'), + value: Buffer$l.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -27981,8 +29187,8 @@ window.Buffer = buffer.Buffer; } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$k.allocUnsafe(4); + const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$l.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -28015,7 +29221,7 @@ window.Buffer = buffer.Buffer; } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -28101,8 +29307,8 @@ window.Buffer = buffer.Buffer; tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$k.from([0])); - return Buffer$k.concat(buffers); + buffers.push(Buffer$l.from([0])); + return Buffer$l.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -28110,7 +29316,7 @@ window.Buffer = buffer.Buffer; const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$k.allocUnsafe( + const buffer = Buffer$l.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -28174,12 +29380,12 @@ window.Buffer = buffer.Buffer; function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -28235,10 +29441,10 @@ window.Buffer = buffer.Buffer; return data; } function encode(data) { - const head = Buffer$k.from([TYPE_BYTE]); - const key = Buffer$k.concat([head, data.pubkey]); + const head = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$l.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28318,7 +29524,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$l.from([TYPE_BYTE]); return { key, value: data, @@ -28355,7 +29561,7 @@ window.Buffer = buffer.Buffer; return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$l.from([TYPE_BYTE]); return { key, value: data, @@ -28564,7 +29770,7 @@ window.Buffer = buffer.Buffer; } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$k.from([keyNum]))) { + if (!keyBuf.equals(Buffer$l.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -28783,13 +29989,13 @@ window.Buffer = buffer.Buffer; const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$k.from([0])] + ? [Buffer$l.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$k.allocUnsafe(5); + const header = Buffer$l.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$k.concat( + return Buffer$l.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -29083,11 +30289,11 @@ window.Buffer = buffer.Buffer; }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$l.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$l.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -29307,11 +30513,11 @@ window.Buffer = buffer.Buffer; dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$l.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$l.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -29835,7 +31041,7 @@ window.Buffer = buffer.Buffer; * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -29860,7 +31066,7 @@ window.Buffer = buffer.Buffer; } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -30035,7 +31241,7 @@ window.Buffer = buffer.Buffer; } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -30399,14 +31605,14 @@ window.Buffer = buffer.Buffer; return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$k.allocUnsafe(0); + let buffer = Buffer$l.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); + buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); + buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -30915,7 +32121,7 @@ window.Buffer = buffer.Buffer; const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$k.from('aa21a9ed', 'hex'); + const HEADER = Buffer$l.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -30931,7 +32137,7 @@ window.Buffer = buffer.Buffer; }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$k.allocUnsafe(36); + const buffer = Buffer$l.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -31207,7 +32413,7 @@ window.Buffer = buffer.Buffer; // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -34947,7 +36153,7 @@ window.Buffer = buffer.Buffer; this.bufs = []; } BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$k.alloc(alloc); + var b = Buffer$l.alloc(alloc); fn(b); this.bufs.push(b); }; @@ -34967,14 +36173,14 @@ window.Buffer = buffer.Buffer; this.bufs.push(varuintBitcoin.encode(i)); }; BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$k.from(slice)); + this.bufs.push(Buffer$l.from(slice)); }; BufferWriter.prototype.writeVarSlice = function (slice) { this.writeVarInt(slice.length); this.writeSlice(slice); }; BufferWriter.prototype.buffer = function () { - return Buffer$k.concat(this.bufs); + return Buffer$l.concat(this.bufs); }; return BufferWriter; }()); @@ -35116,9 +36322,9 @@ window.Buffer = buffer.Buffer; p2pkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); + buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); return { scriptPubKey: buf.buffer() }; }; p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { @@ -35145,7 +36351,7 @@ window.Buffer = buffer.Buffer; var xonlyPubkey = pubkey.slice(1); // x-only pubkey var buf = new BufferWriter(); var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen buf.writeSlice(outputKey); return { scriptPubKey: buf.buffer() }; }; @@ -35168,8 +36374,8 @@ window.Buffer = buffer.Buffer; p2tr.prototype.hashTapTweak = function (x) { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$k.concat([h, h, x])); + var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$l.concat([h, h, x])); }; /** * Calculates a taproot output key from an internal key. This output key will be @@ -35188,13 +36394,13 @@ window.Buffer = buffer.Buffer; // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$k.concat([ - Buffer$k.from([0x02]), + var evenEcdsaPubkey = Buffer$l.concat([ + Buffer$l.from([0x02]), internalPubkey, ]); var tweak = this.hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. var outputSchnorrKey = outputEcdsaKey.slice(1); // Create address @@ -35211,7 +36417,7 @@ window.Buffer = buffer.Buffer; var buf = new BufferWriter(); var redeemScript = this.createRedeemScript(pubkey); var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; @@ -35241,7 +36447,7 @@ window.Buffer = buffer.Buffer; }; p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { var pubkeyHash = hashPublicKey(pubkey); - return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); + return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); }; return p2wpkhWrapped; }(SingleKeyAccount)); @@ -35253,7 +36459,7 @@ window.Buffer = buffer.Buffer; p2wpkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); buf.writeSlice(pubkeyHash); return { scriptPubKey: buf.buffer() }; }; @@ -35334,7 +36540,7 @@ window.Buffer = buffer.Buffer; var n = leaves.length; if (n == 0) { return { - root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), + root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), leaves: [] }; } @@ -35354,16 +36560,16 @@ window.Buffer = buffer.Buffer; return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; }; Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); + return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); }; return Merkle; }()); function hashLeaf(buf, hashFunction) { if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$k.from([0]), buf, hashFunction); + return hashConcat(Buffer$l.from([0]), buf, hashFunction); } function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$k.concat([bufA, bufB])); + return hashFunction(Buffer$l.concat([bufA, bufB])); } var Node = /** @class */ (function () { function Node(left, right, hash) { @@ -35428,13 +36634,13 @@ window.Buffer = buffer.Buffer; }; WalletPolicy.prototype.serialize = function () { var keyBuffers = this.keys.map(function (k) { - return Buffer$k.from(k, "ascii"); + return Buffer$l.from(k, "ascii"); }); var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); var buf = new BufferWriter(); buf.writeUInt8(0x01); // wallet type (policy map) buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); + buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); return buf.buffer(); }; @@ -35457,7 +36663,7 @@ window.Buffer = buffer.Buffer; tx.writeUInt32(psbt.getGlobalTxVersion()); var isSegwit = !!psbt.getInputWitnessUtxo(0); if (isSegwit) { - tx.writeSlice(Buffer$k.from([0, 1])); + tx.writeSlice(Buffer$l.from([0, 1])); } var inputCount = psbt.getGlobalInputCount(); tx.writeVarInt(inputCount); @@ -35465,7 +36671,7 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < inputCount; i++) { tx.writeSlice(psbt.getInputPreviousTxid(i)); tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); tx.writeUInt32(psbt.getInputSequence(i)); if (isSegwit) { witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); @@ -35541,7 +36747,7 @@ window.Buffer = buffer.Buffer; psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { __extends$3(NoSuchEntry, _super); function NoSuchEntry() { @@ -35767,11 +36973,11 @@ window.Buffer = buffer.Buffer; }); }; PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); + from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); }; PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); + buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); serializeMap(buf, this.globalMap); this.inputMaps.forEach(function (map) { serializeMap(buf, map); @@ -35815,17 +37021,17 @@ window.Buffer = buffer.Buffer; var result = []; map.forEach(function (_v, k) { if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$k.from(k.substring(2), "hex")); + result.push(Buffer$l.from(k.substring(2), "hex")); } }); return result; }; PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); + var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); return keyTypes.some(function (k) { return k == keyType; }); }; PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$k.from([])); + var key = new Key(keyType, Buffer$l.from([])); this.globalMap.set(key.toString(), value); }; PsbtV2.prototype.getGlobal = function (keyType) { @@ -35911,7 +37117,7 @@ window.Buffer = buffer.Buffer; throw new NoSuchEntry(key.toString()); } // Make sure to return a copy, to protect the underlying data. - return Buffer$k.from(value); + return Buffer$l.from(value); } var Key = /** @class */ (function () { function Key(keyType, keyData) { @@ -35950,25 +37156,25 @@ window.Buffer = buffer.Buffer; function serializeMap(buf, map) { for (var k in map.keys) { var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); + var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); keyPair.serialize(buf); } buf.writeUInt8(0); } function b() { - return Buffer$k.from([]); + return Buffer$l.from([]); } function set(map, keyType, keyData, value) { var key = new Key(keyType, keyData); map.set(key.toString(), value); } function uint32LE(n) { - var b = Buffer$k.alloc(4); + var b = Buffer$l.alloc(4); b.writeUInt32LE(n, 0); return b; } function uint64LE(n) { - var b = Buffer$k.alloc(8); + var b = Buffer$l.alloc(8); b.writeBigUInt64LE(BigInt(n), 0); return b; } @@ -36103,7 +37309,7 @@ window.Buffer = buffer.Buffer; } else if (data.length <= 256 * 256) { buf.writeUInt8(77); - var b = Buffer$k.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16LE(data.length, 0); buf.writeSlice(b); } @@ -36130,18 +37336,18 @@ window.Buffer = buffer.Buffer; } function createVarint(value) { if (value < 0xfd) { - var buffer_1 = Buffer$k.alloc(1); + var buffer_1 = Buffer$l.alloc(1); buffer_1[0] = value; return buffer_1; } if (value <= 0xffff) { - var buffer_2 = Buffer$k.alloc(3); + var buffer_2 = Buffer$l.alloc(3); buffer_2[0] = 0xfd; buffer_2[1] = value & 0xff; buffer_2[2] = (value >> 8) & 0xff; return buffer_2; } - var buffer = Buffer$k.alloc(5); + var buffer = Buffer$l.alloc(5); buffer[0] = 0xfe; buffer[1] = value & 0xff; buffer[2] = (value >> 8) & 0xff; @@ -36157,11 +37363,11 @@ window.Buffer = buffer.Buffer; */ function serializeTransactionOutputs(_a) { var outputs = _a.outputs; - var outputBuffer = Buffer$k.alloc(0); + var outputBuffer = Buffer$l.alloc(0); if (typeof outputs !== "undefined") { - outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); + outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); outputs.forEach(function (output) { - outputBuffer = Buffer$k.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, output.amount, createVarint(output.script.length), @@ -36175,18 +37381,18 @@ window.Buffer = buffer.Buffer; if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$k.alloc(0); + var inputBuffer = Buffer$l.alloc(0); var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; transaction.inputs.forEach(function (input) { inputBuffer = isDecred || isBech32 - ? Buffer$k.concat([ + ? Buffer$l.concat([ inputBuffer, input.prevout, - Buffer$k.from([0x00]), + Buffer$l.from([0x00]), input.sequence, ]) - : Buffer$k.concat([ + : Buffer$l.concat([ inputBuffer, input.prevout, createVarint(input.script.length), @@ -36197,19 +37403,19 @@ window.Buffer = buffer.Buffer; var outputBuffer = serializeTransactionOutputs(transaction); if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$k.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, - (useWitness && transaction.witness) || Buffer$k.alloc(0), + (useWitness && transaction.witness) || Buffer$l.alloc(0), transaction.locktime, - transaction.nExpiryHeight || Buffer$k.alloc(0), - transaction.extraData || Buffer$k.alloc(0), + transaction.nExpiryHeight || Buffer$l.alloc(0), + transaction.extraData || Buffer$l.alloc(0), ]); } - return Buffer$k.concat([ + return Buffer$l.concat([ transaction.version, - timestamp ? timestamp : Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), + timestamp ? timestamp : Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), createVarint(transaction.inputs.length), inputBuffer, outputBuffer, @@ -36347,7 +37553,7 @@ window.Buffer = buffer.Buffer; case 2: address = _c.sent(); components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); + uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); return [2 /*return*/, { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, @@ -36390,7 +37596,7 @@ window.Buffer = buffer.Buffer; masterFingerprint = _a.sent(); policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; } }); }); @@ -36459,7 +37665,7 @@ window.Buffer = buffer.Buffer; i++; return [3 /*break*/, 2]; case 7: - outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); + outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); outputsBufferReader = new BufferReader(outputsConcat); outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); @@ -36555,7 +37761,7 @@ window.Buffer = buffer.Buffer; case 0: inputTx = input[0]; spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; + redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; sequence = input[3]; if (sequence) { psbt.setInputSequence(i, sequence); @@ -36599,7 +37805,7 @@ window.Buffer = buffer.Buffer; var sigs; return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; case 1: sigs = _a.sent(); sigs.forEach(function (v, k) { @@ -36648,45 +37854,45 @@ window.Buffer = buffer.Buffer; return new p2pkh(psbt, masterFp); } - var id$2 = 0; - var subscribers$1 = []; + var id$1 = 0; + var subscribers = []; /** * log something * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) * @param message a clear message of the log associated to the type */ - var log$1 = function (type, message, data) { + var log = function (type, message, data) { var obj = { type: type, - id: String(++id$2), + id: String(++id$1), date: new Date() }; if (message) obj.message = message; if (data) obj.data = data; - dispatch$1(obj); + dispatch(obj); }; /** * listen to logs. * @param cb that is called for each future log() with the Log object * @return a function that can be called to unsubscribe the listener */ - var listen$1 = function (cb) { - subscribers$1.push(cb); + var listen = function (cb) { + subscribers.push(cb); return function () { - var i = subscribers$1.indexOf(cb); + var i = subscribers.indexOf(cb); if (i !== -1) { // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers$1[i] = subscribers$1[subscribers$1.length - 1]; - subscribers$1.pop(); + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); } }; }; - function dispatch$1(log) { - for (var i = 0; i < subscribers$1.length; i++) { + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { try { - subscribers$1[i](log); + subscribers[i](log); } catch (e) { console.error(e); @@ -36694,13 +37900,13 @@ window.Buffer = buffer.Buffer; } } if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen$1; + window.__ledgerLogsListen = listen; } var index = /*#__PURE__*/Object.freeze({ __proto__: null, - log: log$1, - listen: listen$1 + log: log, + listen: listen }); var __assign$4 = (undefined && undefined.__assign) || function () { @@ -36868,6 +38074,270 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$l.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$l.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ + transaction.version, + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$l.from([0x00]) + : Buffer$l.alloc(0); + data = Buffer$l.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$l.concat([ + output.amount, + isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$l.concat(endData); + extraPart = isDecred + ? data + : Buffer$l.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; var __values$6 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); @@ -36879,270 +38349,6 @@ window.Buffer = buffer.Buffer; }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$k.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$k.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$6(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ - transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$6(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$k.from([0x00]) - : Buffer$k.alloc(0); - data = Buffer$k.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$6(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$k.concat([ - output.amount, - isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$k.concat(endData); - extraPart = isDecred - ? data - : Buffer$k.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { if (bip143 === void 0) { bip143 = false; } if (overwinter === void 0) { overwinter = false; } @@ -37169,10 +38375,10 @@ window.Buffer = buffer.Buffer; return __generator$b(this, function (_e) { switch (_e.label) { case 0: - data = Buffer$k.concat([ + data = Buffer$l.concat([ transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), createVarint(transaction.inputs.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; @@ -37183,7 +38389,7 @@ window.Buffer = buffer.Buffer; _e.label = 2; case 2: _e.trys.push([2, 15, 16, 17]); - _a = __values$5(transaction.inputs), _b = _a.next(); + _a = __values$6(transaction.inputs), _b = _a.next(); _e.label = 3; case 3: if (!!_b.done) return [3 /*break*/, 14]; @@ -37192,24 +38398,24 @@ window.Buffer = buffer.Buffer; inputValue = inputs[i].value; if (bip143) { if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputValue.length]); + prefix = Buffer$l.from([0x01, inputValue.length]); } else { - prefix = Buffer$k.from([0x02]); + prefix = Buffer$l.from([0x02]); } } else { if (inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputs[i].value.length]); + prefix = Buffer$l.from([0x01, inputs[i].value.length]); } else { - prefix = Buffer$k.from([0x00]); + prefix = Buffer$l.from([0x00]); } } - data = Buffer$k.concat([ + data = Buffer$l.concat([ prefix, inputValue, - isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), + isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), createVarint(input.script.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; @@ -37229,7 +38435,7 @@ window.Buffer = buffer.Buffer; scriptBlocks.push(input.script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$k.concat([ + scriptBlocks.push(Buffer$l.concat([ input.script.slice(offset, offset + blockSize), input.sequence, ])); @@ -37240,7 +38446,7 @@ window.Buffer = buffer.Buffer; _e.label = 5; case 5: _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$5(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); _e.label = 6; case 6: if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; @@ -37298,7 +38504,7 @@ window.Buffer = buffer.Buffer; var hash = sha$3("sha256") .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) .digest(); - var data = Buffer$k.alloc(4); + var data = Buffer$l.alloc(4); data.writeUInt32LE(indexLookup, 0); var outputs = transaction.outputs, locktime = transaction.locktime; if (!outputs || !locktime) { @@ -37307,38 +38513,38 @@ window.Buffer = buffer.Buffer; if (!outputs[indexLookup]) { throw new Error("getTrustedInputBIP143: wrong index"); } - hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); + hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); return hash.toString("hex"); } function compressPublicKey(publicKey) { var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$k.alloc(1); + var prefixBuffer = Buffer$l.alloc(1); prefixBuffer[0] = prefix; - return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$k.alloc(4); + var lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32BE(lockTime, 0); var buffer = isDecred - ? Buffer$k.concat([ + ? Buffer$l.concat([ pathsBuffer, lockTimeBuffer, - expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([sigHashType]), + expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([sigHashType]), ]) - : Buffer$k.concat([ + : Buffer$l.concat([ pathsBuffer, - Buffer$k.from([0x00]), + Buffer$l.from([0x00]), lockTimeBuffer, - Buffer$k.from([sigHashType]), + Buffer$l.from([sigHashType]), ]); if (expiryHeight && !isDecred) { - buffer = Buffer$k.concat([buffer, expiryHeight]); + buffer = Buffer$l.concat([buffer, expiryHeight]); } return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { if (result.length > 0) { @@ -37540,7 +38746,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$4 = (undefined && undefined.__values) || function(o) { + var __values$5 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -37613,9 +38819,9 @@ window.Buffer = buffer.Buffer; additionals.includes("gold") || additionals.includes("bip143"))) || (!!expiryHeight && !isDecred); - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST @@ -37630,17 +38836,17 @@ window.Buffer = buffer.Buffer; targetTransaction = { inputs: [], version: defaultVersion, - timestamp: Buffer$k.alloc(0) + timestamp: Buffer$l.alloc(0) }; getTrustedInputCall = useBip143 && !useTrustedInputForSegwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); notify(0, 0); _b.label = 5; case 5: _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); _b.label = 6; case 6: if (!!inputs_1_1.done) return [3 /*break*/, 10]; @@ -37649,14 +38855,14 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; case 7: trustedInput = _b.sent(); - log$1("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$k.alloc(4); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: true, - value: Buffer$k.from(trustedInput, "hex"), + value: Buffer$l.from(trustedInput, "hex"), sequence: sequence }); _b.label = 8; @@ -37667,11 +38873,11 @@ window.Buffer = buffer.Buffer; regularOutputs.push(outputs[index]); } if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); targetTransaction.nExpiryHeight = expiryHeight; // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$k.from(sapling + targetTransaction.extraData = Buffer$l.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); } @@ -37695,7 +38901,7 @@ window.Buffer = buffer.Buffer; return [7 /*endfinally*/]; case 13: targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$k.alloc(4); + var sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); @@ -37724,12 +38930,12 @@ window.Buffer = buffer.Buffer; return [3 /*break*/, 14]; case 17: for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); + publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); } _b.label = 18; case 18: if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$k.alloc(4); + targetTransaction.timestamp = Buffer$l.alloc(4); targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); } onDeviceSignatureRequested(); @@ -37761,13 +38967,13 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 34]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : !segwit ? regularOutputs[i].script - : Buffer$k.concat([ - Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), + : Buffer$l.concat([ + Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), hashPublicKey(publicKeys[i]), - Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), + Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), ]); pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; @@ -37812,20 +39018,20 @@ window.Buffer = buffer.Buffer; // Populate the final input scripts for (i = 0; i < inputs.length; i++) { if (segwit) { - targetTransaction.witness = Buffer$k.alloc(0); + targetTransaction.witness = Buffer$l.alloc(0); if (!bech32) { - targetTransaction.inputs[i].script = Buffer$k.concat([ - Buffer$k.from("160014", "hex"), + targetTransaction.inputs[i].script = Buffer$l.concat([ + Buffer$l.from("160014", "hex"), hashPublicKey(publicKeys[i]), ]); } } else { - signatureSize = Buffer$k.alloc(1); - keySize = Buffer$k.alloc(1); + signatureSize = Buffer$l.alloc(1); + keySize = Buffer$l.alloc(1); signatureSize[0] = signatures[i].length; keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$k.concat([ + targetTransaction.inputs[i].script = Buffer$l.concat([ signatureSize, signatures[i], keySize, @@ -37835,51 +39041,51 @@ window.Buffer = buffer.Buffer; offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); } - lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$k.concat([ + result = Buffer$l.concat([ serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript, ]); if (segwit && !isDecred) { - witness = Buffer$k.alloc(0); + witness = Buffer$l.alloc(0); for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$k.concat([ - Buffer$k.from("02", "hex"), - Buffer$k.from([signatures[i].length]), + tmpScriptData = Buffer$l.concat([ + Buffer$l.from("02", "hex"), + Buffer$l.from([signatures[i].length]), signatures[i], - Buffer$k.from([publicKeys[i].length]), + Buffer$l.from([publicKeys[i].length]), publicKeys[i], ]); - witness = Buffer$k.concat([witness, tmpScriptData]); + witness = Buffer$l.concat([witness, tmpScriptData]); } - result = Buffer$k.concat([result, witness]); + result = Buffer$l.concat([result, witness]); } // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here // and it should not break other coins because expiryHeight is false for them. // Don't know about Decred though. - result = Buffer$k.concat([result, lockTimeBuffer]); + result = Buffer$l.concat([result, lockTimeBuffer]); if (expiryHeight) { - result = Buffer$k.concat([ + result = Buffer$l.concat([ result, - targetTransaction.nExpiryHeight || Buffer$k.alloc(0), - targetTransaction.extraData || Buffer$k.alloc(0), + targetTransaction.nExpiryHeight || Buffer$l.alloc(0), + targetTransaction.extraData || Buffer$l.alloc(0), ]); } if (isDecred) { - decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); + decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$k.concat([ + decredWitness_1 = Buffer$l.concat([ decredWitness_1, - Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0xff, 0xff, 0xff, 0xff]), - Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0xff, 0xff, 0xff, 0xff]), + Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script, ]); }); - result = Buffer$k.concat([result, decredWitness_1]); + result = Buffer$l.concat([result, decredWitness_1]); } return [2 /*return*/, result.toString("hex")]; } @@ -37931,7 +39137,7 @@ window.Buffer = buffer.Buffer; switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$k.from(messageHex, "hex"); + message = Buffer$l.from(messageHex, "hex"); offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; @@ -37944,7 +39150,7 @@ window.Buffer = buffer.Buffer; chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach(function (element, index) { @@ -37971,7 +39177,7 @@ window.Buffer = buffer.Buffer; case 2: _b.sent(); return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; case 4: res = _b.sent(); v = res[0] - 0x30; @@ -38043,7 +39249,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$3 = (undefined && undefined.__values) || function(o) { + var __values$4 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38068,9 +39274,9 @@ window.Buffer = buffer.Buffer; switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); defaultVersion.writeUInt32LE(transactionVersion, 0); trustedInputs = []; regularOutputs = []; @@ -38082,11 +39288,11 @@ window.Buffer = buffer.Buffer; version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); _c.label = 2; case 2: if (!!inputs_1_1.done) return [3 /*break*/, 6]; @@ -38095,15 +39301,15 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; case 3: trustedInput = _c.sent(); - sequence = Buffer$k.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: false, value: segwit - ? Buffer$k.from(trustedInput, "hex") - : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), + ? Buffer$l.from(trustedInput, "hex") + : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), sequence: sequence }); _c.label = 4; @@ -38131,7 +39337,7 @@ window.Buffer = buffer.Buffer; case 9: // Pre-build the target transaction for (i = 0; i < inputs.length; i++) { - sequence = Buffer$k.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); @@ -38156,7 +39362,7 @@ window.Buffer = buffer.Buffer; if (!(i < inputs.length)) return [3 /*break*/, 19]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; @@ -38287,8 +39493,8 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.derivatePath(path)]; case 2: accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); return [2 /*return*/, xpub]; } }); @@ -38406,29 +39612,29 @@ window.Buffer = buffer.Buffer; return hash160(compressedPubKey).slice(0, 4); } function asBufferUInt32BE(n) { - var buf = Buffer$k.allocUnsafe(4); + var buf = Buffer$l.allocUnsafe(4); buf.writeUInt32BE(n, 0); return buf; } var compressPublicKeySECP256 = function (publicKey) { - return Buffer$k.concat([ - Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), + return Buffer$l.concat([ + Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), publicKey.slice(1, 33), ]); }; function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { var indexBuffer = asBufferUInt32BE(index); indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$k.concat([ + var extendedKeyBytes = Buffer$l.concat([ asBufferUInt32BE(version), - Buffer$k.from([depth]), + Buffer$l.from([depth]), parentFingerprint, indexBuffer, chainCode, pubKey, ]); var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); + return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); } function sha256(buffer) { return sha$3("sha256").update(buffer).digest(); @@ -38475,7 +39681,7 @@ window.Buffer = buffer.Buffer; } MerkleMap.prototype.commitment = function () { // returns a buffer between 65 and 73 (included) bytes long - return Buffer$k.concat([ + return Buffer$l.concat([ createVarint(this.keys.length), this.keysTree.getRoot(), this.valuesTree.getRoot(), @@ -38573,7 +39779,7 @@ window.Buffer = buffer.Buffer; } return v; }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); var merkleMap = new MerkleMap(sortedKeys, values); return merkleMap; }; @@ -38620,7 +39826,7 @@ window.Buffer = buffer.Buffer; } return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$2 = (undefined && undefined.__values) || function(o) { + var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38654,9 +39860,9 @@ window.Buffer = buffer.Buffer; return _this; } YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$k.from(request.subarray(1))); + this.results.push(Buffer$l.from(request.subarray(1))); this.progressCallback(); - return Buffer$k.from(""); + return Buffer$l.from(""); }; return YieldCommand; }(ClientCommand)); @@ -38679,7 +39885,7 @@ window.Buffer = buffer.Buffer; throw new Error("Unsupported request, the first byte should be 0"); } // read the hash - var hash = Buffer$k.alloc(32); + var hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { hash[i] = req[1 + i]; } @@ -38693,12 +39899,12 @@ window.Buffer = buffer.Buffer; var payload_size = Math.min(max_payload_size, known_preimage.length); if (payload_size < known_preimage.length) { for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$k.from([known_preimage[i]])); + this.queue.push(Buffer$l.from([known_preimage[i]])); } } - return Buffer$k.concat([ + return Buffer$l.concat([ preimage_len_varint, - Buffer$k.from([payload_size]), + Buffer$l.from([payload_size]), known_preimage.subarray(0, payload_size), ]); } @@ -38750,10 +39956,10 @@ window.Buffer = buffer.Buffer; if (n_leftover_elements > 0) { (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); } - return Buffer$k.concat(__spreadArray$1([ + return Buffer$l.concat(__spreadArray$1([ mt.getLeafHash(leaf_index), - Buffer$k.from([proof.length]), - Buffer$k.from([n_response_elements]) + Buffer$l.from([proof.length]), + Buffer$l.from([n_response_elements]) ], __read$1(proof.slice(0, n_response_elements)), false)); }; return GetMerkleLeafProofCommand; @@ -38772,13 +39978,13 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid request, unexpected trailing data"); } // read the root hash - var root_hash = Buffer$k.alloc(32); + var root_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { root_hash[i] = req.readUInt8(i); } var root_hash_hex = root_hash.toString("hex"); // read the leaf hash - var leef_hash = Buffer$k.alloc(32); + var leef_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { leef_hash[i] = req.readUInt8(32 + i); } @@ -38796,7 +40002,7 @@ window.Buffer = buffer.Buffer; break; } } - return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); + return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); }; return GetMerkleLeafIndexCommand; }(ClientCommand)); @@ -38823,9 +40029,9 @@ window.Buffer = buffer.Buffer; var max_elements = Math.floor(253 / element_len); var n_returned_elements = Math.min(max_elements, this.queue.length); var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$k.concat(__spreadArray$1([ - Buffer$k.from([n_returned_elements]), - Buffer$k.from([element_len]) + return Buffer$l.concat(__spreadArray$1([ + Buffer$l.from([n_returned_elements]), + Buffer$l.from([element_len]) ], __read$1(returned_elements), false)); }; return GetMoreElementsCommand; @@ -38861,7 +40067,7 @@ window.Buffer = buffer.Buffer; new GetMoreElementsCommand(this.queue), ]; try { - for (var commands_1 = __values$2(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { var cmd = commands_1_1.value; if (this.commands.has(cmd.code)) { throw new Error("Multiple commands with code " + cmd.code); @@ -38886,9 +40092,9 @@ window.Buffer = buffer.Buffer; ClientCommandInterpreter.prototype.addKnownList = function (elements) { var e_2, _a; try { - for (var elements_1 = __values$2(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { var el = elements_1_1.value; - var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); + var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); this.addKnownPreimage(preimage); } } @@ -38956,7 +40162,7 @@ window.Buffer = buffer.Buffer; if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$1 = (undefined && undefined.__values) || function(o) { + var __values$2 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -39027,8 +40233,8 @@ window.Buffer = buffer.Buffer; if (pathElements.length > 6) { throw new Error("Path too long. At most 6 levels allowed."); } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), pathElementsToBuffer(pathElements), ]))]; case 1: @@ -39052,15 +40258,15 @@ window.Buffer = buffer.Buffer; throw new Error("Invalid HMAC length"); } clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$k.alloc(4); + addressIndexBuffer = Buffer$l.alloc(4); addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), - Buffer$k.from([change]), + walletHMAC || Buffer$l.alloc(32, 0), + Buffer$l.from([change]), addressIndexBuffer, ]), clientInterpreter)]; case 1: @@ -39083,11 +40289,11 @@ window.Buffer = buffer.Buffer; } clientInterpreter = new ClientCommandInterpreter(progressCallback); // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); try { - for (_a = __values$1(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { map = _b.value; clientInterpreter.addKnownMapping(map); } @@ -39100,7 +40306,7 @@ window.Buffer = buffer.Buffer; finally { if (e_1) throw e_1.error; } } try { - for (_c = __values$1(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { map = _d.value; clientInterpreter.addKnownMapping(map); } @@ -39116,21 +40322,21 @@ window.Buffer = buffer.Buffer; inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ merkelizedPsbt.getGlobalKeysValuesRoot(), createVarint(merkelizedPsbt.getGlobalInputCount()), inputMapsRoot, createVarint(merkelizedPsbt.getGlobalOutputCount()), outputMapsRoot, walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), + walletHMAC || Buffer$l.alloc(32, 0), ]), clientInterpreter)]; case 1: _h.sent(); yielded = clientInterpreter.getYielded(); ret = new Map(); try { - for (yielded_1 = __values$1(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { inputAndSig = yielded_1_1.value; ret.set(inputAndSig[0], inputAndSig.slice(1)); } @@ -39150,7 +40356,7 @@ window.Buffer = buffer.Buffer; AppClient.prototype.getMasterFingerprint = function () { return __awaiter$4(this, void 0, void 0, function () { return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; }); }); }; @@ -39203,18 +40409,18 @@ window.Buffer = buffer.Buffer; var outputs = []; var witness = false; var offset = 0; - var timestamp = Buffer$k.alloc(0); - var nExpiryHeight = Buffer$k.alloc(0); - var nVersionGroupId = Buffer$k.alloc(0); - var extraData = Buffer$k.alloc(0); + var timestamp = Buffer$l.alloc(0); + var nExpiryHeight = Buffer$l.alloc(0); + var nVersionGroupId = Buffer$l.alloc(0); + var extraData = Buffer$l.alloc(0); var isDecred = additionals.includes("decred"); var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$k.from(transactionHex, "hex"); + var transaction = Buffer$l.from(transactionHex, "hex"); var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$k.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$k.from([0x02, 0x00, 0x00, 0x00])); + var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); + var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || + version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); offset += 4; if (!hasTimestamp && isSegwitSupported && @@ -39240,8 +40446,8 @@ window.Buffer = buffer.Buffer; for (var i = 0; i < numberInputs; i++) { var prevout = transaction.slice(offset, offset + 36); offset += 36; - var script = Buffer$k.alloc(0); - var tree = Buffer$k.alloc(0); + var script = Buffer$l.alloc(0); + var tree = Buffer$l.alloc(0); //No script for decred, it has a witness if (!isDecred) { varint = getVarint(transaction, offset); @@ -39331,7 +40537,7 @@ window.Buffer = buffer.Buffer; nExpiryHeight: nExpiryHeight, extraData: extraData }; - log$1("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); return t; } @@ -39658,401 +40864,422 @@ window.Buffer = buffer.Buffer; 'default': Btc }); - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var errorClasses$1 = {}; - var deserializers$1 = {}; - var addCustomErrorDeserializer$1 = function (name, deserializer) { - deserializers$1[name] = deserializer; - }; - var createCustomErrorClass$1 = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses$1[name] = C; - return C; - }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers$1[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses$1[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass$1(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var to = {}; - seen.push(from); - for (var _i = 0, _a = Object.keys(from); _i < _a.length; _i++) { - var key = _a[_i]; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass$1("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass$1("AccountNotSupported"); - var AmountRequired = createCustomErrorClass$1("AmountRequired"); - var BluetoothRequired = createCustomErrorClass$1("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass$1("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass$1("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass$1("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass$1("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass$1("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass$1("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass$1("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass$1("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass$1("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass$1("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass$1("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass$1("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass$1("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass$1("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass$1("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass$1("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass$1("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass$1("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass$1("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass$1("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass$1("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass$1("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass$1("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass$1("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass$1("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass$1("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass$1("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass$1("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass$1("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass$1("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass$1("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass$1("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass$1("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass$1("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass$1("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass$1("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass$1("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass$1("NetworkDown"); - var NoAddressesFound = createCustomErrorClass$1("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass$1("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass$1("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass$1("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass$1("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass$1("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass$1("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass$1("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass$1("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass$1("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass$1("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass$1("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass$1("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass$1("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass$1("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass$1("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass$1("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass$1("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass$1("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass$1("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass$1("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass$1("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass$1("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass$1("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass$1("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass$1("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass$1("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass$1("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass$1("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass$1("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass$1("TransportInterfaceNotAvailable"); - var TransportRaceCondition$1 = createCustomErrorClass$1("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass$1("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass$1("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass$1("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass$1("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass$1("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass$1("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass$1("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass$1("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass$1("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass$1("FeeRequired"); - var FeeTooHigh = createCustomErrorClass$1("FeeTooHigh"); - var SyncError = createCustomErrorClass$1("SyncError"); - var PairingFailed = createCustomErrorClass$1("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass$1("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass$1("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass$1("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass$1("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass$1("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass$1("DBWrongPassword"); - var DBNotReset = createCustomErrorClass$1("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError$1(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportError", function (e) { return new TransportError$1(e.message, e.id); }); - var StatusCodes$1 = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa, - }; - function getAltStatusMessage$1(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError$1(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes$1).find(function (k) { return StatusCodes$1[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage$1(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError$1.prototype = new Error(); - addCustomErrorDeserializer$1("TransportStatusError", function (e) { return new TransportStatusError$1(e.statusCode); }); - - var dist = /*#__PURE__*/Object.freeze({ + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; + }; + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); + var AmountRequired = createCustomErrorClass("AmountRequired"); + var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass("NetworkDown"); + var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass("FeeRequired"); + var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); + var SyncError = createCustomErrorClass("SyncError"); + var PairingFailed = createCustomErrorClass("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); + var DBNotReset = createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); + + var libEs = /*#__PURE__*/Object.freeze({ __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass, + addCustomErrorDeserializer: addCustomErrorDeserializer, AccountNameRequiredError: AccountNameRequiredError, AccountNotSupported: AccountNotSupported, AmountRequired: AmountRequired, BluetoothRequired: BluetoothRequired, BtcUnmatchedApp: BtcUnmatchedApp, CantOpenDevice: CantOpenDevice, - CantScanQRCode: CantScanQRCode, CashAddrNotSupported: CashAddrNotSupported, CurrencyNotSupported: CurrencyNotSupported, - DBNotReset: DBNotReset, - DBWrongPassword: DBWrongPassword, DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceHalted: DeviceHalted, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceNameInvalid: DeviceNameInvalid, DeviceNotGenuineError: DeviceNotGenuineError, DeviceOnDashboardExpected: DeviceOnDashboardExpected, DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceShouldStayInApp: DeviceShouldStayInApp, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, DeviceSocketFail: DeviceSocketFail, DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, DisconnectedDevice: DisconnectedDevice, DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - ETHAddressNonEIP: ETHAddressNonEIP, EnpointConfigError: EnpointConfigError, EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, FeeEstimationFailed: FeeEstimationFailed, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, FirmwareNotRecognized: FirmwareNotRecognized, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - GasLessThanEstimate: GasLessThanEstimate, - GenuineCheckFailed: GenuineCheckFailed, HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, InvalidAddress: InvalidAddress, InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - InvalidXRPTag: InvalidXRPTag, LatestMCUInstalledError: LatestMCUInstalledError, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, + UnknownMCU: UnknownMCU, LedgerAPIError: LedgerAPIError, LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, LedgerAPINotAvailable: LedgerAPINotAvailable, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, ManagerDeviceLockedError: ManagerDeviceLockedError, ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, ManagerUninstallBTCDep: ManagerUninstallBTCDep, NetworkDown: NetworkDown, - NoAccessToCamera: NoAccessToCamera, NoAddressesFound: NoAddressesFound, - NoDBPathGiven: NoDBPathGiven, NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughGas: NotEnoughGas, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, NotSupportedLegacyAddress: NotSupportedLegacyAddress, - PairingFailed: PairingFailed, - PasswordIncorrectError: PasswordIncorrectError, + GasLessThanEstimate: GasLessThanEstimate, PasswordsDontMatchError: PasswordsDontMatchError, - RecipientRequired: RecipientRequired, + PasswordIncorrectError: PasswordIncorrectError, RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, RecommendUndelegation: RecommendUndelegation, - StatusCodes: StatusCodes$1, - SyncError: SyncError, TimeoutTagged: TimeoutTagged, - TransportError: TransportError$1, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportRaceCondition: TransportRaceCondition$1, - TransportStatusError: TransportStatusError$1, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UnexpectedBootloader: UnexpectedBootloader, - UnknownMCU: UnknownMCU, UpdateFetchFileFail: UpdateFetchFileFail, UpdateIncorrectHash: UpdateIncorrectHash, UpdateIncorrectSig: UpdateIncorrectSig, UpdateYourApp: UpdateYourApp, - UserRefusedAddress: UserRefusedAddress, - UserRefusedAllowManager: UserRefusedAllowManager, UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, WebsocketConnectionError: WebsocketConnectionError, WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongAppForCurrency: WrongAppForCurrency, WrongDeviceForAccount: WrongDeviceForAccount, - addCustomErrorDeserializer: addCustomErrorDeserializer$1, - createCustomErrorClass: createCustomErrorClass$1, - deserializeError: deserializeError, - getAltStatusMessage: getAltStatusMessage$1, - serializeError: serializeError + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError, + StatusCodes: StatusCodes, + getAltStatusMessage: getAltStatusMessage, + TransportStatusError: TransportStatusError }); var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -40132,7 +41359,7 @@ window.Buffer = buffer.Buffer; * A **Descriptor** is a parametric type that is up to be determined for the implementation. * it can be for instance an ID, an file path, a URL,... */ - var Transport$1 = /** @class */ (function () { + var Transport = /** @class */ (function () { function Transport() { var _this = this; this.exchangeTimeout = 30000; @@ -40150,26 +41377,26 @@ window.Buffer = buffer.Buffer; * @return a Promise of response buffer */ this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$k.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes$1.OK]; } + if (data === void 0) { data = Buffer$l.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes.OK]; } return __awaiter$2(_this, void 0, void 0, function () { var response, sw; return __generator$2(this, function (_a) { switch (_a.label) { case 0: if (data.length >= 256) { - throw new TransportError$1("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - return [4 /*yield*/, this.exchange(Buffer$k.concat([ - Buffer$k.from([cla, ins, p1, p2]), - Buffer$k.from([data.length]), + return [4 /*yield*/, this.exchange(Buffer$l.concat([ + Buffer$l.from([cla, ins, p1, p2]), + Buffer$l.from([data.length]), data, ]))]; case 1: response = _a.sent(); sw = response.readUInt16BE(response.length - 2); if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError$1(sw); + throw new TransportStatusError(sw); } return [2 /*return*/, response]; } @@ -40183,7 +41410,7 @@ window.Buffer = buffer.Buffer; switch (_a.label) { case 0: if (this.exchangeBusyPromise) { - throw new TransportRaceCondition$1("An action was already pending on the Ledger device. Please deny or reconnect."); + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); } busyPromise = new Promise(function (r) { resolveBusy = r; @@ -40309,14 +41536,14 @@ window.Buffer = buffer.Buffer; if (listenTimeoutId) clearTimeout(listenTimeoutId); if (!found) { - reject(new TransportError$1(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); } } }); var listenTimeoutId = listenTimeout ? setTimeout(function () { sub.unsubscribe(); - reject(new TransportError$1(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); }, listenTimeout) : null; }); @@ -40351,7 +41578,7 @@ window.Buffer = buffer.Buffer; case 0: _appAPIlock = this._appAPIlock; if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError$1("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; } _a.label = 1; case 1: @@ -40376,19 +41603,19 @@ window.Buffer = buffer.Buffer; var hidFraming$1 = {}; - var require$$0 = /*@__PURE__*/getAugmentedNamespace(dist); + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); (function (exports) { exports.__esModule = true; var errors_1 = require$$0; var Tag = 0x05; function asUInt16BE(value) { - var b = Buffer$k.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16BE(value, 0); return b; } var initialAcc = { - data: Buffer$k.alloc(0), + data: Buffer$l.alloc(0), dataLength: 0, sequence: 0 }; @@ -40398,21 +41625,21 @@ window.Buffer = buffer.Buffer; var createHIDframing = function (channel, packetSize) { return { makeBlocks: function (apdu) { - var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); + var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); var blockSize = packetSize - 5; var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$k.concat([ + data = Buffer$l.concat([ data, - Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), ]); var blocks = []; for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$k.alloc(5); + var head = Buffer$l.alloc(5); head.writeUInt16BE(channel, 0); head.writeUInt8(Tag, 2); head.writeUInt16BE(i, 3); var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$k.concat([head, chunk])); + blocks.push(Buffer$l.concat([head, chunk])); } return blocks; }, @@ -40432,7 +41659,7 @@ window.Buffer = buffer.Buffer; } sequence++; var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$k.concat([data, chunkData]); + data = Buffer$l.concat([data, chunkData]); if (data.length > dataLength) { data = data.slice(0, dataLength); } @@ -40559,8 +41786,8 @@ window.Buffer = buffer.Buffer; }; var bluetoothServices = []; var serviceUuidToInfos = {}; - for (var id$1 in devices) { - var deviceModel = devices[id$1]; + for (var id in devices) { + var deviceModel = devices[id]; var bluetoothSpec = deviceModel.bluetoothSpec; if (bluetoothSpec) { for (var i = 0; i < bluetoothSpec.length; i++) { @@ -40655,7 +41882,7 @@ window.Buffer = buffer.Buffer; }); }); } - var isSupported$1 = function () { + var isSupported = function () { return Promise.resolve(!!navigator && !!navigator.usb && typeof navigator.usb.getDevices === "function"); @@ -40870,7 +42097,7 @@ window.Buffer = buffer.Buffer; switch (_b.label) { case 0: _a = this, channel = _a.channel, packetSize = _a.packetSize; - log$1("apdu", "=> " + apdu.toString("hex")); + log("apdu", "=> " + apdu.toString("hex")); framing = hidFraming(channel, packetSize); blocks = framing.makeBlocks(apdu); i = 0; @@ -40889,11 +42116,11 @@ window.Buffer = buffer.Buffer; return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$k.from(r.data.buffer); + buffer = Buffer$l.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: - log$1("apdu", "<= " + result.toString("hex")); + log("apdu", "<= " + result.toString("hex")); return [2 /*return*/, result]; } }); @@ -40915,7 +42142,7 @@ window.Buffer = buffer.Buffer; /** * Check if WebUSB transport is supported. */ - TransportWebUSB.isSupported = isSupported$1; + TransportWebUSB.isSupported = isSupported; /** * List the WebUSB devices that was previously authorized by the user. */ @@ -40956,7 +42183,7 @@ window.Buffer = buffer.Buffer; }; }; return TransportWebUSB; - }(Transport$1)); + }(Transport)); function gracefullyResetDevice(device) { return __awaiter(this, void 0, void 0, function () { var err_1; @@ -40983,1352 +42210,8 @@ window.Buffer = buffer.Buffer; 'default': TransportWebUSB }); - /** Namespace for the U2F api. - * @type {Object} - */ - var u2f = u2f || {}; - - var googleU2fApi = u2f; // Adaptation for u2f-api package - - /** - * The U2F extension id - * @type {string} - * @const - */ - u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd'; - - /** - * Message types for messsages to/from the extension - * @const - * @enum {string} - */ - u2f.MessageTypes = { - 'U2F_REGISTER_REQUEST': 'u2f_register_request', - 'U2F_SIGN_REQUEST': 'u2f_sign_request', - 'U2F_REGISTER_RESPONSE': 'u2f_register_response', - 'U2F_SIGN_RESPONSE': 'u2f_sign_response' - }; - - /** - * Response status codes - * @const - * @enum {number} - */ - u2f.ErrorCodes = { - 'OK': 0, - 'OTHER_ERROR': 1, - 'BAD_REQUEST': 2, - 'CONFIGURATION_UNSUPPORTED': 3, - 'DEVICE_INELIGIBLE': 4, - 'TIMEOUT': 5 - }; - - /** - * A message type for registration requests - * @typedef {{ - * type: u2f.MessageTypes, - * signRequests: Array., - * registerRequests: ?Array., - * timeoutSeconds: ?number, - * requestId: ?number - * }} - */ - u2f.Request; - - /** - * A message for registration responses - * @typedef {{ - * type: u2f.MessageTypes, - * responseData: (u2f.Error | u2f.RegisterResponse | u2f.SignResponse), - * requestId: ?number - * }} - */ - u2f.Response; - - /** - * An error object for responses - * @typedef {{ - * errorCode: u2f.ErrorCodes, - * errorMessage: ?string - * }} - */ - u2f.Error; - - /** - * Data object for a single sign request. - * @typedef {{ - * version: string, - * challenge: string, - * keyHandle: string, - * appId: string - * }} - */ - u2f.SignRequest; - - /** - * Data object for a sign response. - * @typedef {{ - * keyHandle: string, - * signatureData: string, - * clientData: string - * }} - */ - u2f.SignResponse; - - /** - * Data object for a registration request. - * @typedef {{ - * version: string, - * challenge: string, - * appId: string - * }} - */ - u2f.RegisterRequest; - - /** - * Data object for a registration response. - * @typedef {{ - * registrationData: string, - * clientData: string - * }} - */ - u2f.RegisterResponse; - - - // Low level MessagePort API support - - /** - * Call MessagePort disconnect - */ - u2f.disconnect = function() { - if (u2f.port_ && u2f.port_.port_) { - u2f.port_.port_.disconnect(); - u2f.port_ = null; - } - }; - - /** - * Sets up a MessagePort to the U2F extension using the - * available mechanisms. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - */ - u2f.getMessagePort = function(callback) { - if (typeof chrome != 'undefined' && chrome.runtime) { - // The actual message here does not matter, but we need to get a reply - // for the callback to run. Thus, send an empty signature request - // in order to get a failure response. - var msg = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: [] - }; - chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() { - if (!chrome.runtime.lastError) { - // We are on a whitelisted origin and can talk directly - // with the extension. - u2f.getChromeRuntimePort_(callback); - } else { - // chrome.runtime was available, but we couldn't message - // the extension directly, use iframe - u2f.getIframePort_(callback); - } - }); - } else { - // chrome.runtime was not available at all, which is normal - // when this origin doesn't have access to any extensions. - u2f.getIframePort_(callback); - } - }; - - /** - * Connects directly to the extension via chrome.runtime.connect - * @param {function(u2f.WrappedChromeRuntimePort_)} callback - * @private - */ - u2f.getChromeRuntimePort_ = function(callback) { - var port = chrome.runtime.connect(u2f.EXTENSION_ID, - {'includeTlsChannelId': true}); - setTimeout(function() { - callback(null, new u2f.WrappedChromeRuntimePort_(port)); - }, 0); - }; - - /** - * A wrapper for chrome.runtime.Port that is compatible with MessagePort. - * @param {Port} port - * @constructor - * @private - */ - u2f.WrappedChromeRuntimePort_ = function(port) { - this.port_ = port; - }; - - /** - * Posts a message on the underlying channel. - * @param {Object} message - */ - u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) { - this.port_.postMessage(message); - }; - - /** - * Emulates the HTML 5 addEventListener interface. Works only for the - * onmessage event, which is hooked up to the chrome.runtime.Port.onMessage. - * @param {string} eventName - * @param {function({data: Object})} handler - */ - u2f.WrappedChromeRuntimePort_.prototype.addEventListener = - function(eventName, handler) { - var name = eventName.toLowerCase(); - if (name == 'message' || name == 'onmessage') { - this.port_.onMessage.addListener(function(message) { - // Emulate a minimal MessageEvent object - handler({'data': message}); - }); - } else { - console.error('WrappedChromeRuntimePort only supports onMessage'); - } - }; - - /** - * Sets up an embedded trampoline iframe, sourced from the extension. - * @param {function(MessagePort)} callback - * @private - */ - u2f.getIframePort_ = function(callback) { - // Create the iframe - var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID; - var iframe = document.createElement('iframe'); - iframe.src = iframeOrigin + '/u2f-comms.html'; - iframe.setAttribute('style', 'display:none'); - document.body.appendChild(iframe); - - var hasCalledBack = false; - - var channel = new MessageChannel(); - var ready = function(message) { - if (message.data == 'ready') { - channel.port1.removeEventListener('message', ready); - if (!hasCalledBack) - { - hasCalledBack = true; - callback(null, channel.port1); - } - } else { - console.error('First event on iframe port was not "ready"'); - } - }; - channel.port1.addEventListener('message', ready); - channel.port1.start(); - - iframe.addEventListener('load', function() { - // Deliver the port to the iframe and initialize - iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]); - }); - - // Give this 200ms to initialize, after that, we treat this method as failed - setTimeout(function() { - if (!hasCalledBack) - { - hasCalledBack = true; - callback(new Error("IFrame extension not supported")); - } - }, 200); - }; - - - // High-level JS API - - /** - * Default extension response timeout in seconds. - * @const - */ - u2f.EXTENSION_TIMEOUT_SEC = 30; - - /** - * A singleton instance for a MessagePort to the extension. - * @type {MessagePort|u2f.WrappedChromeRuntimePort_} - * @private - */ - u2f.port_ = null; - - /** - * Callbacks waiting for a port - * @type {Array.} - * @private - */ - u2f.waitingForPort_ = []; - - /** - * A counter for requestIds. - * @type {number} - * @private - */ - u2f.reqCounter_ = 0; - - /** - * A map from requestIds to client callbacks - * @type {Object.} - * @private - */ - u2f.callbackMap_ = {}; - - /** - * Creates or retrieves the MessagePort singleton to use. - * @param {function((MessagePort|u2f.WrappedChromeRuntimePort_))} callback - * @private - */ - u2f.getPortSingleton_ = function(callback) { - if (u2f.port_) { - callback(null, u2f.port_); - } else { - if (u2f.waitingForPort_.length == 0) { - u2f.getMessagePort(function(err, port) { - if (!err) { - u2f.port_ = port; - u2f.port_.addEventListener('message', - /** @type {function(Event)} */ (u2f.responseHandler_)); - } - - // Careful, here be async callbacks. Maybe. - while (u2f.waitingForPort_.length) - u2f.waitingForPort_.shift()(err, port); - }); - } - u2f.waitingForPort_.push(callback); - } - }; - - /** - * Handles response messages from the extension. - * @param {MessageEvent.} message - * @private - */ - u2f.responseHandler_ = function(message) { - var response = message.data; - var reqId = response['requestId']; - if (!reqId || !u2f.callbackMap_[reqId]) { - console.error('Unknown or missing requestId in response.'); - return; - } - var cb = u2f.callbackMap_[reqId]; - delete u2f.callbackMap_[reqId]; - cb(null, response['responseData']); - }; - - /** - * Calls the callback with true or false as first and only argument - * @param {Function} callback - */ - u2f.isSupported = function(callback) { - u2f.getPortSingleton_(function(err, port) { - callback(!err); - }); - }; - - /** - * Dispatches an array of sign requests to available U2F tokens. - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.SignResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.sign = function(signRequests, callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_SIGN_REQUEST, - signRequests: signRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - /** - * Dispatches register requests to available U2F tokens. An array of sign - * requests identifies already registered tokens. - * @param {Array.} registerRequests - * @param {Array.} signRequests - * @param {function((u2f.Error|u2f.RegisterResponse))} callback - * @param {number=} opt_timeoutSeconds - */ - u2f.register = function(registerRequests, signRequests, - callback, opt_timeoutSeconds) { - u2f.getPortSingleton_(function(err, port) { - if (err) - return callback(err); - - var reqId = ++u2f.reqCounter_; - u2f.callbackMap_[reqId] = callback; - var req = { - type: u2f.MessageTypes.U2F_REGISTER_REQUEST, - signRequests: signRequests, - registerRequests: registerRequests, - timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ? - opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC), - requestId: reqId - }; - port.postMessage(req); - }); - }; - - var u2fApi$1 = API; - - var chromeApi = googleU2fApi; - - // Feature detection (yes really) - var isBrowser = ( typeof navigator !== 'undefined' ) && !!navigator.userAgent; - var isSafari = isBrowser && navigator.userAgent.match( /Safari\// ) - && !navigator.userAgent.match( /Chrome\// ); - var isEDGE = isBrowser && navigator.userAgent.match( /Edge\/1[2345]/ ); - - var _backend = null; - function getBackend( Promise ) - { - if ( !_backend ) - _backend = new Promise( function( resolve, reject ) - { - function notSupported( ) - { - // Note; {native: true} means *not* using Google's hack - resolve( { u2f: null, native: true } ); - } - - if ( !isBrowser ) - return notSupported( ); - - if ( isSafari ) - // Safari doesn't support U2F, and the Safari-FIDO-U2F - // extension lacks full support (Multi-facet apps), so we - // block it until proper support. - return notSupported( ); - - var hasNativeSupport = - ( typeof window.u2f !== 'undefined' ) && - ( typeof window.u2f.sign === 'function' ); - - if ( hasNativeSupport ) - resolve( { u2f: window.u2f, native: true } ); - - if ( isEDGE ) - // We don't want to check for Google's extension hack on EDGE - // as it'll cause trouble (popups, etc) - return notSupported( ); - - if ( location.protocol === 'http:' ) - // U2F isn't supported over http, only https - return notSupported( ); - - if ( typeof MessageChannel === 'undefined' ) - // Unsupported browser, the chrome hack would throw - return notSupported( ); - - // Test for google extension support - chromeApi.isSupported( function( ok ) - { - if ( ok ) - resolve( { u2f: chromeApi, native: false } ); - else - notSupported( ); - } ); - } ); - - return _backend; - } - - function API( Promise ) - { - return { - isSupported : isSupported.bind( Promise ), - ensureSupport : ensureSupport.bind( Promise ), - register : register.bind( Promise ), - sign : sign.bind( Promise ), - ErrorCodes : API.ErrorCodes, - ErrorNames : API.ErrorNames - }; - } - - API.ErrorCodes = { - CANCELLED: -1, - OK: 0, - OTHER_ERROR: 1, - BAD_REQUEST: 2, - CONFIGURATION_UNSUPPORTED: 3, - DEVICE_INELIGIBLE: 4, - TIMEOUT: 5 - }; - API.ErrorNames = { - "-1": "CANCELLED", - "0": "OK", - "1": "OTHER_ERROR", - "2": "BAD_REQUEST", - "3": "CONFIGURATION_UNSUPPORTED", - "4": "DEVICE_INELIGIBLE", - "5": "TIMEOUT" - }; - - function makeError( msg, err ) - { - var code = err != null ? err.errorCode : 1; // Default to OTHER_ERROR - var type = API.ErrorNames[ '' + code ]; - var error = new Error( msg ); - error.metaData = { - type: type, - code: code - }; - return error; - } - - function deferPromise( Promise, promise ) - { - var ret = { }; - ret.promise = new Promise( function( resolve, reject ) { - ret.resolve = resolve; - ret.reject = reject; - promise.then( resolve, reject ); - } ); - /** - * Reject request promise and disconnect port if 'disconnect' flag is true - * @param {string} msg - * @param {boolean} disconnect - */ - ret.promise.cancel = function( msg, disconnect ) - { - getBackend( Promise ) - .then( function( backend ) - { - if ( disconnect && !backend.native ) - backend.u2f.disconnect( ); - - ret.reject( makeError( msg, { errorCode: -1 } ) ); - } ); - }; - return ret; - } - - function isSupported( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( function( backend ) - { - return !!backend.u2f; - } ); - } - - function _ensureSupport( backend ) - { - if ( !backend.u2f ) - { - if ( location.protocol === 'http:' ) - throw new Error( "U2F isn't supported over http, only https" ); - throw new Error( "U2F not supported" ); - } - } - - function ensureSupport( ) - { - var Promise = this; - - return getBackend( Promise ) - .then( _ensureSupport ); - } - - function register( registerRequests, signRequests /* = null */, timeout ) - { - var Promise = this; - - if ( !Array.isArray( registerRequests ) ) - registerRequests = [ registerRequests ]; - - if ( typeof signRequests === 'number' && typeof timeout === 'undefined' ) - { - timeout = signRequests; - signRequests = null; - } - - if ( !signRequests ) - signRequests = [ ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Registration failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = registerRequests[ 0 ].appId; - - u2f.register( - appId, registerRequests, signRequests, cbNative, timeout ); - } - else - { - u2f.register( - registerRequests, signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function sign( signRequests, timeout ) - { - var Promise = this; - - if ( !Array.isArray( signRequests ) ) - signRequests = [ signRequests ]; - - return deferPromise( Promise, getBackend( Promise ) - .then( function( backend ) - { - _ensureSupport( backend ); - - var native = backend.native; - var u2f = backend.u2f; - - return new Promise( function( resolve, reject ) - { - function cbNative( response ) - { - if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - { - delete response.errorCode; - resolve( response ); - } - } - - function cbChrome( err, response ) - { - if ( err ) - reject( err ); - else if ( response.errorCode ) - reject( makeError( "Sign failed", response ) ); - else - resolve( response ); - } - - if ( native ) - { - var appId = signRequests[ 0 ].appId; - var challenge = signRequests[ 0 ].challenge; - - u2f.sign( appId, challenge, signRequests, cbNative, timeout ); - } - else - { - u2f.sign( signRequests, cbChrome, timeout ); - } - } ); - } ) ).promise; - } - - function makeDefault( func ) - { - API[ func ] = function( ) - { - if ( !commonjsGlobal.Promise ) - // This is very unlikely to ever happen, since browsers - // supporting U2F will most likely support Promises. - throw new Error( "The platform doesn't natively support promises" ); - - var args = [ ].slice.call( arguments ); - return API( commonjsGlobal.Promise )[ func ].apply( null, args ); - }; - } - - // Provide default functions using the built-in Promise if available. - makeDefault( 'isSupported' ); - makeDefault( 'ensureSupport' ); - makeDefault( 'register' ); - makeDefault( 'sign' ); - - var u2fApi = u2fApi$1; - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; - }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; - }; - - createCustomErrorClass("AccountNameRequired"); - createCustomErrorClass("AccountNotSupported"); - createCustomErrorClass("AmountRequired"); - createCustomErrorClass("BluetoothRequired"); - createCustomErrorClass("BtcUnmatchedApp"); - createCustomErrorClass("CantOpenDevice"); - createCustomErrorClass("CashAddrNotSupported"); - createCustomErrorClass("CurrencyNotSupported"); - createCustomErrorClass("DeviceAppVerifyNotSupported"); - createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - createCustomErrorClass("DeviceNotGenuine"); - createCustomErrorClass("DeviceOnDashboardExpected"); - createCustomErrorClass("DeviceOnDashboardUnexpected"); - createCustomErrorClass("DeviceInOSUExpected"); - createCustomErrorClass("DeviceHalted"); - createCustomErrorClass("DeviceNameInvalid"); - createCustomErrorClass("DeviceSocketFail"); - createCustomErrorClass("DeviceSocketNoBulkStatus"); - createCustomErrorClass("DisconnectedDevice"); - createCustomErrorClass("DisconnectedDeviceDuringOperation"); - createCustomErrorClass("EnpointConfig"); - createCustomErrorClass("EthAppPleaseEnableContractData"); - createCustomErrorClass("FeeEstimationFailed"); - createCustomErrorClass("FirmwareNotRecognized"); - createCustomErrorClass("HardResetFail"); - createCustomErrorClass("InvalidXRPTag"); - createCustomErrorClass("InvalidAddress"); - createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - createCustomErrorClass("LatestMCUInstalledError"); - createCustomErrorClass("UnknownMCU"); - createCustomErrorClass("LedgerAPIError"); - createCustomErrorClass("LedgerAPIErrorWithMessage"); - createCustomErrorClass("LedgerAPINotAvailable"); - createCustomErrorClass("ManagerAppAlreadyInstalled"); - createCustomErrorClass("ManagerAppRelyOnBTC"); - createCustomErrorClass("ManagerAppDepInstallRequired"); - createCustomErrorClass("ManagerAppDepUninstallRequired"); - createCustomErrorClass("ManagerDeviceLocked"); - createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - createCustomErrorClass("ManagerNotEnoughSpace"); - createCustomErrorClass("ManagerUninstallBTCDep"); - createCustomErrorClass("NetworkDown"); - createCustomErrorClass("NoAddressesFound"); - createCustomErrorClass("NotEnoughBalance"); - createCustomErrorClass("NotEnoughBalanceToDelegate"); - createCustomErrorClass("NotEnoughBalanceInParentAccount"); - createCustomErrorClass("NotEnoughSpendableBalance"); - createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - createCustomErrorClass("NoAccessToCamera"); - createCustomErrorClass("NotEnoughGas"); - createCustomErrorClass("NotSupportedLegacyAddress"); - createCustomErrorClass("GasLessThanEstimate"); - createCustomErrorClass("PasswordsDontMatch"); - createCustomErrorClass("PasswordIncorrect"); - createCustomErrorClass("RecommendSubAccountsToEmpty"); - createCustomErrorClass("RecommendUndelegation"); - createCustomErrorClass("TimeoutTagged"); - createCustomErrorClass("UnexpectedBootloader"); - createCustomErrorClass("MCUNotGenuineToDashboard"); - createCustomErrorClass("RecipientRequired"); - createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - createCustomErrorClass("UpdateFetchFileFail"); - createCustomErrorClass("UpdateIncorrectHash"); - createCustomErrorClass("UpdateIncorrectSig"); - createCustomErrorClass("UpdateYourApp"); - createCustomErrorClass("UserRefusedDeviceNameChange"); - createCustomErrorClass("UserRefusedAddress"); - createCustomErrorClass("UserRefusedFirmwareUpdate"); - createCustomErrorClass("UserRefusedAllowManager"); - createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - createCustomErrorClass("TransportOpenUserCancelled"); - createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - createCustomErrorClass("TransportWebUSBGestureRequired"); - createCustomErrorClass("DeviceShouldStayInApp"); - createCustomErrorClass("WebsocketConnectionError"); - createCustomErrorClass("WebsocketConnectionFailed"); - createCustomErrorClass("WrongDeviceForAccount"); - createCustomErrorClass("WrongAppForCurrency"); - createCustomErrorClass("ETHAddressNonEIP"); - createCustomErrorClass("CantScanQRCode"); - createCustomErrorClass("FeeNotLoaded"); - createCustomErrorClass("FeeRequired"); - createCustomErrorClass("FeeTooHigh"); - createCustomErrorClass("SyncError"); - createCustomErrorClass("PairingFailed"); - createCustomErrorClass("GenuineCheckFailed"); - createCustomErrorClass("LedgerAPI4xx"); - createCustomErrorClass("LedgerAPI5xx"); - createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - createCustomErrorClass("NoDBPathGiven"); - createCustomErrorClass("DBWrongPassword"); - createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa, - }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - - /** - */ - - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - class Transport { - constructor() { - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - - this.send = async (cla, ins, p1, p2, data = Buffer$k.alloc(0), statusList = [StatusCodes.OK]) => { - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - - const response = await this.exchange(Buffer$k.concat([Buffer$k.from([cla, ins, p1, p2]), Buffer$k.from([data.length]), data])); - const sw = response.readUInt16BE(response.length - 2); - - if (!statusList.some(s => s === sw)) { - throw new TransportStatusError(sw); - } - - return response; - }; - - this.exchangeBusyPromise = void 0; - - this.exchangeAtomicImpl = async f => { - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - - let resolveBusy; - const busyPromise = new Promise(r => { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - let unresponsiveReached = false; - const timeout = setTimeout(() => { - unresponsiveReached = true; - this.emit("unresponsive"); - }, this.unresponsiveTimeout); - - try { - const res = await f(); - - if (unresponsiveReached) { - this.emit("responsive"); - } - - return res; - } finally { - clearTimeout(timeout); - if (resolveBusy) resolveBusy(); - this.exchangeBusyPromise = null; - } - }; - - this._appAPIlock = null; - } - - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - exchange(_apdu) { - throw new Error("exchange not implemented"); - } - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - - - setScrambleKey(_key) {} - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - - - close() { - return Promise.resolve(); - } - - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - on(eventName, cb) { - this._events.on(eventName, cb); - } - /** - * Stop listening to an event on an instance of transport. - */ - - - off(eventName, cb) { - this._events.removeListener(eventName, cb); - } - - emit(event, ...args) { - this._events.emit(event, ...args); - } - /** - * Enable or not logs of the binary exchange - */ - - - setDebugMode() { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - } - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - - - setExchangeTimeout(exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - } - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - - - setExchangeUnresponsiveTimeout(unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - } - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - - - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - static create(openTimeout = 3000, listenTimeout) { - return new Promise((resolve, reject) => { - let found = false; - const sub = this.listen({ - next: e => { - found = true; - if (sub) sub.unsubscribe(); - if (listenTimeoutId) clearTimeout(listenTimeoutId); - this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: e => { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - reject(e); - }, - complete: () => { - if (listenTimeoutId) clearTimeout(listenTimeoutId); - - if (!found) { - reject(new TransportError(this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - const listenTimeoutId = listenTimeout ? setTimeout(() => { - sub.unsubscribe(); - reject(new TransportError(this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) : null; - }); - } - - decorateAppAPIMethods(self, methods, scrambleKey) { - for (let methodName of methods) { - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - - decorateAppAPIMethod(methodName, f, ctx, scrambleKey) { - return async (...args) => { - const { - _appAPIlock - } = this; - - if (_appAPIlock) { - return Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked")); - } - - try { - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return await f.apply(ctx, args); - } finally { - this._appAPIlock = null; - } - }; - } - - } - Transport.isSupported = void 0; - Transport.list = void 0; - Transport.listen = void 0; - Transport.open = void 0; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - - /** - * A Log object - */ - let id = 0; - const subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - - const log = (type, message, data) => { - const obj = { - type, - id: String(++id), - date: new Date() - }; - if (message) obj.message = message; - if (data) obj.data = data; - dispatch(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - - const listen = cb => { - subscribers.push(cb); - return () => { - const i = subscribers.indexOf(cb); - - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - - function dispatch(log) { - for (let i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } catch (e) { - console.error(e); - } - } - } // for debug purpose - - - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; - } - - function wrapU2FTransportError(originalError, message, id) { - const err = new TransportError(message, id); // $FlowFixMe - - err.originalError = originalError; - return err; - } - - function wrapApdu(apdu, key) { - const result = Buffer$k.alloc(apdu.length); - - for (let i = 0; i < apdu.length; i++) { - result[i] = apdu[i] ^ key[i % key.length]; - } - - return result; - } // Convert from normal to web-safe, strip trailing "="s - - - const webSafe64 = base64 => base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); // Convert from web-safe to normal, add trailing "="s - - - const normal64 = base64 => base64.replace(/-/g, "+").replace(/_/g, "/") + "==".substring(0, 3 * base64.length % 4); - - function attemptExchange(apdu, timeoutMillis, scrambleKey, unwrap) { - const keyHandle = wrapApdu(apdu, scrambleKey); - const challenge = Buffer$k.from("0000000000000000000000000000000000000000000000000000000000000000", "hex"); - const signRequest = { - version: "U2F_V2", - keyHandle: webSafe64(keyHandle.toString("base64")), - challenge: webSafe64(challenge.toString("base64")), - appId: location.origin - }; - log("apdu", "=> " + apdu.toString("hex")); - return u2fApi.sign(signRequest, timeoutMillis / 1000).then(response => { - const { - signatureData - } = response; - - if (typeof signatureData === "string") { - const data = Buffer$k.from(normal64(signatureData), "base64"); - let result; - - if (!unwrap) { - result = data; - } else { - result = data.slice(5); - } - - log("apdu", "<= " + result.toString("hex")); - return result; - } else { - throw response; - } - }); - } - - let transportInstances = []; - - function emitDisconnect() { - transportInstances.forEach(t => t.emit("disconnect")); - transportInstances = []; - } - - function isTimeoutU2FError(u2fError) { - return u2fError.metaData.code === 5; - } - /** - * U2F web Transport implementation - * @example - * import TransportU2F from "@ledgerhq/hw-transport-u2f"; - * ... - * TransportU2F.create().then(transport => ...) - */ - - - class TransportU2F extends Transport { - /* - */ - - /* - */ - - /** - * static function to create a new Transport from a connected Ledger device discoverable via U2F (browser support) - */ - static async open(_, _openTimeout = 5000) { - return new TransportU2F(); - } - - constructor() { - super(); - this.scrambleKey = void 0; - this.unwrap = true; - transportInstances.push(this); - } - /** - * Exchange with the device using APDU protocol. - * @param apdu - * @returns a promise of apdu response - */ - - - async exchange(apdu) { - try { - return await attemptExchange(apdu, this.exchangeTimeout, this.scrambleKey, this.unwrap); - } catch (e) { - const isU2FError = typeof e.metaData === "object"; - - if (isU2FError) { - if (isTimeoutU2FError(e)) { - emitDisconnect(); - } // the wrapping make error more usable and "printable" to the end user. - - - throw wrapU2FTransportError(e, "Failed to sign with Ledger device: U2F " + e.metaData.type, "U2F_" + e.metaData.code); - } else { - throw e; - } - } - } - /** - */ - - - setScrambleKey(scrambleKey) { - this.scrambleKey = Buffer$k.from(scrambleKey, "ascii"); - } - /** - */ - - - setUnwrap(unwrap) { - this.unwrap = unwrap; - } - - close() { - // u2f have no way to clean things up - return Promise.resolve(); - } - - } - TransportU2F.isSupported = u2fApi.isSupported; - - TransportU2F.list = () => // this transport is not discoverable but we are going to guess if it is here with isSupported() - u2fApi.isSupported().then(supported => supported ? [null] : []); - - TransportU2F.listen = observer => { - let unsubscribed = false; - u2fApi.isSupported().then(supported => { - if (unsubscribed) return; - - if (supported) { - observer.next({ - type: "add", - descriptor: null - }); - observer.complete(); - } else { - observer.error(new TransportError("U2F browser support is needed for Ledger. " + "Please use Chrome, Opera or Firefox with a U2F extension. " + "Also make sure you're on an HTTPS connection", "U2FNotSupported")); - } - }); - return { - unsubscribe: () => { - unsubscribed = true; - } - }; - }; - - var TransportU2F$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': TransportU2F - }); - exports.Btc = Btc$1; exports.Log = index; - exports.TransportU2F = TransportU2F$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; @@ -42338,6 +42221,5 @@ window.Buffer = buffer.Buffer; window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; -window.TransportU2F = NewLedger.TransportU2F.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From 80531a6e16fbbeed8f24b87e2c67f9c3c9a8be70 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 26 Jan 2022 13:25:52 +1100 Subject: [PATCH 42/78] new version --- js/ledger.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 93806e2d..cadc424e 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -39268,12 +39268,12 @@ window.Buffer = buffer.Buffer; }; function signP2SHTransaction(transport, arg) { return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, startTime, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; return __generator$6(this, function (_c) { switch (_c.label) { case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; nullScript = Buffer$l.alloc(0); nullPrevout = Buffer$l.alloc(0); defaultVersion = Buffer$l.alloc(4); @@ -39285,10 +39285,12 @@ window.Buffer = buffer.Buffer; resuming = false; targetTransaction = { inputs: [], + timestamp: Buffer$l.alloc(0), version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; outputScript = Buffer$l.from(outputScriptHex, "hex"); + startTime = Date.now(); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); @@ -39366,6 +39368,10 @@ window.Buffer = buffer.Buffer; : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$l.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } if (segwit) { pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; } From 8e6a2d375df3c9246027407ee872ced7958c2fce Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Sat, 5 Feb 2022 09:52:58 +1100 Subject: [PATCH 43/78] new version --- js/ledger.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index cadc424e..2a452bd0 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -39268,7 +39268,7 @@ window.Buffer = buffer.Buffer; }; function signP2SHTransaction(transport, arg) { return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, startTime, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; return __generator$6(this, function (_c) { switch (_c.label) { @@ -39283,6 +39283,7 @@ window.Buffer = buffer.Buffer; signatures = []; firstRun = true; resuming = false; + startTime = Date.now(); targetTransaction = { inputs: [], timestamp: Buffer$l.alloc(0), @@ -39290,7 +39291,6 @@ window.Buffer = buffer.Buffer; }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; outputScript = Buffer$l.from(outputScriptHex, "hex"); - startTime = Date.now(); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); @@ -39378,7 +39378,7 @@ window.Buffer = buffer.Buffer; else { pseudoTX.inputs[i].script = script; } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; case 14: _c.sent(); if (!!segwit) return [3 /*break*/, 16]; @@ -40587,7 +40587,7 @@ window.Buffer = buffer.Buffer; * Bitcoin API. * * @example - * import Btc from "@backpacker69/hw-app-btc"; + * import Btc from "@ledgerhq/hw-app-btc"; * const btc = new Btc(transport) */ var Btc = /** @class */ (function () { From fd6e66dbb60090c25512da4196a727d01fd360a2 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 08:36:43 +1100 Subject: [PATCH 44/78] new version --- js/ledger.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 2a452bd0..37ef6c0c 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1,7 +1,3 @@ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).buffer=t()}}(function(){return function(){return function t(r,e,n){function i(f,u){if(!e[f]){if(!r[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var h=new Error("Cannot find module '"+f+"'");throw h.code="MODULE_NOT_FOUND",h}var a=e[f]={exports:{}};r[f][0].call(a.exports,function(t){return i(r[f][1][t]||t)},a,a.exports,t,r,e,n)}return e[f].exports}for(var o="function"==typeof require&&require,f=0;fo)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=r.prototype,e}function r(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return u(t,r,e)}function u(t,e,n){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!r.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var n=0|c(t,e),i=f(n),o=i.write(t,e);o!==n&&(i=i.slice(0,o));return i}(t,e);if(ArrayBuffer.isView(t))return a(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(z(t,ArrayBuffer)||t&&z(t.buffer,ArrayBuffer))return function(t,e,n){if(e<0||t.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function c(t,e){if(r.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||z(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var n=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var o=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return P(t).length;default:if(o)return i?-1:N(t).length;e=(""+e).toLowerCase(),o=!0}}function l(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function y(t,e,n,i,o){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),D(n=+n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof e&&(e=r.from(e,i)),r.isBuffer(e))return 0===e.length?-1:g(t,e,n,i,o);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):g(t,[e],n,i,o);throw new TypeError("val must be string, number or Buffer")}function g(t,r,e,n,i){var o,f=1,u=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;f=2,u/=2,s/=2,e/=2}function h(t,r){return 1===f?t[r]:t.readUInt16BE(r*f)}if(i){var a=-1;for(o=e;ou&&(e=u-s),o=e;o>=0;o--){for(var p=!0,c=0;ci&&(n=i):n=i;var o=r.length;n>o/2&&(n=o/2);for(var f=0;f>8,i=e%256,o.push(i),o.push(n);return o}(r,t.length-e),t,e,n)}function A(t,r,e){return 0===r&&e===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(r,e))}function B(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i239?4:h>223?3:h>191?2:1;if(i+p<=e)switch(p){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],f=t[i+2],128==(192&o)&&128==(192&f)&&(s=(15&h)<<12|(63&o)<<6|63&f)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],f=t[i+2],u=t[i+3],128==(192&o)&&128==(192&f)&&128==(192&u)&&(s=(15&h)<<18|(63&o)<<12|(63&f)<<6|63&u)>65535&&s<1114112&&(a=s)}null===a?(a=65533,p=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=p}return function(t){var r=t.length;if(r<=U)return String.fromCharCode.apply(String,t);var e="",n=0;for(;nthis.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return I(this,r,e);case"utf8":case"utf-8":return B(this,r,e);case"ascii":return _(this,r,e);case"latin1":case"binary":return T(this,r,e);case"base64":return A(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},r.prototype.toLocaleString=r.prototype.toString,r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),""},r.prototype.compare=function(t,e,n,i,o){if(z(t,Uint8Array)&&(t=r.from(t,t.offset,t.byteLength)),!r.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),e<0||n>t.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&e>=n)return 0;if(i>=o)return-1;if(e>=n)return 1;if(this===t)return 0;for(var f=(o>>>=0)-(i>>>=0),u=(n>>>=0)-(e>>>=0),s=Math.min(f,u),h=this.slice(i,o),a=t.slice(e,n),p=0;p>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return w(this,t,r,e);case"utf8":case"utf-8":return d(this,t,r,e);case"ascii":return v(this,t,r,e);case"latin1":case"binary":return b(this,t,r,e);case"base64":return m(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var U=4096;function _(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;in)&&(e=n);for(var i="",o=r;oe)throw new RangeError("Trying to access beyond buffer length")}function L(t,e,n,i,o,f){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||et.length)throw new RangeError("Index out of range")}function R(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function x(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,4),i.write(t,r,e,n,23,4),e+4}function M(t,r,e,n,o){return r=+r,e>>>=0,o||R(t,0,e,8),i.write(t,r,e,n,52,8),e+8}r.prototype.slice=function(t,e){var n=this.length;(t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},r.prototype.readUInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,r){return t>>>=0,r||C(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*r)),n},r.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||C(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},r.prototype.readInt8=function(t,r){return t>>>=0,r||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt16BE=function(t,r){t>>>=0,r||C(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},r.prototype.readInt32LE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,r){return t>>>=0,r||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,r){return t>>>=0,r||C(t,4,this.length),i.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,r){return t>>>=0,r||C(t,8,this.length),i.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r>>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o>>=0,e>>>=0,n)||L(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},r.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,255,0),this[r]=255&t,r+1},r.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},r.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=0,f=1,u=0;for(this[r]=255&t;++o>0)-u&255;return r+e},r.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var i=Math.pow(2,8*e-1);L(this,t,r,e,i-1,-i)}var o=e-1,f=1,u=0;for(this[r+o]=255&t;--o>=0&&(f*=256);)t<0&&0===u&&0!==this[r+o+1]&&(u=1),this[r+o]=(t/f>>0)-u&255;return r+e},r.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},r.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},r.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},r.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},r.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||L(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},r.prototype.writeFloatLE=function(t,r,e){return x(this,t,r,!0,e)},r.prototype.writeFloatBE=function(t,r,e){return x(this,t,r,!1,e)},r.prototype.writeDoubleLE=function(t,r,e){return M(this,t,r,!0,e)},r.prototype.writeDoubleBE=function(t,r,e){return M(this,t,r,!1,e)},r.prototype.copy=function(t,e,n,i){if(!r.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--f)t[f+e]=this[f+n];else Uint8Array.prototype.set.call(t,this.subarray(n,i),e);return o},r.prototype.fill=function(t,e,n,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!r.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var o=t.charCodeAt(0);("utf8"===i&&o<128||"latin1"===i)&&(t=o)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(f=e;f55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(f+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function P(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function j(t,r,e,n){for(var i=0;i=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function z(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function D(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":2,buffer:5,ieee754:3}],2:[function(t,r,e){"use strict";e.byteLength=function(t){var r=h(t),e=r[0],n=r[1];return 3*(e+n)/4-n},e.toByteArray=function(t){for(var r,e=h(t),n=e[0],f=e[1],u=new o(function(t,r,e){return 3*(r+e)/4-e}(0,n,f)),s=0,a=f>0?n-4:n,p=0;p>16&255,u[s++]=r>>8&255,u[s++]=255&r;2===f&&(r=i[t.charCodeAt(p)]<<2|i[t.charCodeAt(p+1)]>>4,u[s++]=255&r);1===f&&(r=i[t.charCodeAt(p)]<<10|i[t.charCodeAt(p+1)]<<4|i[t.charCodeAt(p+2)]>>2,u[s++]=r>>8&255,u[s++]=255&r);return u},e.fromByteArray=function(t){for(var r,e=t.length,i=e%3,o=[],f=0,u=e-i;fu?u:f+16383));1===i?(r=t[e-1],o.push(n[r>>2]+n[r<<4&63]+"==")):2===i&&(r=(t[e-2]<<8)+t[e-1],o.push(n[r>>10]+n[r>>4&63]+n[r<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,s=f.length;u0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function a(t,r,e){for(var i,o,f=[],u=r;u>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return f.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],3:[function(t,r,e){e.read=function(t,r,e,n,i){var o,f,u=8*i-n-1,s=(1<>1,a=-7,p=e?i-1:0,c=e?-1:1,l=t[r+p];for(p+=c,o=l&(1<<-a)-1,l>>=-a,a+=u;a>0;o=256*o+t[r+p],p+=c,a-=8);for(f=o&(1<<-a)-1,o>>=-a,a+=n;a>0;f=256*f+t[r+p],p+=c,a-=8);if(0===o)o=1-h;else{if(o===s)return f?NaN:1/0*(l?-1:1);f+=Math.pow(2,n),o-=h}return(l?-1:1)*f*Math.pow(2,o-n)},e.write=function(t,r,e,n,i,o){var f,u,s,h=8*o-i-1,a=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:o-1,y=n?1:-1,g=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(u=isNaN(r)?1:0,f=a):(f=Math.floor(Math.log(r)/Math.LN2),r*(s=Math.pow(2,-f))<1&&(f--,s*=2),(r+=f+p>=1?c/s:c*Math.pow(2,1-p))*s>=2&&(f++,s/=2),f+p>=a?(u=0,f=a):f+p>=1?(u=(r*s-1)*Math.pow(2,i),f+=p):(u=r*Math.pow(2,p-1)*Math.pow(2,i),f=0));i>=8;t[e+l]=255&u,l+=y,u/=256,i-=8);for(f=f<0;t[e+l]=255&f,l+=y,f/=256,h-=8);t[e+l-y]|=128*g}},{}],4:[function(t,r,e){arguments[4][2][0].apply(e,arguments)},{dup:2}],5:[function(t,r,e){arguments[4][1][0].apply(e,arguments)},{"base64-js":4,buffer:5,dup:1,ieee754:6}],6:[function(t,r,e){arguments[4][3][0].apply(e,arguments)},{dup:3}]},{},[1])(1)}); -window.global = window; -window.Buffer = buffer.Buffer; - (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : From a8dfa5aa7becc1bc042af391eb40bd726aa00b7b Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 11:37:02 +1100 Subject: [PATCH 45/78] new version --- js/ledger.js | 19294 +++++++++++++++++++++++-------------------------- 1 file changed, 9048 insertions(+), 10246 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 37ef6c0c..c69a2c3a 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -1029,12 +1029,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$l.TYPED_ARRAY_SUPPORT + return Buffer$m.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1043,14 +1043,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$l(length); + that = new Buffer$m(length); } that.length = length; } @@ -1068,9 +1068,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$l (arg, encodingOrOffset, length) { - if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { - return new Buffer$l(arg, encodingOrOffset, length) + function Buffer$m (arg, encodingOrOffset, length) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { + return new Buffer$m(arg, encodingOrOffset, length) } // Common case. @@ -1085,11 +1085,11 @@ return from$1(this, arg, encodingOrOffset, length) } - Buffer$l.poolSize = 8192; // not used by this implementation + Buffer$m.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$l._augment = function (arr) { - arr.__proto__ = Buffer$l.prototype; + Buffer$m._augment = function (arr) { + arr.__proto__ = Buffer$m.prototype; return arr }; @@ -1117,13 +1117,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$l.from = function (value, encodingOrOffset, length) { + Buffer$m.from = function (value, encodingOrOffset, length) { return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { - Buffer$l.prototype.__proto__ = Uint8Array.prototype; - Buffer$l.__proto__ = Uint8Array; + if (Buffer$m.TYPED_ARRAY_SUPPORT) { + Buffer$m.prototype.__proto__ = Uint8Array.prototype; + Buffer$m.__proto__ = Uint8Array; } function assertSize (size) { @@ -1154,14 +1154,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$l.alloc = function (size, fill, encoding) { + Buffer$m.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1172,13 +1172,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$l.allocUnsafe = function (size) { + Buffer$m.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$l.allocUnsafeSlow = function (size) { + Buffer$m.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1187,7 +1187,7 @@ encoding = 'utf8'; } - if (!Buffer$l.isEncoding(encoding)) { + if (!Buffer$m.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1234,10 +1234,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$l.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1284,12 +1284,12 @@ } return length | 0 } - Buffer$l.isBuffer = isBuffer; + Buffer$m.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$l.compare = function compare (a, b) { + Buffer$m.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1312,7 +1312,7 @@ return 0 }; - Buffer$l.isEncoding = function isEncoding (encoding) { + Buffer$m.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1331,13 +1331,13 @@ } }; - Buffer$l.concat = function concat (list, length) { + Buffer$m.concat = function concat (list, length) { if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$l.alloc(0) + return Buffer$m.alloc(0) } var i; @@ -1348,7 +1348,7 @@ } } - var buffer = Buffer$l.allocUnsafe(length); + var buffer = Buffer$m.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1404,7 +1404,7 @@ } } } - Buffer$l.byteLength = byteLength$1; + Buffer$m.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1478,7 +1478,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$l.prototype._isBuffer = true; + Buffer$m.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1486,7 +1486,7 @@ b[m] = i; } - Buffer$l.prototype.swap16 = function swap16 () { + Buffer$m.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1497,7 +1497,7 @@ return this }; - Buffer$l.prototype.swap32 = function swap32 () { + Buffer$m.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1509,7 +1509,7 @@ return this }; - Buffer$l.prototype.swap64 = function swap64 () { + Buffer$m.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1523,20 +1523,20 @@ return this }; - Buffer$l.prototype.toString = function toString () { + Buffer$m.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$l.prototype.equals = function equals (b) { + Buffer$m.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$l.compare(this, b) === 0 + return Buffer$m.compare(this, b) === 0 }; - Buffer$l.prototype.inspect = function inspect () { + Buffer$m.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1546,7 +1546,7 @@ return '' }; - Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1645,7 +1645,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$l.from(val, encoding); + val = Buffer$m.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1657,7 +1657,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$l.TYPED_ARRAY_SUPPORT && + if (Buffer$m.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1727,15 +1727,15 @@ return -1 } - Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1786,7 +1786,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$l.prototype.write = function write (string, offset, length, encoding) { + Buffer$m.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1858,7 +1858,7 @@ } }; - Buffer$l.prototype.toJSON = function toJSON () { + Buffer$m.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2011,7 +2011,7 @@ return res } - Buffer$l.prototype.slice = function slice (start, end) { + Buffer$m.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2033,12 +2033,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$l.prototype; + newBuf.__proto__ = Buffer$m.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$l(sliceLen, undefined); + newBuf = new Buffer$m(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2055,7 +2055,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2070,7 +2070,7 @@ return val }; - Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2086,22 +2086,22 @@ return val }; - Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2110,7 +2110,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2119,7 +2119,7 @@ this[offset + 3]) }; - Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2137,7 +2137,7 @@ return val }; - Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2155,25 +2155,25 @@ return val }; - Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2182,7 +2182,7 @@ (this[offset + 3] << 24) }; - Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2191,22 +2191,22 @@ (this[offset + 3]) }; - Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2217,7 +2217,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2236,7 +2236,7 @@ return offset + byteLength }; - Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2255,11 +2255,11 @@ return offset + byteLength }; - Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2272,11 +2272,11 @@ } } - Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2285,11 +2285,11 @@ return offset + 2 }; - Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2305,11 +2305,11 @@ } } - Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2320,11 +2320,11 @@ return offset + 4 }; - Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2335,7 +2335,7 @@ return offset + 4 }; - Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2358,7 +2358,7 @@ return offset + byteLength }; - Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2381,21 +2381,21 @@ return offset + byteLength }; - Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2404,11 +2404,11 @@ return offset + 2 }; - Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2417,11 +2417,11 @@ return offset + 2 }; - Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2432,12 +2432,12 @@ return offset + 4 }; - Buffer$l.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$m.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; - if (Buffer$l.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2461,11 +2461,11 @@ return offset + 4 } - Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2477,16 +2477,16 @@ return offset + 8 } - Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2518,7 +2518,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2538,7 +2538,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$l.prototype.fill = function fill (val, start, end, encoding) { + Buffer$m.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2558,7 +2558,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2587,7 +2587,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$l(val, encoding).toString()); + : utf8ToBytes(new Buffer$m(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5747,7 +5747,7 @@ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require$2 = buffer, - Buffer$k = _require$2.Buffer; + Buffer$l = _require$2.Buffer; var _require2 = require$$3, inspect$1 = _require2.inspect; @@ -5755,7 +5755,7 @@ var custom = inspect$1 && inspect$1.custom || 'inspect'; function copyBuffer(src, target, offset) { - Buffer$k.prototype.copy.call(src, target, offset); + Buffer$l.prototype.copy.call(src, target, offset); } var buffer_list = @@ -5822,8 +5822,8 @@ }, { key: "concat", value: function concat(n) { - if (this.length === 0) return Buffer$k.alloc(0); - var ret = Buffer$k.allocUnsafe(n >>> 0); + if (this.length === 0) return Buffer$l.alloc(0); + var ret = Buffer$l.allocUnsafe(n >>> 0); var p = this.head; var i = 0; @@ -5897,7 +5897,7 @@ }, { key: "_getBuffer", value: function _getBuffer(n) { - var ret = Buffer$k.allocUnsafe(n); + var ret = Buffer$l.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); @@ -6304,16 +6304,16 @@ /**/ - var Buffer$j = buffer.Buffer; + var Buffer$k = buffer.Buffer; var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer$1(chunk) { - return Buffer$j.from(chunk); + return Buffer$k.from(chunk); } function _isUint8Array$1(obj) { - return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; } var destroyImpl$1 = destroy_1; @@ -6528,7 +6528,7 @@ var isBuf = !state.objectMode && _isUint8Array$1(chunk); - if (isBuf && !Buffer$j.isBuffer(chunk)) { + if (isBuf && !Buffer$k.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer$1(chunk); } @@ -6579,7 +6579,7 @@ function decodeChunk$1(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$j.from(chunk, encoding); + chunk = Buffer$k.from(chunk, encoding); } return chunk; @@ -7048,14 +7048,14 @@ } }); - var string_decoder = {}; + var string_decoder$1 = {}; /**/ - var Buffer$i = safeBuffer.exports.Buffer; + var Buffer$j = safeBuffer.exports.Buffer; /**/ - var isEncoding = Buffer$i.isEncoding || function (encoding) { + var isEncoding = Buffer$j.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': @@ -7096,15 +7096,15 @@ // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + if (typeof nenc !== 'string' && (Buffer$j.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. - var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(encoding) { + string_decoder$1.StringDecoder = StringDecoder$3; + function StringDecoder$3(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { @@ -7129,10 +7129,10 @@ } this.lastNeed = 0; this.lastTotal = 0; - this.lastChar = Buffer$i.allocUnsafe(nb); + this.lastChar = Buffer$j.allocUnsafe(nb); } - StringDecoder$2.prototype.write = function (buf) { + StringDecoder$3.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; @@ -7148,13 +7148,13 @@ return r || ''; }; - StringDecoder$2.prototype.end = utf8End; + StringDecoder$3.prototype.end = utf8End; // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; + StringDecoder$3.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.prototype.fillLast = function (buf) { + StringDecoder$3.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); @@ -7657,28 +7657,28 @@ /**/ - var Buffer$h = buffer.Buffer; + var Buffer$i = buffer.Buffer; var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { - return Buffer$h.from(chunk); + return Buffer$i.from(chunk); } function _isUint8Array(obj) { - return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = require$$3; - var debug$5; + var debug$9; if (debugUtil && debugUtil.debuglog) { - debug$5 = debugUtil.debuglog('stream'); + debug$9 = debugUtil.debuglog('stream'); } else { - debug$5 = function debug() {}; + debug$9 = function debug() {}; } /**/ @@ -7697,7 +7697,7 @@ ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - var StringDecoder$1; + var StringDecoder$2; var createReadableStreamAsyncIterator; var from; @@ -7774,8 +7774,8 @@ this.encoding = null; if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + this.decoder = new StringDecoder$2(options.encoding); this.encoding = options.encoding; } } @@ -7842,7 +7842,7 @@ encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$h.from(chunk, encoding); + chunk = Buffer$i.from(chunk, encoding); encoding = ''; } @@ -7861,7 +7861,7 @@ }; function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$5('readableAddChunk', chunk); + debug$9('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { @@ -7874,7 +7874,7 @@ if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { chunk = _uint8ArrayToBuffer(chunk); } @@ -7936,8 +7936,8 @@ Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + var decoder = new StringDecoder$2(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: @@ -8004,7 +8004,7 @@ Readable$1.prototype.read = function (n) { - debug$5('read', n); + debug$9('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -8013,7 +8013,7 @@ // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$5('read: emitReadable', state.length, state.ended); + debug$9('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); return null; } @@ -8048,20 +8048,20 @@ var doRead = state.needReadable; - debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$5('length less than watermark', doRead); + debug$9('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$5('reading or ended', doRead); + debug$9('reading or ended', doRead); } else if (doRead) { - debug$5('do read'); + debug$9('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -8099,7 +8099,7 @@ }; function onEofChunk$1(stream, state) { - debug$5('onEofChunk'); + debug$9('onEofChunk'); if (state.ended) return; if (state.decoder) { @@ -8134,11 +8134,11 @@ function emitReadable$1(stream) { var state = stream._readableState; - debug$5('emitReadable', state.needReadable, state.emittedReadable); + debug$9('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { - debug$5('emitReadable', state.flowing); + debug$9('emitReadable', state.flowing); state.emittedReadable = true; nextTick(emitReadable_$1, stream); } @@ -8146,7 +8146,7 @@ function emitReadable_$1(stream) { var state = stream._readableState; - debug$5('emitReadable_', state.destroyed, state.length, state.ended); + debug$9('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); @@ -8202,7 +8202,7 @@ // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; - debug$5('maybeReadMore read 0'); + debug$9('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; @@ -8238,14 +8238,14 @@ } state.pipesCount += 1; - debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { - debug$5('onunpipe'); + debug$9('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { @@ -8256,7 +8256,7 @@ } function onend() { - debug$5('onend'); + debug$9('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() @@ -8269,7 +8269,7 @@ var cleanedUp = false; function cleanup() { - debug$5('cleanup'); // cleanup event handlers once the pipe is broken + debug$9('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -8291,9 +8291,9 @@ src.on('data', ondata); function ondata(chunk) { - debug$5('ondata'); + debug$9('ondata'); var ret = dest.write(chunk); - debug$5('dest.write', ret); + debug$9('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible @@ -8301,7 +8301,7 @@ // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$5('false write response, pause', state.awaitDrain); + debug$9('false write response, pause', state.awaitDrain); state.awaitDrain++; } @@ -8312,7 +8312,7 @@ function onerror(er) { - debug$5('onerror', er); + debug$9('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); @@ -8329,7 +8329,7 @@ dest.once('close', onclose); function onfinish() { - debug$5('onfinish'); + debug$9('onfinish'); dest.removeListener('close', onclose); unpipe(); } @@ -8337,7 +8337,7 @@ dest.once('finish', onfinish); function unpipe() { - debug$5('unpipe'); + debug$9('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to @@ -8345,7 +8345,7 @@ dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { - debug$5('pipe resume'); + debug$9('pipe resume'); src.resume(); } @@ -8355,7 +8355,7 @@ function pipeOnDrain$1(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; - debug$5('pipeOnDrain', state.awaitDrain); + debug$9('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { @@ -8430,7 +8430,7 @@ state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; - debug$5('on readable', state.length, state.reading); + debug$9('on readable', state.length, state.reading); if (state.length) { emitReadable$1(this); @@ -8491,7 +8491,7 @@ } function nReadingNextTick$1(self) { - debug$5('readable nexttick read 0'); + debug$9('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. @@ -8501,7 +8501,7 @@ var state = this._readableState; if (!state.flowing) { - debug$5('resume'); // we flow only if there is no one listening + debug$9('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() @@ -8521,7 +8521,7 @@ } function resume_$1(stream, state) { - debug$5('resume', state.reading); + debug$9('resume', state.reading); if (!state.reading) { stream.read(0); @@ -8534,10 +8534,10 @@ } Readable$1.prototype.pause = function () { - debug$5('call pause flowing=%j', this._readableState.flowing); + debug$9('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { - debug$5('pause'); + debug$9('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -8548,7 +8548,7 @@ function flow$1(stream) { var state = stream._readableState; - debug$5('flow', state.flowing); + debug$9('flow', state.flowing); while (state.flowing && stream.read() !== null) { } @@ -8563,7 +8563,7 @@ var state = this._readableState; var paused = false; stream.on('end', function () { - debug$5('wrapped end'); + debug$9('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); @@ -8573,7 +8573,7 @@ _this.push(null); }); stream.on('data', function (chunk) { - debug$5('wrapped data'); + debug$9('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; @@ -8605,7 +8605,7 @@ this._read = function (n) { - debug$5('wrapped _read', n); + debug$9('wrapped _read', n); if (paused) { paused = false; @@ -8690,7 +8690,7 @@ function endReadable$1(stream) { var state = stream._readableState; - debug$5('endReadable', state.endEmitted); + debug$9('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; @@ -8699,7 +8699,7 @@ } function endReadableNT$1(state, stream) { - debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; @@ -8996,12 +8996,12 @@ exports.pipeline = pipeline_1; }(readableBrowser, readableBrowser.exports)); - var Buffer$g = safeBuffer.exports.Buffer; + var Buffer$h = safeBuffer.exports.Buffer; var Transform$2 = readableBrowser.exports.Transform; var inherits$i = inherits_browser.exports; function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer') } } @@ -9009,7 +9009,7 @@ function HashBase$2 (blockSize) { Transform$2.call(this); - this._block = Buffer$g.allocUnsafe(blockSize); + this._block = Buffer$h.allocUnsafe(blockSize); this._blockSize = blockSize; this._blockOffset = 0; this._length = [0, 0, 0, 0]; @@ -9044,7 +9044,7 @@ HashBase$2.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data'); if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); // consume data var block = this._block; @@ -9093,7 +9093,7 @@ var inherits$h = inherits_browser.exports; var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + var Buffer$g = safeBuffer.exports.Buffer; var ARRAY16$1 = new Array(16); @@ -9207,7 +9207,7 @@ this._update(); // produce result - var buffer = Buffer$f.allocUnsafe(16); + var buffer = Buffer$g.allocUnsafe(16); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9237,7 +9237,7 @@ var md5_js = MD5$2; - var Buffer$e = buffer.Buffer; + var Buffer$f = buffer.Buffer; var inherits$g = inherits_browser.exports; var HashBase = hashBase; @@ -9365,7 +9365,7 @@ this._update(); // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); buffer.writeInt32LE(this._a, 0); buffer.writeInt32LE(this._b, 4); buffer.writeInt32LE(this._c, 8); @@ -9402,11 +9402,11 @@ var sha_js = {exports: {}}; - var Buffer$d = safeBuffer.exports.Buffer; + var Buffer$e = safeBuffer.exports.Buffer; // prototype class for hash functions function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); + this._block = Buffer$e.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; @@ -9415,7 +9415,7 @@ Hash$7.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); + data = Buffer$e.from(data, enc); } var block = this._block; @@ -9494,7 +9494,7 @@ var inherits$f = inherits_browser.exports; var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + var Buffer$d = safeBuffer.exports.Buffer; var K$4 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9566,7 +9566,7 @@ }; Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + var H = Buffer$d.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9590,7 +9590,7 @@ var inherits$e = inherits_browser.exports; var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + var Buffer$c = safeBuffer.exports.Buffer; var K$3 = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 @@ -9666,7 +9666,7 @@ }; Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + var H = Buffer$c.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); @@ -9689,7 +9689,7 @@ var inherits$d = inherits_browser.exports; var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + var Buffer$b = safeBuffer.exports.Buffer; var K$2 = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, @@ -9799,7 +9799,7 @@ }; Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); + var H = Buffer$b.allocUnsafe(32); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9826,7 +9826,7 @@ var inherits$c = inherits_browser.exports; var Sha256 = sha256$2; var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + var Buffer$a = safeBuffer.exports.Buffer; var W$2 = new Array(64); @@ -9854,7 +9854,7 @@ }; Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + var H = Buffer$a.allocUnsafe(28); H.writeInt32BE(this._a, 0); H.writeInt32BE(this._b, 4); @@ -9871,7 +9871,7 @@ var inherits$b = inherits_browser.exports; var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + var Buffer$9 = safeBuffer.exports.Buffer; var K$1 = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, @@ -10109,7 +10109,7 @@ }; Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + var H = Buffer$9.allocUnsafe(64); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10133,7 +10133,7 @@ var inherits$a = inherits_browser.exports; var SHA512$2 = sha512; var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; + var Buffer$8 = safeBuffer.exports.Buffer; var W = new Array(160); @@ -10169,7 +10169,7 @@ }; Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + var H = Buffer$8.allocUnsafe(48); function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset); @@ -10764,9 +10764,234 @@ return ret; }; + var string_decoder = {}; + + var StringDecoder_1; + // 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$7 = buffer.Buffer; + + var isBufferEncoding = Buffer$7.isEncoding + || function(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 assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$7(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; + + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$1.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder$1.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + Readable.ReadableState = ReadableState; - var debug$4 = debuglog('stream'); + var debug$8 = debuglog('stream'); inherits$9(Readable, EventEmitter$1); function prependListener(emitter, event, fn) { @@ -10880,7 +11105,7 @@ if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$l.from(chunk, encoding); + chunk = Buffer$m.from(chunk, encoding); encoding = ''; } } @@ -11005,7 +11230,7 @@ // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { - debug$4('read', n); + debug$8('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; @@ -11016,7 +11241,7 @@ // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); + debug$8('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } @@ -11053,21 +11278,21 @@ // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; - debug$4('need readable', doRead); + debug$8('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - debug$4('length less than watermark', doRead); + debug$8('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; - debug$4('reading or ended', doRead); + debug$8('reading or ended', doRead); } else if (doRead) { - debug$4('do read'); + debug$8('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. @@ -11134,14 +11359,14 @@ var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); + debug$8('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { - debug$4('emit readable'); + debug$8('emit readable'); stream.emit('readable'); flow(stream); } @@ -11162,7 +11387,7 @@ function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); + debug$8('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. @@ -11195,7 +11420,7 @@ break; } state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false); @@ -11204,14 +11429,14 @@ dest.on('unpipe', onunpipe); function onunpipe(readable) { - debug$4('onunpipe'); + debug$8('onunpipe'); if (readable === src) { cleanup(); } } function onend() { - debug$4('onend'); + debug$8('onend'); dest.end(); } @@ -11224,7 +11449,7 @@ var cleanedUp = false; function cleanup() { - debug$4('cleanup'); + debug$8('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); @@ -11252,7 +11477,7 @@ var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { - debug$4('ondata'); + debug$8('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { @@ -11261,7 +11486,7 @@ // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); + debug$8('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } @@ -11272,7 +11497,7 @@ // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { - debug$4('onerror', er); + debug$8('onerror', er); unpipe(); dest.removeListener('error', onerror); if (listenerCount(dest, 'error') === 0) dest.emit('error', er); @@ -11288,14 +11513,14 @@ } dest.once('close', onclose); function onfinish() { - debug$4('onfinish'); + debug$8('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { - debug$4('unpipe'); + debug$8('unpipe'); src.unpipe(dest); } @@ -11304,7 +11529,7 @@ // start the flow if it hasn't been started already. if (!state.flowing) { - debug$4('pipe resume'); + debug$8('pipe resume'); src.resume(); } @@ -11314,7 +11539,7 @@ function pipeOnDrain(src) { return function () { var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); + debug$8('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && src.listeners('data').length) { state.flowing = true; @@ -11398,7 +11623,7 @@ Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); + debug$8('readable nexttick read 0'); self.read(0); } @@ -11407,7 +11632,7 @@ Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { - debug$4('resume'); + debug$8('resume'); state.flowing = true; resume(this, state); } @@ -11423,7 +11648,7 @@ function resume_(stream, state) { if (!state.reading) { - debug$4('resume read 0'); + debug$8('resume read 0'); stream.read(0); } @@ -11435,9 +11660,9 @@ } Readable.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); + debug$8('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { - debug$4('pause'); + debug$8('pause'); this._readableState.flowing = false; this.emit('pause'); } @@ -11446,7 +11671,7 @@ function flow(stream) { var state = stream._readableState; - debug$4('flow', state.flowing); + debug$8('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } @@ -11459,7 +11684,7 @@ var self = this; stream.on('end', function () { - debug$4('wrapped end'); + debug$8('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); @@ -11469,7 +11694,7 @@ }); stream.on('data', function (chunk) { - debug$4('wrapped data'); + debug$8('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode @@ -11503,7 +11728,7 @@ // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function (n) { - debug$4('wrapped _read', n); + debug$8('wrapped _read', n); if (paused) { paused = false; stream.resume(); @@ -11590,7 +11815,7 @@ // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { - var ret = Buffer$l.allocUnsafe(n); + var ret = Buffer$m.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -12734,7 +12959,7 @@ var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$l.alloc(1 + paths.length * 4); + var buffer = Buffer$m.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -12923,7 +13148,7 @@ } crypto$5.hmacSHA512 = hmacSHA512; - var bn$1 = {exports: {}}; + var bn = {exports: {}}; (function (module) { (function (module, exports) { @@ -16369,7 +16594,7 @@ return res._forceRed(this); }; })(module, commonjsGlobal); - }(bn$1)); + }(bn)); var elliptic = {}; @@ -16446,4579 +16671,1131 @@ var utils$n = {}; - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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; - } + var minimalisticAssert = assert$f; - // BN + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; - this.negative = 0; - this.words = null; - this.length = 0; + var utils$m = {}; - // Reduction context - this.red = null; + (function (exports) { - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } + var utils = exports; - this._init(number || 0, base || 10, endian || 'be'); - } + 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 (typeof module === 'object') { - module.exports = BN; + 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 { - 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 = require('buffer').Buffer; + 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); } - } catch (e) { } + return res; + } + utils.toArray = toArray; - 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); - }; + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils.zero2 = zero2; - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + }(utils$m)); - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + (function (exports) { - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } + // 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); - 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); - } - } - } - }; + var ws = 1 << (w + 1); + var k = num.clone(); - 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; + 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 { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; + z = 0; } - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + naf[i] = z; + k.iushrn(1); + } - 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; - } + return naf; + } + utils.getNAF = getNAF; - 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; - } + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; - 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++; - } - } + 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; } - return this.strip(); - }; + jsf[0].push(u1); - 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' + var u2; + if ((m24 & 1) === 0) { + u2 = 0; } else { - return (c - 48) & 0xf; + m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; } - } + jsf[1].push(u2); - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); } - 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; - } - } - } + return jsf; + } + utils.getJSF = getJSF; - this.strip(); + 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 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; + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; + } + utils.parseBytes = parseBytes; - r *= mul; + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); + } + utils.intFromLE = intFromLE; + }(utils$n)); - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + var brorand = {exports: {}}; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + var r$1; - // '0' - '9' - } else { - r += c; - } - } - return r; - } + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + return r$1.generate(len); + }; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + function Rand(rand) { + this.rand = rand; + } + brorand.exports.Rand = Rand; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + Rand.prototype.generate = function generate(len) { + return this._rand(len); + }; - 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); - } - } + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; - for (i = 0; i < mod; i++) { - pow *= base; - } + 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; + }; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + // 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$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); - this.strip(); - }; + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { + } + } - 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; - }; + var curve = {}; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); - // 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(); - }; + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + // Curve configuration, optional + this.n = conf.n && new BN$8(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); - var zeros = []; - var groupSizes = []; - var groupBases = []; + this._bitLength = this.n ? this.n.bitLength() : 0; - 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; + // 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); } + } + var base = BaseCurve; - */ + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); + }; - 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' - ]; + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); + }; - 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 - ]; + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$e(p.precomputed); + var doubles = p._getDoubles(); - 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 - ]; + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + // 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 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; + 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(); + }; - 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); + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; - 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; - } + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; - assert(false, 'Base should be between 2 and 36'); - }; + // Get NAF form + var naf = getNAF(k, w, this._bitLength); - 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'); + // 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$e(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 (this.negative !== 0) ? -ret : ret; - }; + } + return p.type === 'affine' ? acc.toP() : acc; + }; - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; + // 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; + } - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + // 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; + } - 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'); + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + // 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 b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + 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 */ + ]; - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + 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; - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } - res[i] = b; - } + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; - for (; i < reqLength; i++) { - res[i] = 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; - return res; - }; + for (j = 0; j < len; j++) { + var z = tmp[j]; + 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 (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; - }; + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } } + // Zeroify references + for (i = 0; i < len; i++) + wnd[i] = null; - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + if (jacobianResult) + return acc; + else + return acc.toP(); + }; - 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; - }; + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; + } + BaseCurve.BasePoint = BasePoint; - // 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; - }; + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; - function toBitArray (num) { - var w = new Array(num.bitLength()); + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils$l.toArray(bytes, enc); - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + var len = this.p.byteLength(); - return w; + // 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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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'); + }; - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; - 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; - }; + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); + }; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + BasePoint.prototype.encode = function encode(enc, compact) { + return utils$l.encode(this._encode(compact), enc); + }; - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); + 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; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + return this; + }; - return this; - }; + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + var doubles = this.precomputed.doubles; + if (!doubles) + return false; - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + }; - return this.strip(); - }; + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); + 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, }; + }; - // 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); - }; + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); + 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, }; + }; - // 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; - } + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; - this.length = b.length; + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; - return this.strip(); - }; + var assert$d = utils$k.assert; - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); - // 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); - }; + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - // 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; - } + // 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$3(ShortCurve, Base$2); + var short = ShortCurve; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } + } - this.length = a.length; + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN$7(vec.a, 16), + b: new BN$7(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } - return this.strip(); + return { + beta: beta, + lambda: lambda, + basis: basis, }; + }; - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; + 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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); - // 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); - }; + var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; + }; - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(1); - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + // 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; - if (bitsLeft > 0) { - bytesNeeded--; - } + 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)); - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; } + prevR = r; - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; - // And remove leading zeroes - return this.strip(); - }; + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; + }; - var off = (bit / 26) | 0; - var wbit = bit % 26; + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; - this._expand(off + 1); + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); - return this.strip(); - }; + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$7(x, 16); + if (!x.red) + x = x.toRed(this.red); - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + 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'); - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + // 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(); - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + return this.point(x, y); + }; - 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; - } + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; - 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]; - } - } + var x = point.x; + var y = point.y; - return this; - }; + 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; + }; - // 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; + 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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - if (this.length > num.length) return this.clone().iadd(num); + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; - return num.clone().iadd(this); + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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; + }; - // 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(); + Point$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; - // At this point both numbers are positive - var cmp = this.cmp(num); + Point$2.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + // P + O = P + if (p.inf) + return this; - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + // P + P = 2P + if (this.eq(p)) + return this.dbl(); - 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; - } + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); - this.length = Math.max(this.length, i); + 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); + }; - if (a !== this) { - this.negative = 1; - } + Point$2.prototype.dbl = function dbl() { + if (this.inf) + return this; - return this.strip(); - }; + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + var a = this.curve.a; - 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; + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - // 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 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); + }; - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + Point$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; - 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--; - } + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; - return out.strip(); + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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; + }; - // 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) ; 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); - }; - })(module, commonjsGlobal); - }(bn)); - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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; - }; - }(utils$m)); - - (function (exports) { - - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; - - 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; - }(utils$n)); - - var brorand = {exports: {}}; - - var r$1; - - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); - }; - - function Rand(rand) { - this.rand = rand; - } - brorand.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$4 = require('crypto'); - if (typeof crypto$4.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto$4.randomBytes(n); - }; - } catch (e) { - } - } - - var curve = {}; - - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; - - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN$8(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); - } - } - var base = 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$e(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$e(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]; - 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(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$l.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; - }; - - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$3 = inherits_browser.exports; - var Base$2 = base; - - var assert$d = utils$k.assert; - - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); - - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(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$3(ShortCurve, Base$2); - var short = 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$7(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$7(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$d(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$7(vec.a, 16), - b: new BN$7(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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN$7(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$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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$2.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$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + Point$2.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; @@ -24447,16 +21224,16 @@ const createHmac = browser$2; - const ONE1 = Buffer$l.alloc(1, 1); - const ZERO1 = Buffer$l.alloc(1, 0); + const ONE1 = Buffer$m.alloc(1, 1); + const ZERO1 = Buffer$m.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$l.alloc(32, 0); - let v = Buffer$l.alloc(32, 1); + let k = Buffer$m.alloc(32, 0); + let v = Buffer$m.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -24508,14 +21285,14 @@ var rfc6979 = deterministicGenerateK$1; - const BN = bn$1.exports; + const BN = bn.exports; const EC = elliptic.ec; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$l.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$m.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -24587,9 +21364,9 @@ } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -24721,7 +21498,7 @@ s = n.sub(s); } - const buffer = Buffer$l.allocUnsafe(64); + const buffer = Buffer$m.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -24954,7 +21731,7 @@ var _HexN = _LengthN.bind(null, Hex); var _StringN = _LengthN.bind(null, NATIVE$1.String); - function Range$b (a, b, f) { + function Range$m (a, b, f) { f = f || NATIVE$1.Number; function _range (value, strict) { return f(value, strict) && (value > a) && (value < b) @@ -25000,7 +21777,7 @@ Int16: Int16, Int32: Int32, Int53: Int53, - Range: Range$b, + Range: Range$m, StringN: _StringN, UInt8: UInt8, UInt16: UInt16, @@ -25306,7 +22083,7 @@ } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$l(compressed ? 34 : 33); + var result = new Buffer$m(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -25425,7 +22202,7 @@ const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$l.allocUnsafe(78); + const buffer = Buffer$m.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -25459,7 +22236,7 @@ derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$l.allocUnsafe(37); + const data = Buffer$m.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -25539,7 +22316,7 @@ } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -25631,7 +22408,7 @@ if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -25738,7 +22515,7 @@ function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$l.allocUnsafe(size); + const buffer = Buffer$m.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -25933,18 +22710,18 @@ const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$l.alloc(1, 0); + const ZERO$1 = Buffer$m.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$l.alloc(32, 0); + const buffer = Buffer$m.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -25958,7 +22735,7 @@ const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$l.concat([r, s], 64); + const signature = Buffer$m.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -25973,11 +22750,11 @@ const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$l.allocUnsafe(1); + const hashTypeBuffer = Buffer$m.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -26366,7 +23143,7 @@ // opcode return accum + 1; }, 0.0); - const buffer = Buffer$l.allocUnsafe(bufferSize); + const buffer = Buffer$m.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -26451,7 +23228,7 @@ if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$l.from(chunkStr, 'hex'); + return Buffer$m.from(chunkStr, 'hex'); }), ); } @@ -26461,7 +23238,7 @@ typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -26869,7 +23646,7 @@ const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -26908,7 +23685,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27027,7 +23804,7 @@ // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -27063,7 +23840,7 @@ return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -27339,7 +24116,7 @@ const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$l.alloc(0); + const EMPTY_BUFFER$1 = Buffer$m.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -27367,7 +24144,7 @@ return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -27407,7 +24184,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27471,7 +24248,7 @@ const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$l.alloc(0); + const EMPTY_BUFFER = Buffer$m.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -27521,7 +24298,7 @@ return { version, prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; }); const _rchunks = lazy.value(() => { @@ -27586,7 +24363,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$l.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -27709,13 +24486,13 @@ return { version: result.words[0], prefix: result.prefix, - data: Buffer$l.from(data), + data: Buffer$m.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$l.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -27871,7 +24648,7 @@ return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$l.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -27943,10 +24720,10 @@ var Buffer = safeBuffer.exports.Buffer; // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; + var MAX_SAFE_INTEGER$5 = 9007199254740991; function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') } function encode$b (number, buffer, offset) { @@ -28073,7 +24850,7 @@ } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$l.allocUnsafe(buffer.length); + const clone = Buffer$m.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -28196,17 +24973,17 @@ }, 0) ); } - const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$l.from( + const ZERO = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$l.from( + const ONE = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -28268,7 +25045,7 @@ return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -28428,7 +25205,7 @@ txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -28438,13 +25215,13 @@ types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$l.from([]); + let tbuffer = Buffer$m.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -28457,7 +25234,7 @@ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -28471,7 +25248,7 @@ const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$l.allocUnsafe(txOutsSize); + tbuffer = Buffer$m.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -28483,13 +25260,13 @@ inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -28507,7 +25284,7 @@ } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -28529,7 +25306,7 @@ this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -28591,7 +25368,7 @@ for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$l.concat([left, right]); + var data = Buffer$m.concat([left, right]); results[j] = digestFn(data); } @@ -28658,12 +25435,12 @@ return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$l.from(hex, 'hex')); + return Block.fromBuffer(Buffer$m.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$l.alloc(32, 0); + const target = Buffer$m.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -28678,7 +25455,7 @@ const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -28690,18 +25467,18 @@ // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$l && result.length === 32)) return null; + if (!(result instanceof Buffer$m && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$l && + this.witnessCommit instanceof Buffer$m && this.witnessCommit.length === 32 ) return true; @@ -28737,7 +25514,7 @@ } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -28879,7 +25656,7 @@ Object.defineProperty(globalXpub$1, '__esModule', { value: true }); const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; + const range$4 = n => [...Array(n).keys()]; function decode$9(keyVal) { if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { throw new Error( @@ -28904,7 +25681,7 @@ extendedPubkey, path: 'm', }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { + for (const i of range$4(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -28914,10 +25691,10 @@ } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$l.concat([head, data.extendedPubkey]); + const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$m.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28966,7 +25743,7 @@ const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -28987,7 +25764,7 @@ } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -29019,7 +25796,7 @@ } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -29054,7 +25831,7 @@ nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -29097,9 +25874,9 @@ } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$l.concat([head, pSig.pubkey]), + key: Buffer$m.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -29151,10 +25928,10 @@ } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$l.from(data, 'utf8'), + value: Buffer$m.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -29183,8 +25960,8 @@ } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$l.allocUnsafe(4); + const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$m.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -29210,14 +25987,14 @@ Object.defineProperty(varint$1, '__esModule', { value: true }); // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; + const MAX_SAFE_INTEGER$4 = 9007199254740991; function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) throw new RangeError('value out of range'); } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -29303,8 +26080,8 @@ tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$l.from([0])); - return Buffer$l.concat(buffers); + buffers.push(Buffer$m.from([0])); + return Buffer$m.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -29312,7 +26089,7 @@ const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$l.allocUnsafe( + const buffer = Buffer$m.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -29376,12 +26153,12 @@ function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -29399,7 +26176,7 @@ var bip32Derivation$1 = {}; Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; + const range$3 = n => [...Array(n).keys()]; function makeConverter$2(TYPE_BYTE) { function decode(keyVal) { if (keyVal.key[0] !== TYPE_BYTE) { @@ -29428,7 +26205,7 @@ pubkey, path: 'm', }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { + for (const i of range$3(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -29437,10 +26214,10 @@ return data; } function encode(data) { - const head = Buffer$l.from([TYPE_BYTE]); - const key = Buffer$l.concat([head, data.pubkey]); + const head = Buffer$m.from([TYPE_BYTE]); + const key = Buffer$m.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$l.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -29520,7 +26297,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -29557,7 +26334,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -29766,7 +26543,7 @@ } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$l.from([keyNum]))) { + if (!keyBuf.equals(Buffer$m.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -29985,13 +26762,13 @@ const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$l.from([0])] + ? [Buffer$m.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$l.allocUnsafe(5); + const header = Buffer$m.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$l.concat( + return Buffer$m.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -30285,11 +27062,11 @@ }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -30509,11 +27286,11 @@ dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$l.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$l.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -30684,7 +27461,7 @@ } finalizeAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); return this; } finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { @@ -30751,7 +27528,7 @@ } validateSignaturesOfAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => + const results = range$2(this.data.inputs.length).map(idx => this.validateSignaturesOfInput(idx), ); return results.reduce((final, res) => res === true && final, true); @@ -30797,7 +27574,7 @@ throw new Error('Need HDSigner to sign input'); } const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInputHD(i, hdKeyPair, sighashTypes); results.push(true); @@ -30820,7 +27597,7 @@ } const results = []; const promises = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { promises.push( this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( () => { @@ -30882,7 +27659,7 @@ // as input information is added, then eventually // optimize this method. const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInput(i, keyPair, sighashTypes); results.push(true); @@ -31037,7 +27814,7 @@ * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -31062,7 +27839,7 @@ } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -31237,7 +28014,7 @@ } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -31601,14 +28378,14 @@ return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$l.allocUnsafe(0); + let buffer = Buffer$m.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); + buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); + buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -31813,7 +28590,7 @@ if (isP2PK(script)) return 'pubkey'; return 'nonstandard'; } - function range$1(n) { + function range$2(n) { return [...Array(n).keys()]; } @@ -32117,7 +28894,7 @@ const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$l.from('aa21a9ed', 'hex'); + const HEADER = Buffer$m.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -32133,7 +28910,7 @@ }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$l.allocUnsafe(36); + const buffer = Buffer$m.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -32409,7 +29186,7 @@ // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -33377,27 +30154,27 @@ var transaction_builder_1 = transaction_builder; src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - var re$5 = {exports: {}}; + var re$b = {exports: {}}; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; + const SEMVER_SPEC_VERSION$1 = '2.0.0'; - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + const MAX_LENGTH$5 = 256; + const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; + const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH + var constants$1 = { + SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, + MAX_LENGTH: MAX_LENGTH$5, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, + MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 }; - const debug$3 = ( + const debug$7 = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && @@ -33405,11 +30182,11 @@ ) ? (...args) => console.error('SEMVER', ...args) : () => {}; - var debug_1 = debug$3; + var debug_1$1 = debug$7; (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; + const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; + const debug = debug_1$1; exports = module.exports = {}; // The actual regexps go on exports.re @@ -33590,24 +30367,24 @@ // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + }(re$b, re$b.exports)); // parse out just the options we care about so we always get a consistent // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => + const opts$1 = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$9 = options => !options ? {} : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { + : opts$1.filter(k => options[k]).reduce((options, k) => { options[k] = true; return options }, {}); - var parseOptions_1 = parseOptions$4; + var parseOptions_1$1 = parseOptions$9; - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + const numeric$1 = /^[0-9]+$/; + const compareIdentifiers$3 = (a, b) => { + const anum = numeric$1.test(a); + const bnum = numeric$1.test(b); if (anum && bnum) { a = +a; @@ -33621,24 +30398,24 @@ : 1 }; - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers + var identifiers$1 = { + compareIdentifiers: compareIdentifiers$3, + rcompareIdentifiers: rcompareIdentifiers$1 }; - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; + const debug$6 = debug_1$1; + const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; + const { re: re$a, t: t$9 } = re$b.exports; - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { + const parseOptions$8 = parseOptions_1$1; + const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; + class SemVer$t { constructor (version, options) { - options = parseOptions$3(options); + options = parseOptions$8(options); - if (version instanceof SemVer$e) { + if (version instanceof SemVer$t) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version @@ -33649,20 +30426,20 @@ throw new TypeError(`Invalid Version: ${version}`) } - if (version.length > MAX_LENGTH$1) { + if (version.length > MAX_LENGTH$4) { throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` + `version is longer than ${MAX_LENGTH$4} characters` ) } - debug$2('SemVer', version, options); + debug$6('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); if (!m) { throw new TypeError(`Invalid Version: ${version}`) @@ -33675,15 +30452,15 @@ this.minor = +m[2]; this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { throw new TypeError('Invalid major version') } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { throw new TypeError('Invalid minor version') } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { throw new TypeError('Invalid patch version') } @@ -33694,7 +30471,7 @@ this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { + if (num >= 0 && num < MAX_SAFE_INTEGER$2) { return num } } @@ -33719,12 +30496,12 @@ } compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { + debug$6('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$t)) { if (typeof other === 'string' && other === this.version) { return 0 } - other = new SemVer$e(other, this.options); + other = new SemVer$t(other, this.options); } if (other.version === this.version) { @@ -33735,20 +30512,20 @@ } compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) + compareIdentifiers$2(this.major, other.major) || + compareIdentifiers$2(this.minor, other.minor) || + compareIdentifiers$2(this.patch, other.patch) ) } comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } // NOT having a prerelease is > having one @@ -33764,7 +30541,7 @@ do { const a = this.prerelease[i]; const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -33774,21 +30551,21 @@ } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -33798,7 +30575,7 @@ } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } @@ -33914,17 +30691,17 @@ } } - var semver$1 = SemVer$e; + var semver$3 = SemVer$t; - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; + const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; + const { re: re$9, t: t$8 } = re$b.exports; + const SemVer$s = semver$3; - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); + const parseOptions$7 = parseOptions_1$1; + const parse$b = (version, options) => { + options = parseOptions$7(options); - if (version instanceof SemVer$d) { + if (version instanceof SemVer$s) { return version } @@ -33932,73 +30709,73 @@ return null } - if (version.length > MAX_LENGTH) { + if (version.length > MAX_LENGTH$3) { return null } - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; if (!r.test(version)) { return null } try { - return new SemVer$d(version, options) + return new SemVer$s(version, options) } catch (er) { return null } }; - var parse_1 = parse$5; + var parse_1$1 = parse$b; - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); + const parse$a = parse_1$1; + const valid$3 = (version, options) => { + const v = parse$a(version, options); return v ? v.version : null }; - var valid_1 = valid$1; + var valid_1$1 = valid$3; - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + const parse$9 = parse_1$1; + const clean$1 = (version, options) => { + const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); return s ? s.version : null }; - var clean_1 = clean; + var clean_1$1 = clean$1; - const SemVer$c = semver$1; + const SemVer$r = semver$3; - const inc = (version, release, options, identifier) => { + const inc$1 = (version, release, options, identifier) => { if (typeof (options) === 'string') { identifier = options; options = undefined; } try { - return new SemVer$c(version, options).inc(release, identifier).version + return new SemVer$r(version, options).inc(release, identifier).version } catch (er) { return null } }; - var inc_1 = inc; + var inc_1$1 = inc$1; - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + const SemVer$q = semver$3; + const compare$l = (a, b, loose) => + new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - var compare_1 = compare$a; + var compare_1$1 = compare$l; - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; + const compare$k = compare_1$1; + const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; + var eq_1$1 = eq$5; - const parse$2 = parse_1; - const eq$1 = eq_1; + const parse$8 = parse_1$1; + const eq$4 = eq_1$1; - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { + const diff$1 = (version1, version2) => { + if (eq$4(version1, version2)) { return null } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); + const v1 = parse$8(version1); + const v2 = parse$8(version2); const hasPre = v1.prerelease.length || v2.prerelease.length; const prefix = hasPre ? 'pre' : ''; const defaultResult = hasPre ? 'prerelease' : ''; @@ -34012,79 +30789,79 @@ return defaultResult // may be undefined } }; - var diff_1 = diff; + var diff_1$1 = diff$1; - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; + const SemVer$p = semver$3; + const major$1 = (a, loose) => new SemVer$p(a, loose).major; + var major_1$1 = major$1; - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; + const SemVer$o = semver$3; + const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; + var minor_1$1 = minor$1; - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; + const SemVer$n = semver$3; + const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; + var patch_1$1 = patch$1; - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); + const parse$7 = parse_1$1; + const prerelease$1 = (version, options) => { + const parsed = parse$7(version, options); return (parsed && parsed.prerelease.length) ? parsed.prerelease : null }; - var prerelease_1 = prerelease; + var prerelease_1$1 = prerelease$1; - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; + const compare$j = compare_1$1; + const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); + var rcompare_1$1 = rcompare$1; - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; + const compare$i = compare_1$1; + const compareLoose$1 = (a, b) => compare$i(a, b, true); + var compareLoose_1$1 = compareLoose$1; - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); + const SemVer$m = semver$3; + const compareBuild$5 = (a, b, loose) => { + const versionA = new SemVer$m(a, loose); + const versionB = new SemVer$m(b, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB) }; - var compareBuild_1 = compareBuild$2; + var compareBuild_1$1 = compareBuild$5; - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; + const compareBuild$4 = compareBuild_1$1; + const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); + var sort_1$1 = sort$1; - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; + const compareBuild$3 = compareBuild_1$1; + const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); + var rsort_1$1 = rsort$1; - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; + const compare$h = compare_1$1; + const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; + var gt_1$1 = gt$7; - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; + const compare$g = compare_1$1; + const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; + var lt_1$1 = lt$5; - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; + const compare$f = compare_1$1; + const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; + var neq_1$1 = neq$3; - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; + const compare$e = compare_1$1; + const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; + var gte_1$1 = gte$5; - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; + const compare$d = compare_1$1; + const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; + var lte_1$1 = lte$5; - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; + const eq$3 = eq_1$1; + const neq$2 = neq_1$1; + const gt$6 = gt_1$1; + const gte$4 = gte_1$1; + const lt$4 = lt_1$1; + const lte$4 = lte_1$1; - const cmp$1 = (a, op, b, loose) => { + const cmp$3 = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') @@ -34103,35 +30880,35 @@ case '': case '=': case '==': - return eq(a, b, loose) + return eq$3(a, b, loose) case '!=': - return neq(a, b, loose) + return neq$2(a, b, loose) case '>': - return gt$2(a, b, loose) + return gt$6(a, b, loose) case '>=': - return gte$1(a, b, loose) + return gte$4(a, b, loose) case '<': - return lt$1(a, b, loose) + return lt$4(a, b, loose) case '<=': - return lte$1(a, b, loose) + return lte$4(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } }; - var cmp_1 = cmp$1; + var cmp_1$1 = cmp$3; - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; + const SemVer$l = semver$3; + const parse$6 = parse_1$1; + const {re: re$8, t: t$7} = re$b.exports; - const coerce = (version, options) => { - if (version instanceof SemVer$6) { + const coerce$1 = (version, options) => { + if (version instanceof SemVer$l) { return version } @@ -34147,7 +30924,7 @@ let match = null; if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); + match = version.match(re$8[t$7.COERCE]); } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. @@ -34158,25 +30935,25 @@ // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && + while ((next = re$8[t$7.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next; } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; + re$8[t$7.COERCERTL].lastIndex = -1; } if (match === null) return null - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) }; - var coerce_1 = coerce; + var coerce_1$1 = coerce$1; var yallist = Yallist$1; @@ -34938,22 +31715,22 @@ var lruCache = LRUCache; // hoisted class for cyclic dependency - class Range$a { + class Range$l { constructor (range, options) { - options = parseOptions$1(options); + options = parseOptions$6(options); - if (range instanceof Range$a) { + if (range instanceof Range$l) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { - return new Range$a(range.raw, options) + return new Range$l(range.raw, options) } } - if (range instanceof Comparator$3) { + if (range instanceof Comparator$7) { // just put it in the set and return this.raw = range.value; this.set = [[range]]; @@ -34984,13 +31761,13 @@ if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); + this.set = this.set.filter(c => !isNullSet$1(c[0])); if (this.set.length === 0) this.set = [first]; else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { + if (c.length === 1 && isAny$1(c[0])) { this.set = [c]; break } @@ -35022,24 +31799,24 @@ // this is a very hot path, and fully deterministic. const memoOpts = Object.keys(this.options).join(','); const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); + const cached = cache$1.get(memoKey); if (cached) return cached const loose = this.options.loose; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); + const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); + debug$5('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); + debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); // normalize spaces range = range.split(/\s+/).join(' '); @@ -35047,17 +31824,17 @@ // At this point, the range is completely trimmed and // ready to be split into comparators. - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; const rangeList = range .split(' ') - .map(comp => parseComparator(comp, this.options)) + .map(comp => parseComparator$1(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) + .map(comp => replaceGTE0$1(comp, this.options)) // in loose mode, throw out any that are not valid comparators .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); + .map(comp => new Comparator$7(comp, this.options)); // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators @@ -35065,7 +31842,7 @@ rangeList.length; const rangeMap = new Map(); for (const comp of rangeList) { - if (isNullSet(comp)) + if (isNullSet$1(comp)) return [comp] rangeMap.set(comp.value, comp); } @@ -35073,21 +31850,21 @@ rangeMap.delete(''); const result = [...rangeMap.values()]; - cache.set(memoKey, result); + cache$1.set(memoKey, result); return result } intersects (range, options) { - if (!(range instanceof Range$a)) { + if (!(range instanceof Range$l)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( - isSatisfiable(thisComparators, options) && + isSatisfiable$1(thisComparators, options) && range.set.some((rangeComparators) => { return ( - isSatisfiable(rangeComparators, options) && + isSatisfiable$1(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) @@ -35107,43 +31884,43 @@ if (typeof version === 'string') { try { - version = new SemVer$5(version, this.options); + version = new SemVer$k(version, this.options); } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { + if (testSet$1(this.set[i], version, this.options)) { return true } } return false } } - var range = Range$a; + var range$1 = Range$l; - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); + const LRU$1 = lruCache; + const cache$1 = new LRU$1({ max: 1000 }); - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; + const parseOptions$6 = parseOptions_1$1; + const Comparator$7 = comparator$1; + const debug$5 = debug_1$1; + const SemVer$k = semver$3; const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; + re: re$7, + t: t$6, + comparatorTrimReplace: comparatorTrimReplace$1, + tildeTrimReplace: tildeTrimReplace$1, + caretTrimReplace: caretTrimReplace$1 + } = re$b.exports; - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; + const isNullSet$1 = c => c.value === '<0.0.0-0'; + const isAny$1 = c => c.value === ''; // take a set of comparators and determine whether there // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { + const isSatisfiable$1 = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); @@ -35162,20 +31939,20 @@ // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); + const parseComparator$1 = (comp, options) => { + debug$5('comp', comp, options); + comp = replaceCarets$1(comp, options); + debug$5('caret', comp); + comp = replaceTildes$1(comp, options); + debug$5('tildes', comp); + comp = replaceXRanges$1(comp, options); + debug$5('xrange', comp); + comp = replaceStars$1(comp, options); + debug$5('stars', comp); return comp }; - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 @@ -35183,26 +31960,26 @@ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => + const replaceTildes$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) + return replaceTilde$1(comp, options) }).join(' '); - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + const replaceTilde$1 = (comp, options) => { + const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); + debug$5('tilde', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { - debug$1('replaceTilde pr', pr); + debug$5('replaceTilde pr', pr); ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0`; } else { @@ -35211,7 +31988,7 @@ } <${M}.${+m + 1}.0-0`; } - debug$1('tilde return', ret); + debug$5('tilde return', ret); return ret }) }; @@ -35222,31 +31999,31 @@ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => + const replaceCarets$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) + return replaceCaret$1(comp, options) }).join(' '); - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const replaceCaret$1 = (comp, options) => { + debug$5('caret', comp, options); + const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; const z = options.includePrerelease ? '-0' : ''; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); + debug$5('caret', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { - debug$1('replaceCaret pr', pr); + debug$5('replaceCaret pr', pr); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr @@ -35260,7 +32037,7 @@ } <${+M + 1}.0.0-0`; } } else { - debug$1('no pr'); + debug$5('no pr'); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p @@ -35275,26 +32052,26 @@ } } - debug$1('caret return', ret); + debug$5('caret return', ret); return ret }) }; - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); + const replaceXRanges$1 = (comp, options) => { + debug$5('replaceXRanges', comp, options); return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) + return replaceXRange$1(comp, options) }).join(' ') }; - const replaceXRange = (comp, options) => { + const replaceXRange$1 = (comp, options) => { comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); + debug$5('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX$1(M); + const xm = xM || isX$1(m); + const xp = xm || isX$1(p); const anyX = xp; if (gtlt === '=' && anyX) { @@ -35355,7 +32132,7 @@ } <${M}.${+m + 1}.0-0`; } - debug$1('xRange return', ret); + debug$5('xRange return', ret); return ret }) @@ -35363,16 +32140,16 @@ // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); + const replaceStars$1 = (comp, options) => { + debug$5('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') + return comp.trim().replace(re$7[t$6.STAR], '') }; - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); + const replaceGTE0$1 = (comp, options) => { + debug$5('replaceGTE0', comp, options); return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') }; // This function is passed to string.replace(re[t.HYPHENRANGE]) @@ -35380,14 +32157,14 @@ // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, + const hyphenReplace$1 = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { + if (isX$1(fM)) { from = ''; - } else if (isX(fm)) { + } else if (isX$1(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { + } else if (isX$1(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; } else if (fpr) { from = `>=${from}`; @@ -35395,11 +32172,11 @@ from = `>=${from}${incPr ? '-0' : ''}`; } - if (isX(tM)) { + if (isX$1(tM)) { to = ''; - } else if (isX(tm)) { + } else if (isX$1(tm)) { to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { + } else if (isX$1(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; @@ -35412,7 +32189,7 @@ return (`${from} ${to}`).trim() }; - const testSet = (set, version, options) => { + const testSet$1 = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false @@ -35426,8 +32203,8 @@ // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { + debug$5(set[i].semver); + if (set[i].semver === Comparator$7.ANY) { continue } @@ -35448,16 +32225,16 @@ return true }; - const ANY$2 = Symbol('SemVer ANY'); + const ANY$5 = Symbol('SemVer ANY'); // hoisted class for cyclic dependency - class Comparator$2 { + class Comparator$6 { static get ANY () { - return ANY$2 + return ANY$5 } constructor (comp, options) { - options = parseOptions(options); + options = parseOptions$5(options); - if (comp instanceof Comparator$2) { + if (comp instanceof Comparator$6) { if (comp.loose === !!options.loose) { return comp } else { @@ -35465,22 +32242,22 @@ } } - debug('comparator', comp, options); + debug$4('comparator', comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); - if (this.semver === ANY$2) { + if (this.semver === ANY$5) { this.value = ''; } else { this.value = this.operator + this.semver.version; } - debug('comp', this); + debug$4('comp', this); } parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; const m = comp.match(r); if (!m) { @@ -35494,9 +32271,9 @@ // if it literally is just '>' or '' then allow anything. if (!m[2]) { - this.semver = ANY$2; + this.semver = ANY$5; } else { - this.semver = new SemVer$4(m[2], this.options.loose); + this.semver = new SemVer$j(m[2], this.options.loose); } } @@ -35505,25 +32282,25 @@ } test (version) { - debug('Comparator.test', version, this.options.loose); + debug$4('Comparator.test', version, this.options.loose); - if (this.semver === ANY$2 || version === ANY$2) { + if (this.semver === ANY$5 || version === ANY$5) { return true } if (typeof version === 'string') { try { - version = new SemVer$4(version, this.options); + version = new SemVer$j(version, this.options); } catch (er) { return false } } - return cmp(version, this.operator, this.semver, this.options) + return cmp$2(version, this.operator, this.semver, this.options) } intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { + if (!(comp instanceof Comparator$6)) { throw new TypeError('a Comparator is required') } @@ -35538,12 +32315,12 @@ if (this.value === '') { return true } - return new Range$9(comp.value, options).test(this.value) + return new Range$k(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } - return new Range$9(this.value, options).test(comp.semver) + return new Range$k(this.value, options).test(comp.semver) } const sameDirectionIncreasing = @@ -35557,11 +32334,11 @@ (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && + cmp$2(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && + cmp$2(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); @@ -35575,44 +32352,44 @@ } } - var comparator = Comparator$2; + var comparator$1 = Comparator$6; - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; + const parseOptions$5 = parseOptions_1$1; + const {re: re$6, t: t$5} = re$b.exports; + const cmp$2 = cmp_1$1; + const debug$4 = debug_1$1; + const SemVer$j = semver$3; + const Range$k = range$1; - const Range$8 = range; - const satisfies$3 = (version, range, options) => { + const Range$j = range$1; + const satisfies$7 = (version, range, options) => { try { - range = new Range$8(range, options); + range = new Range$j(range, options); } catch (er) { return false } return range.test(version) }; - var satisfies_1 = satisfies$3; + var satisfies_1$1 = satisfies$7; - const Range$7 = range; + const Range$i = range$1; // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set + const toComparators$1 = (range, options) => + new Range$i(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - var toComparators_1 = toComparators; + var toComparators_1$1 = toComparators$1; - const SemVer$3 = semver$1; - const Range$6 = range; + const SemVer$i = semver$3; + const Range$h = range$1; - const maxSatisfying = (versions, range, options) => { + const maxSatisfying$1 = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { - rangeObj = new Range$6(range, options); + rangeObj = new Range$h(range, options); } catch (er) { return null } @@ -35622,22 +32399,22 @@ if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v; - maxSV = new SemVer$3(max, options); + maxSV = new SemVer$i(max, options); } } }); return max }; - var maxSatisfying_1 = maxSatisfying; + var maxSatisfying_1$1 = maxSatisfying$1; - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { + const SemVer$h = semver$3; + const Range$g = range$1; + const minSatisfying$1 = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { - rangeObj = new Range$5(range, options); + rangeObj = new Range$g(range, options); } catch (er) { return null } @@ -35647,27 +32424,27 @@ if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v; - minSV = new SemVer$2(min, options); + minSV = new SemVer$h(min, options); } } }); return min }; - var minSatisfying_1 = minSatisfying; + var minSatisfying_1$1 = minSatisfying$1; - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; + const SemVer$g = semver$3; + const Range$f = range$1; + const gt$5 = gt_1$1; - const minVersion = (range, loose) => { - range = new Range$4(range, loose); + const minVersion$1 = (range, loose) => { + range = new Range$f(range, loose); - let minver = new SemVer$1('0.0.0'); + let minver = new SemVer$g('0.0.0'); if (range.test(minver)) { return minver } - minver = new SemVer$1('0.0.0-0'); + minver = new SemVer$g('0.0.0-0'); if (range.test(minver)) { return minver } @@ -35679,7 +32456,7 @@ let setMin = null; comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); + const compver = new SemVer$g(comparator.semver.version); switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { @@ -35691,7 +32468,7 @@ /* fallthrough */ case '': case '>=': - if (!setMin || gt$1(compver, setMin)) { + if (!setMin || gt$5(compver, setMin)) { setMin = compver; } break @@ -35704,7 +32481,7 @@ throw new Error(`Unexpected operation: ${comparator.operator}`) } }); - if (setMin && (!minver || gt$1(minver, setMin))) + if (setMin && (!minver || gt$5(minver, setMin))) minver = setMin; } @@ -35714,47 +32491,47 @@ return null }; - var minVersion_1 = minVersion; + var minVersion_1$1 = minVersion$1; - const Range$3 = range; - const validRange = (range, options) => { + const Range$e = range$1; + const validRange$1 = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' + return new Range$e(range, options).range || '*' } catch (er) { return null } }; - var valid = validRange; + var valid$2 = validRange$1; - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; + const SemVer$f = semver$3; + const Comparator$5 = comparator$1; + const {ANY: ANY$4} = Comparator$5; + const Range$d = range$1; + const satisfies$6 = satisfies_1$1; + const gt$4 = gt_1$1; + const lt$3 = lt_1$1; + const lte$3 = lte_1$1; + const gte$3 = gte_1$1; - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); + const outside$5 = (version, range, hilo, options) => { + version = new SemVer$f(version, options); + range = new Range$d(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; + gtfn = gt$4; + ltefn = lte$3; + ltfn = lt$3; comp = '>'; ecomp = '>='; break case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; + gtfn = lt$3; + ltefn = gte$3; + ltfn = gt$4; comp = '<'; ecomp = '<='; break @@ -35763,7 +32540,7 @@ } // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { + if (satisfies$6(version, range, options)) { return false } @@ -35777,8 +32554,8 @@ let low = null; comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); + if (comparator.semver === ANY$4) { + comparator = new Comparator$5('>=0.0.0'); } high = high || comparator; low = low || comparator; @@ -35807,38 +32584,38 @@ return true }; - var outside_1 = outside$2; + var outside_1$1 = outside$5; // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; + const outside$4 = outside_1$1; + const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); + var gtr_1$1 = gtr$1; - const outside = outside_1; + const outside$3 = outside_1$1; // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; + const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); + var ltr_1$1 = ltr$1; - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); + const Range$c = range$1; + const intersects$1 = (r1, r2, options) => { + r1 = new Range$c(r1, options); + r2 = new Range$c(r2, options); return r1.intersects(r2) }; - var intersects_1 = intersects; + var intersects_1$1 = intersects$1; // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { + const satisfies$5 = satisfies_1$1; + const compare$c = compare_1$1; + var simplify$1 = (versions, range, options) => { const set = []; let min = null; let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); + const v = versions.sort((a, b) => compare$c(a, b, options)); for (const version of v) { - const included = satisfies$1(version, range, options); + const included = satisfies$5(version, range, options); if (included) { prev = version; if (!min) @@ -35872,11 +32649,11 @@ return simplified.length < original.length ? simplified : range }; - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; + const Range$b = range$1; + const Comparator$4 = comparator$1; + const { ANY: ANY$3 } = Comparator$4; + const satisfies$4 = satisfies_1$1; + const compare$b = compare_1$1; // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR @@ -35914,17 +32691,17 @@ // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true - const subset = (sub, dom, options = {}) => { + const subset$1 = (sub, dom, options = {}) => { if (sub === dom) return true - sub = new Range(sub, options); - dom = new Range(dom, options); + sub = new Range$b(sub, options); + dom = new Range$b(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); + const isSub = simpleSubset$1(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) continue OUTER @@ -35939,33 +32716,33 @@ return true }; - const simpleSubset = (sub, dom, options) => { + const simpleSubset$1 = (sub, dom, options) => { if (sub === dom) return true - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) + if (sub.length === 1 && sub[0].semver === ANY$3) { + if (dom.length === 1 && dom[0].semver === ANY$3) return true else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; + sub = [ new Comparator$4('>=0.0.0-0') ]; else - sub = [ new Comparator('>=0.0.0') ]; + sub = [ new Comparator$4('>=0.0.0') ]; } - if (dom.length === 1 && dom[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY$3) { if (options.includePrerelease) return true else - dom = [ new Comparator('>=0.0.0') ]; + dom = [ new Comparator$4('>=0.0.0') ]; } const eqSet = new Set(); let gt, lt; for (const c of sub) { if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); + gt = higherGT$1(gt, c, options); else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); + lt = lowerLT$1(lt, c, options); else eqSet.add(c.semver); } @@ -35975,7 +32752,7 @@ let gtltComp; if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); + gtltComp = compare$b(gt.semver, lt.semver, options); if (gtltComp > 0) return null else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) @@ -35984,1441 +32761,2603 @@ // will iterate one or zero times for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) + if (gt && !satisfies$4(eq, String(gt), options)) return null - if (lt && !satisfies(eq, String(lt), options)) + if (lt && !satisfies$4(eq, String(lt), options)) return null for (const c of dom) { - if (!satisfies(eq, String(c), options)) + if (!satisfies$4(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT$1(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT$1(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) return false } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1$1 = subset$1; + + // just pre-load all the stuff that index.js lazily exports + const internalRe$1 = re$b.exports; + var semver$2 = { + re: internalRe$1.re, + src: internalRe$1.src, + tokens: internalRe$1.t, + SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, + SemVer: semver$3, + compareIdentifiers: identifiers$1.compareIdentifiers, + rcompareIdentifiers: identifiers$1.rcompareIdentifiers, + parse: parse_1$1, + valid: valid_1$1, + clean: clean_1$1, + inc: inc_1$1, + diff: diff_1$1, + major: major_1$1, + minor: minor_1$1, + patch: patch_1$1, + prerelease: prerelease_1$1, + compare: compare_1$1, + rcompare: rcompare_1$1, + compareLoose: compareLoose_1$1, + compareBuild: compareBuild_1$1, + sort: sort_1$1, + rsort: rsort_1$1, + gt: gt_1$1, + lt: lt_1$1, + eq: eq_1$1, + neq: neq_1$1, + gte: gte_1$1, + lte: lte_1$1, + cmp: cmp_1$1, + coerce: coerce_1$1, + Comparator: comparator$1, + Range: range$1, + satisfies: satisfies_1$1, + toComparators: toComparators_1$1, + maxSatisfying: maxSatisfying_1$1, + minSatisfying: minSatisfying_1$1, + minVersion: minVersion_1$1, + validRange: valid$2, + outside: outside_1$1, + gtr: gtr_1$1, + ltr: ltr_1$1, + intersects: intersects_1$1, + simplifyRange: simplify$1, + subset: subset_1$1, + }; + + function unsafeTo64bitLE(n) { + // we want to represent the input as a 8-bytes array + if (n > Number.MAX_SAFE_INTEGER) { + throw new Error("Can't convert numbers > MAX_SAFE_INT"); + } + var byteArray = Buffer$m.alloc(8, 0); + for (var index = 0; index < byteArray.length; index++) { + var byte = n & 0xff; + byteArray[index] = byte; + n = (n - byte) / 256; + } + return byteArray; + } + function unsafeFrom64bitLE(byteArray) { + var value = 0; + if (byteArray.length != 8) { + throw new Error("Expected Bufffer of lenght 8"); + } + if (byteArray[7] != 0) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + if (byteArray[6] > 0x1f) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + for (var i = byteArray.length - 1; i >= 0; i--) { + value = value * 256 + byteArray[i]; + } + return value; + } + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$m.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + var bytes = unsafeTo64bitLE(i); + this.writeSlice(bytes); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$m.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$m.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var buf = this.readSlice(8); + var n = unsafeFrom64bitLE(buf); + return n; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); + } + + var __extends$4 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$4(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$4(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$4(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$m.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$m.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$m.concat([ + Buffer$m.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$4(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$m.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$4(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$m.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false + finally { if (e) throw e.error; } } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true + return ar; }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$m.concat([Buffer$m.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$m.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$m.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$m.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + } - var subset_1 = subset; + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$m.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(psbt.getOutputAmount(i)); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$5.apply(this, arguments); }; - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$l.alloc(alloc); - fn(b); - this.bufs.push(b); + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$l.from(slice)); + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); }; - BufferWriter.prototype.buffer = function () { - return Buffer$l.concat(this.bufs); + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } - - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); + return unsafeFrom64bitLE(buf); }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$l.concat([h, h, x])); + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$l.concat([ - Buffer$l.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + buf.writeSlice(Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$m.from(k.substring(2), "hex")); + } + }); + return result; }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$m.from([])); + this.globalMap.set(key.toString(), value); }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); }; - return p2wpkh; - }(SingleKeyAccount)); - - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; + return (maps[index] = new Map()); }; - Merkle.prototype.size = function () { - return this.leaves.length; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); }; - Merkle.prototype.getLeaves = function () { - return this.leaves; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), - leaves: [] - }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$m.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); }; - return Merkle; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$l.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$l.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); }; - return Node; + return KeyPair; }()); - function proveNode(node) { - if (!node.parent) { - return []; + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); + keyPair.serialize(buf); } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); + buf.writeUInt8(0); + } + function b() { + return Buffer$m.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$m.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + return unsafeTo64bitLE(n); + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input ".concat(i, " present")); } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); } } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; + psbt.deleteInputEntries(inputIndex, keyTypes); } - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$l.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$m.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); } - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$l.from([0, 1])); + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$m.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$m.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$m.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; } - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$m.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$m.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$m.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$m.concat([ + inputBuffer, + input.prevout, + Buffer$m.from([0x00]), + input.sequence, + ]) + : Buffer$m.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$m.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$m.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$m.alloc(0), + transaction.extraData || Buffer$m.alloc(0), + ]); + } + return Buffer$m.concat([ + transaction.version, + timestamp ? timestamp : Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return NoSuchEntry; - }(Error)); + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver$2.major(appAndVersion.version) >= 2); + } /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); + } + return [2 /*return*/, xpub]; + } + }); + }); }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime != undefined) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); }); }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$m.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence != undefined) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType != undefined) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input ".concat(k)); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); }); }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$1 = 0; + var subscribers = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = function (cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; + }; + }; + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; + catch (e) { + console.error(e); } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; + } + + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log, + listen: listen + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; + return t; }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$l.from(k.substring(2), "hex")); + return __assign$4.apply(this, arguments); + }; + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; } }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$l.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; + }); + } + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var browser = invariant; + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$m.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$m.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$m.from([0x00]) + : Buffer$m.alloc(0); + data = Buffer$m.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$m.concat([ + output.amount, + isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$m.concat(endData); + extraPart = isDecred + ? data + : Buffer$m.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer$l.from(value); + }); } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); - keyPair.serialize(buf); - } - buf.writeUInt8(0); - } - function b() { - return Buffer$l.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$l.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer$l.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); } - - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$m.from([0x02]); + } } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); + else { + if (inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$m.from([0x00]); + } + } + data = Buffer$m.concat([ + prefix, + inputValue, + isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$l.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); + }); + }); } - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$l.alloc(1); - buffer_1[0] = value; - return buffer_1; + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$m.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); } - if (value <= 0xffff) { - var buffer_2 = Buffer$l.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); } - var buffer = Buffer$l.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; + hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); } - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$l.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$l.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$l.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$l.concat([ - inputBuffer, - input.prevout, - Buffer$l.from([0x00]), - input.sequence, - ]) - : Buffer$l.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$l.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$l.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$l.alloc(0), - transaction.extraData || Buffer$l.alloc(0), + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$m.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$m.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([sigHashType]), + ]) + : Buffer$m.concat([ + pathsBuffer, + Buffer$m.from([0x00]), + lockTimeBuffer, + Buffer$m.from([sigHashType]), ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$m.concat([buffer, expiryHeight]); } - return Buffer$l.concat([ - transaction.version, - timestamp ? timestamp : Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37427,7 +35366,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37454,459 +35393,116 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver.major(appAndVersion.version) >= 2); + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); + }); } - var id$1 = 0; - var subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch(obj); + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = function (cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } - catch (e) { - console.error(e); + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; } - } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; - } + }); + }); }; - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log, - listen: listen - }); + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver$2.gte(version, "1.4.0"); + } - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -37914,9 +35510,9 @@ } return t; }; - return __assign$4.apply(this, arguments); + return __assign$3.apply(this, arguments); }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37925,7 +35521,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37952,89 +35548,474 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { switch (_b.label) { case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$m.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$m.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$m.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$m.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$m.concat([ + Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$m.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$m.concat([ + Buffer$m.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$m.alloc(1); + keySize = Buffer$m.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$m.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$m.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$m.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$m.concat([ + Buffer$m.from("02", "hex"), + Buffer$m.from([signatures[i].length]), + signatures[i], + Buffer$m.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$m.concat([witness, tmpScriptData]); + } + result = Buffer$m.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$m.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$m.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$m.alloc(0), + targetTransaction.extraData || Buffer$m.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$m.concat([ + decredWitness_1, + Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0xff, 0xff, 0xff, 0xff]), + Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$m.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; } }); }); } - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$m.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); }; - - var browser = invariant; - - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38043,7 +36024,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38070,7 +36051,7 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$7 = (undefined && undefined.__values) || function(o) { + var __values$4 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38081,260 +36062,573 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$l.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { switch (_c.label) { case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$l.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ - transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + _c.label = 1; case 1: - _c.sent(); + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); _c.label = 2; case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; + if (!!inputs_1_1.done) return [3 /*break*/, 6]; input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$l.from([0x00]) - : Buffer$l.alloc(0); - data = Buffer$l.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$m.from(trustedInput, "hex") + : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: e_1_1 = _c.sent(); e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: + return [3 /*break*/, 9]; + case 8: try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; case 11: _c.sent(); _c.label = 12; case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + i = 0; _c.label = 13; case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$l.concat([ - output.amount, - isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; case 14: _c.sent(); - _c.label = 15; + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$l.concat(endData); - extraPart = isDecred - ? data - : Buffer$l.concat([createVarint(data.length), data]); + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; } - return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; } }); }); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$m.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$m.concat([ + Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$m.concat([ + asBufferUInt32BE(version), + Buffer$m.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$m.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } } + return ar; }; - var __values$6 = (undefined && undefined.__values) || function(o) { + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38345,213 +36639,296 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$l.concat([ - transaction.version, - transaction.timestamp || Buffer$l.alloc(0), - transaction.nVersionGroupId || Buffer$l.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$l.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$l.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$l.from([0x00]); - } - } - data = Buffer$l.concat([ - prefix, - inputValue, - isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$l.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$l.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$m.from(request.subarray(1))); + this.progressCallback(); + return Buffer$m.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + GetPreimageCommand.prototype.execute = function (request) { + var req = Buffer$m.from(request.subarray(1)); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$m.from([known_preimage[i]])); + } + } + return Buffer$m.concat([ + preimage_len_varint, + Buffer$m.from([payload_size]), + Buffer$m.from(known_preimage.subarray(0, payload_size)), + ]); + } + throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = Buffer$m.from(request.subarray(1)); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$m.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$m.from([proof.length]), + Buffer$m.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = Buffer$m.from(request.subarray(1)); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; } - hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$l.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$l.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$l.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([sigHashType]), - ]) - : Buffer$l.concat([ - pathsBuffer, - Buffer$l.from([0x00]), - lockTimeBuffer, - Buffer$l.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$l.concat([buffer, expiryHeight]); + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$m.concat(__spreadArray$1([ + Buffer$m.from([n_returned_elements]), + Buffer$m.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code ".concat(cmd.code)); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); + this.addKnownPreimage(preimage); + } } - return result; - }); - } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code ".concat(cmdCode)); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38560,7 +36937,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38587,45 +36964,380 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ + Buffer$m.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$m.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ + Buffer$m.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + Buffer$m.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput ".concat(i, ":"); + str += " prevout ".concat(prevout.toString("hex")); + str += " script ".concat(script.toString("hex")); + str += " sequence ".concat(sequence.toString("hex")); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput ".concat(i, ":"); + str += " amount ".concat(amount.toString("hex")); + str += " script ".concat(script.toString("hex")); + }); + return str; } - function hashOutputFull(transport, outputScript, additionals) { + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$m.alloc(0); + var nExpiryHeight = Buffer$m.alloc(0); + var nVersionGroupId = Buffer$m.alloc(0); + var extraData = Buffer$m.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$m.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$m.alloc(0); + var tree = Buffer$m.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree }); - }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + return t; } - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38634,7 +37346,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38661,435 +37373,712 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } - - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + else { + options = opts || {}; } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$l.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$l.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$l.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$l.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$l.concat([ - Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$l.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$l.concat([ - Buffer$l.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; } else { - signatureSize = Buffer$l.alloc(1); - keySize = Buffer$l.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$l.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); + return [2 /*return*/, this["new"]()]; } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$l.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$l.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$l.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$l.concat([ - Buffer$l.from("02", "hex"), - Buffer$l.from([signatures[i].length]), - signatures[i], - Buffer$l.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$l.concat([witness, tmpScriptData]); + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; + }; + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; } - result = Buffer$l.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$l.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$l.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$l.alloc(0), - targetTransaction.extraData || Buffer$l.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$l.concat([ - decredWitness_1, - Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0x00, 0x00, 0x00, 0x00]), - Buffer$l.from([0xff, 0xff, 0xff, 0xff]), - Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$l.concat([result, decredWitness_1]); } - return [2 /*return*/, result.toString("hex")]; + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } } - }); - }); + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); + var AmountRequired = createCustomErrorClass("AmountRequired"); + var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass("NetworkDown"); + var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass("FeeRequired"); + var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); + var SyncError = createCustomErrorClass("SyncError"); + var PairingFailed = createCustomErrorClass("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); + var DBNotReset = createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); + + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass, + addCustomErrorDeserializer: addCustomErrorDeserializer, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError, + StatusCodes: StatusCodes, + getAltStatusMessage: getAltStatusMessage, + TransportStatusError: TransportStatusError + }); - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39098,7 +38087,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39125,127 +38114,32 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$l.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + finally { if (e) throw e.error; } + } + return ar; }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } + return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$4 = (undefined && undefined.__values) || function(o) { + var __values = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -39256,2433 +38150,2341 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - startTime = Date.now(); - targetTransaction = { - inputs: [], - timestamp: Buffer$l.alloc(0), - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$l.from(trustedInput, "hex") - : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$l.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { + var Transport = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$m.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$m.concat([ + Buffer$m.from([cla, ins, p1, p2]), + Buffer$m.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { switch (_a.label) { case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: res = _a.sent(); - this.derivationsCache[path] = res; + if (unresponsiveReached) { + this.emit("responsive"); + } return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; } }); - }); + }); }; + this._appAPIlock = null; + } + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); }; /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); }; /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); + * Enable or not logs of the binary exchange */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); }; /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; }; /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); + TransportFoo.create().then(transport => ...) */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } } - return signP2SHTransaction(this.transport, arg); }; - return BtcOld; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$l.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; + + var hidFraming$1 = {}; + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$m.alloc(2); + b.writeUInt16BE(value, 0); + return b; } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$l.concat([ - Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); + var initialAcc = { + data: Buffer$m.alloc(0), + dataLength: 0, + sequence: 0 + }; + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$m.concat([ + data, + Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$m.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$m.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$m.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + exports["default"] = createHIDframing; + + }(hidFraming$1)); + + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$3; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$l.concat([ - asBufferUInt32BE(version), - Buffer$l.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$l.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } } - finally { if (e) throw e.error; } + return id + }); } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; + + if (other.version === this.version) { + return 0 } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$l.from(request.subarray(1))); - this.progressCallback(); - return Buffer$l.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$l.from([known_preimage[i]])); - } - } - return Buffer$l.concat([ - preimage_len_varint, - Buffer$l.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$l.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$l.from([proof.length]), - Buffer$l.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$l.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$l.concat(__spreadArray$1([ - Buffer$l.from([n_returned_elements]), - Buffer$l.from([element_len]) - ], __read$1(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); - this.addKnownPreimage(preimage); + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); + } else { + this.prerelease = [identifier, 0]; + } } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); + break - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + default: + throw new Error(`invalid increment argument: ${release}`) } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$l.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ - Buffer$l.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), - Buffer$l.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$l.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; - }); - }); - }; - return AppClient; - }()); + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$l.alloc(0); - var nExpiryHeight = Buffer$l.alloc(0); - var nVersionGroupId = Buffer$l.alloc(0); - var extraData = Buffer$l.alloc(0); - var isDecred = additionals.includes("decred"); - var isPeercoin = additionals.includes("peercoin"); - var transaction = Buffer$l.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); - var oldpeercoin = version.equals(Buffer$l.from([0x01, 0x00, 0x00, 0x00])) || - version.equals(Buffer$l.from([0x02, 0x00, 0x00, 0x00])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - if (hasTimestamp) { - if (!isPeercoin || - (isPeercoin && oldpeercoin)) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } } + } } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$l.alloc(0); - var tree = Buffer$l.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } - else { - locktime = transaction.slice(offset, offset + 4); + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } } - if (hasExtraData) { - extraData = transaction.slice(offset); + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); + + debug$1('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; - } - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + debug$1('caret return', ret); + return ret + }) }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); - }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; } - return false; - } - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); + debug$1('xRange return', ret); - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + return ret + }) }; - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } - return error; + } } - return new Error(String(object)); + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } + + debug('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - if (typeof from.name === "string") { - to.name = from.name; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); } - if (typeof from.message === "string") { - to.message = from.message; + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true } - if (typeof from.stack === "string") { - to.stack = from.stack; + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } } - return to; - } - var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); - var AmountRequired = createCustomErrorClass("AmountRequired"); - var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass("NetworkDown"); - var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass("FeeRequired"); - var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); - var SyncError = createCustomErrorClass("SyncError"); - var PairingFailed = createCustomErrorClass("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); - var DBNotReset = createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); + }); + return min + }; + var minSatisfying_1 = minSatisfying; - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass, - addCustomErrorDeserializer: addCustomErrorDeserializer, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError, - StatusCodes: StatusCodes, - getAltStatusMessage: getAltStatusMessage, - TransportStatusError: TransportStatusError - }); + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } + } + return true }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$l.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$l.concat([ - Buffer$l.from([cla, ins, p1, p2]), - Buffer$l.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError(sw); - } - return [2 /*return*/, response]; - } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; - } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } - var hidFraming$1 = {}; + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$l.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$l.alloc(0), - dataLength: 0, - sequence: 0 + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$l.concat([ - data, - Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$l.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$l.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$l.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - exports["default"] = createHIDframing; - }(hidFraming$1)); + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -41731,7 +40533,7 @@ }, _a[DeviceModelId.nanoSP] = { id: DeviceModelId.nanoSP, - productName: "Ledger Nano SP", + productName: "Ledger Nano S Plus", productIdMM: 0x50, legacyUsbProductId: 0x0005, usbOnly: true, @@ -42118,7 +40920,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$l.from(r.data.buffer); + buffer = Buffer$m.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: From a5edc93b7a1b2d9cc41e6902b9e1e5a91d561ea0 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 12:21:50 +1100 Subject: [PATCH 46/78] different way to split --- js/cointoolkit.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index a8e9f2cc..6d9dc7e7 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -707,11 +707,12 @@ $(document).ready(function() { {verify: false, format: "legacy"} ); + var hasTimestamp = isPeercoin && currenttransaction.version < 3; var publicKey = result.publicKey; var path = coinjs.ledgerPath; console.log("path",path,"address",result.bitcoinAddress,"pubkey",result.publicKey); - var txn = appBtc.splitTransaction(currenttransaction.serialize(),false,isPeercoin,false,["peercoin"]); + var txn = appBtc.splitTransaction(currenttransaction.serialize(),false,hasTimestamp,false); var outputsBuffer = Crypto.util.bytesToHex(appBtc.serializeTransactionOutputs(txn)); var inputs = []; @@ -729,7 +730,8 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - inputs.push([result[1],appBtc.splitTransaction(result[0],false,isPeercoin,false,["peercoin"]),currenttransaction.ins[result[1]].outpoint.index,script]); + hasTimestamp = isPeercoin && result[0][1] in ['1','2'] + inputs.push([result[1],appBtc.splitTransaction(result[0],false,hasTimestamp,false),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { // we are ready From b62c835e29606150743d1ebac5bac289f13f12fe Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 12:32:23 +1100 Subject: [PATCH 47/78] try with segwit --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 6d9dc7e7..6bbbe540 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -750,7 +750,7 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, segwit:true, additionals: ["peercoin"]}; result = await appBtc.signP2SHTransaction(params); var success=false; From b138a7268099a00af6c009b25c288eebad767f5f Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 12:53:10 +1100 Subject: [PATCH 48/78] new version --- js/ledger.js | 52 +++++++++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index c69a2c3a..99825cbf 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -33236,7 +33236,7 @@ if (userSuppliedRedeemScript && !expectedRedeemScript.equals(userSuppliedRedeemScript)) { // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); } this.psbt.setInputRedeemScript(i, expectedRedeemScript); this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); @@ -33451,7 +33451,7 @@ }()); function createKey$1(masterFingerprint, path, xpub) { var accountPath = pathArrayToString(path); - return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; } /** @@ -34010,11 +34010,11 @@ var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); var taprootSig = psbt.getInputTapKeySig(i); if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input ".concat(i, " present")); + throw Error("No signature for input " + i + " present"); } if (legacyPubkeys.length > 0) { if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); } if (taprootSig) { throw Error("Both taproot and non-taproot signatures present."); @@ -34325,7 +34325,7 @@ xpub = _b.sent(); xpubComponents = getXpubComponents(xpub); if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); } return [2 /*return*/, xpub]; } @@ -34537,7 +34537,7 @@ // going on. for (i = 0; i < accountPath.length; i++) { if (accountPath[i] != pathElems[i]) { - throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); } } return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; @@ -34619,7 +34619,7 @@ // No legacy BIP32_DERIVATION, assume we're using taproot. pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input ".concat(k)); + throw Error("Missing pubkey derivation for input " + k); } psbt.setInputTapKeySig(k, v); } @@ -36070,12 +36070,12 @@ }; function signP2SHTransaction(transport, arg) { return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; return __generator$6(this, function (_c) { switch (_c.label) { case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; nullScript = Buffer$m.alloc(0); nullPrevout = Buffer$m.alloc(0); defaultVersion = Buffer$m.alloc(4); @@ -36085,8 +36085,10 @@ signatures = []; firstRun = true; resuming = false; + startTime = Date.now(); targetTransaction = { inputs: [], + timestamp: Buffer$m.alloc(0), version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; @@ -36168,13 +36170,17 @@ : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$m.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } if (segwit) { pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; } else { pseudoTX.inputs[i].script = script; } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; case 14: _c.sent(); if (!!segwit) return [3 /*break*/, 16]; @@ -36710,7 +36716,7 @@ Buffer$m.from(known_preimage.subarray(0, payload_size)), ]); } - throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); + throw Error("Requested unknown preimage for: " + req_hash_hex); }; return GetPreimageCommand; }(ClientCommand)); @@ -36743,7 +36749,7 @@ } var mt = this.known_trees.get(hash_hex); if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); } if (leaf_index >= tree_size || mt.size() != tree_size) { throw Error("Invalid index or tree size."); @@ -36793,7 +36799,7 @@ var leef_hash_hex = leef_hash.toString("hex"); var mt = this.known_trees.get(root_hash_hex); if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); } var leaf_index = 0; var found = 0; @@ -36872,7 +36878,7 @@ for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { var cmd = commands_1_1.value; if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code ".concat(cmd.code)); + throw new Error("Multiple commands with code " + cmd.code); } this.commands.set(cmd.code, cmd); } @@ -36921,7 +36927,7 @@ var cmdCode = request[0]; var cmd = this.commands.get(cmdCode); if (!cmd) { - throw new Error("Unexpected command code ".concat(cmdCode)); + throw new Error("Unexpected command code " + cmdCode); } return cmd.execute(request); }; @@ -37188,16 +37194,16 @@ } transaction.inputs.forEach(function (_a, i) { var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput ".concat(i, ":"); - str += " prevout ".concat(prevout.toString("hex")); - str += " script ".concat(script.toString("hex")); - str += " sequence ".concat(sequence.toString("hex")); + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); }); (transaction.outputs || []).forEach(function (_a, i) { var amount = _a.amount, script = _a.script; - str += "\noutput ".concat(i, ":"); - str += " amount ".concat(amount.toString("hex")); - str += " script ".concat(script.toString("hex")); + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); }); return str; } @@ -37333,7 +37339,7 @@ nExpiryHeight: nExpiryHeight, extraData: extraData }; - log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); return t; } From 831f6209eeb5ec15c3e2c2096b10fb04a7b5269a Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 9 Feb 2022 13:08:58 +1100 Subject: [PATCH 49/78] no segwit --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 6bbbe540..3469cbbc 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -750,7 +750,7 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, segwit:true, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; result = await appBtc.signP2SHTransaction(params); var success=false; From fa17d782c85af49f243ef6297583f7bbf577a640 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 10 Feb 2022 13:36:58 +1100 Subject: [PATCH 50/78] coinstake initial work --- js/coin.js | 6 +++--- js/cointoolkit.js | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/js/coin.js b/js/coin.js index b6177abc..2250db5c 100644 --- a/js/coin.js +++ b/js/coin.js @@ -19,7 +19,7 @@ coinjs.priv = 0x80; coinjs.multisig = 0x05; coinjs.hdkey = {'prv':0x0488ade4, 'pub':0x0488b21e}; - coinjs.bech32 = {'charset':'qpzry9x8gf2tvdw0s3jn54khce6mua7l', 'version':0, 'hrp':'bc'}; + coinjs.bech32 = {'charset':'qpzry9x8gf2tvdw0s3jn54khce6mua7l', 'version':0, 'hrp':'pc'}; coinjs.txExtraTimeField = false; coinjs.txExtraTimeFieldValue = false; coinjs.txExtraUnitField = false; @@ -1979,7 +1979,7 @@ var buffer = []; buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version),4)); - if (coinjs.txExtraTimeField) { + if (coinjs.txExtraTimeField && (coinjs.symbol in ['tPPC', 'PPC'] && this.version<3)) { buffer = buffer.concat(coinjs.numToBytes(parseInt(this.nTime),4)); } @@ -2064,7 +2064,7 @@ obj.version = readAsInt(4); - if (coinjs.txExtraTimeField) { + if (coinjs.txExtraTimeField && (coinjs.symbol in ['tPPC', 'PPC'] && obj.version<3)) { obj.nTime = readAsInt(4); } diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 3469cbbc..da7787b7 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -367,6 +367,13 @@ $(document).ready(function() { h += ''+(o.value/("1e"+coinjs.decimalPlaces)).toFixed(coinjs.decimalPlaces)+''; h += ''; h += ''; + } else if(o.script.chunks.length==0) { + h += ''; + h += ''; + h += ''; // to account for known address value + h += '0.0000000'; + h += ''; + h += ''; } else { var addr = ''; From 323e21acb22c671727e170e8dac64cb7bf8ec80c Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 10 Feb 2022 13:46:51 +1100 Subject: [PATCH 51/78] enable pubkey outputs --- js/cointoolkit.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index da7787b7..180fd1b9 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -389,6 +389,9 @@ $(document).ready(function() { }); } else if((o.script.chunks.length==2) && o.script.chunks[0]==0){ addr = coinjs.bech32_encode(coinjs.bech32.hrp, [coinjs.bech32.version].concat(coinjs.bech32_convert(o.script.chunks[1], 8, 5, true))); + } else if((o.script.chunks.length==2) && o.script.chunks[1]==172){ + var pubKey = Crypto.util.bytesToHex(o.script.chunks[0]) + addr = coinjs.pubkey2address(pubKey, coinjs.pub); } else { var scriptHash = Crypto.util.bytesToHex(o.script.chunks[1]); addr = coinjs.scripthash2address(scriptHash, coinjs.multisig); From afc6de5d31451e1e6134045308d1eec5353cc59a Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 10 Feb 2022 14:05:34 +1100 Subject: [PATCH 52/78] let's specify initial timestamp only when version requires it --- js/cointoolkit.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 180fd1b9..c8e059eb 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -760,7 +760,10 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, transactionVersion:1, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; + if (timeStamp) { + params.initialTimestamp = timeStamp; + } result = await appBtc.signP2SHTransaction(params); var success=false; From 310e85bf909d84ee20762451285c3eb8530526f8 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 10 Feb 2022 16:28:44 +1100 Subject: [PATCH 53/78] correct js syntax --- js/coin.js | 2 +- js/cointoolkit.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/js/coin.js b/js/coin.js index 2250db5c..b5c0a800 100644 --- a/js/coin.js +++ b/js/coin.js @@ -1979,7 +1979,7 @@ var buffer = []; buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version),4)); - if (coinjs.txExtraTimeField && (coinjs.symbol in ['tPPC', 'PPC'] && this.version<3)) { + if (coinjs.txExtraTimeField && (['tPPC','PPC'].includes(coinjs.symbol) && this.version<3)) { buffer = buffer.concat(coinjs.numToBytes(parseInt(this.nTime),4)); } diff --git a/js/cointoolkit.js b/js/cointoolkit.js index c8e059eb..f16b53b3 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -740,7 +740,7 @@ $(document).ready(function() { for (var i = 0; i < currenttransaction.ins.length; i++) { var result = providers[$("#coinSelector").val()].getTransaction[toolkit.getTransaction](currenttransaction.ins[i].outpoint.hash,i,async function(result) { // todo replace !isPeercoin with proper segwit support flag from coinjs params - hasTimestamp = isPeercoin && result[0][1] in ['1','2'] + hasTimestamp = isPeercoin && ['1','2'].includes(result[0][1]) inputs.push([result[1],appBtc.splitTransaction(result[0],false,hasTimestamp,false),currenttransaction.ins[result[1]].outpoint.index,script]); paths.push(path); if (inputs.length == currenttransaction.ins.length) { From a57083edeb89fd7f6ca1e279930a56138951016c Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 10 Feb 2022 16:39:05 +1100 Subject: [PATCH 54/78] correct js syntax --- js/coin.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/coin.js b/js/coin.js index b5c0a800..5324f92d 100644 --- a/js/coin.js +++ b/js/coin.js @@ -2064,7 +2064,7 @@ obj.version = readAsInt(4); - if (coinjs.txExtraTimeField && (coinjs.symbol in ['tPPC', 'PPC'] && obj.version<3)) { + if (coinjs.txExtraTimeField && (['tPPC','PPC'].includes(coinjs.symbol) && obj.version<3)) { obj.nTime = readAsInt(4); } From 6366bda87d773f4de655203ef4c8fd1d6786f611 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 14 Feb 2022 15:28:31 +1100 Subject: [PATCH 55/78] let's try older hw-btc-app for time being --- js/ledger.js | 61247 +++++++++++++++++++++++++------------------------ 1 file changed, 30625 insertions(+), 30622 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 99825cbf..c20e37ca 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -999,7 +999,7 @@ var toString = {}.toString; - var isArray$1 = Array.isArray || function (arr) { + var isArray$3 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1029,12 +1029,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$m.TYPED_ARRAY_SUPPORT + return Buffer$k.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1043,14 +1043,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$m(length); + that = new Buffer$k(length); } that.length = length; } @@ -1068,9 +1068,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$m (arg, encodingOrOffset, length) { - if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { - return new Buffer$m(arg, encodingOrOffset, length) + function Buffer$k (arg, encodingOrOffset, length) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { + return new Buffer$k(arg, encodingOrOffset, length) } // Common case. @@ -1082,18 +1082,18 @@ } return allocUnsafe(this, arg) } - return from$1(this, arg, encodingOrOffset, length) + return from(this, arg, encodingOrOffset, length) } - Buffer$m.poolSize = 8192; // not used by this implementation + Buffer$k.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$m._augment = function (arr) { - arr.__proto__ = Buffer$m.prototype; + Buffer$k._augment = function (arr) { + arr.__proto__ = Buffer$k.prototype; return arr }; - function from$1 (that, value, encodingOrOffset, length) { + function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1117,13 +1117,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$m.from = function (value, encodingOrOffset, length) { - return from$1(null, value, encodingOrOffset, length) + Buffer$k.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) }; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { - Buffer$m.prototype.__proto__ = Uint8Array.prototype; - Buffer$m.__proto__ = Uint8Array; + if (Buffer$k.TYPED_ARRAY_SUPPORT) { + Buffer$k.prototype.__proto__ = Uint8Array.prototype; + Buffer$k.__proto__ = Uint8Array; } function assertSize (size) { @@ -1154,14 +1154,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$m.alloc = function (size, fill, encoding) { + Buffer$k.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1172,13 +1172,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$m.allocUnsafe = function (size) { + Buffer$k.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$m.allocUnsafeSlow = function (size) { + Buffer$k.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1187,7 +1187,7 @@ encoding = 'utf8'; } - if (!Buffer$m.isEncoding(encoding)) { + if (!Buffer$k.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1234,10 +1234,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$1(obj.data)) { + if (obj.type === 'Buffer' && isArray$3(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1284,12 +1284,12 @@ } return length | 0 } - Buffer$m.isBuffer = isBuffer; + Buffer$k.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$m.compare = function compare (a, b) { + Buffer$k.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1312,7 +1312,7 @@ return 0 }; - Buffer$m.isEncoding = function isEncoding (encoding) { + Buffer$k.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1331,13 +1331,13 @@ } }; - Buffer$m.concat = function concat (list, length) { - if (!isArray$1(list)) { + Buffer$k.concat = function concat (list, length) { + if (!isArray$3(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$m.alloc(0) + return Buffer$k.alloc(0) } var i; @@ -1348,7 +1348,7 @@ } } - var buffer = Buffer$m.allocUnsafe(length); + var buffer = Buffer$k.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1404,7 +1404,7 @@ } } } - Buffer$m.byteLength = byteLength$1; + Buffer$k.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1478,7 +1478,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$m.prototype._isBuffer = true; + Buffer$k.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1486,7 +1486,7 @@ b[m] = i; } - Buffer$m.prototype.swap16 = function swap16 () { + Buffer$k.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1497,7 +1497,7 @@ return this }; - Buffer$m.prototype.swap32 = function swap32 () { + Buffer$k.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1509,7 +1509,7 @@ return this }; - Buffer$m.prototype.swap64 = function swap64 () { + Buffer$k.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1523,20 +1523,20 @@ return this }; - Buffer$m.prototype.toString = function toString () { + Buffer$k.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$m.prototype.equals = function equals (b) { + Buffer$k.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$m.compare(this, b) === 0 + return Buffer$k.compare(this, b) === 0 }; - Buffer$m.prototype.inspect = function inspect () { + Buffer$k.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1546,7 +1546,7 @@ return '' }; - Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1645,7 +1645,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$m.from(val, encoding); + val = Buffer$k.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1657,7 +1657,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$m.TYPED_ARRAY_SUPPORT && + if (Buffer$k.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1727,15 +1727,15 @@ return -1 } - Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1786,7 +1786,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$m.prototype.write = function write (string, offset, length, encoding) { + Buffer$k.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1858,7 +1858,7 @@ } }; - Buffer$m.prototype.toJSON = function toJSON () { + Buffer$k.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2011,7 +2011,7 @@ return res } - Buffer$m.prototype.slice = function slice (start, end) { + Buffer$k.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2033,12 +2033,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$m.prototype; + newBuf.__proto__ = Buffer$k.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$m(sliceLen, undefined); + newBuf = new Buffer$k(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2055,7 +2055,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2070,7 +2070,7 @@ return val }; - Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2086,22 +2086,22 @@ return val }; - Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2110,7 +2110,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2119,7 +2119,7 @@ this[offset + 3]) }; - Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2137,7 +2137,7 @@ return val }; - Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2155,25 +2155,25 @@ return val }; - Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2182,7 +2182,7 @@ (this[offset + 3] << 24) }; - Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2191,22 +2191,22 @@ (this[offset + 3]) }; - Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2217,7 +2217,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2236,7 +2236,7 @@ return offset + byteLength }; - Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2255,11 +2255,11 @@ return offset + byteLength }; - Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2272,11 +2272,11 @@ } } - Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2285,11 +2285,11 @@ return offset + 2 }; - Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2305,11 +2305,11 @@ } } - Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2320,11 +2320,11 @@ return offset + 4 }; - Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2335,7 +2335,7 @@ return offset + 4 }; - Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2358,7 +2358,7 @@ return offset + byteLength }; - Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2381,21 +2381,21 @@ return offset + byteLength }; - Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2404,11 +2404,11 @@ return offset + 2 }; - Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2417,11 +2417,11 @@ return offset + 2 }; - Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2432,12 +2432,12 @@ return offset + 4 }; - Buffer$m.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$k.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; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2461,11 +2461,11 @@ return offset + 4 } - Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2477,16 +2477,16 @@ return offset + 8 } - Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2518,7 +2518,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2538,7 +2538,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$m.prototype.fill = function fill (val, start, end, encoding) { + Buffer$k.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2558,7 +2558,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2587,7 +2587,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$m(val, encoding).toString()); + : utf8ToBytes(new Buffer$k(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5021,8 +5021,6 @@ }; }(safeBuffer, safeBuffer.exports)); - var readableBrowser = {exports: {}}; - // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5158,23 +5156,23 @@ }; var title = 'browser'; var platform = 'browser'; - var browser$6 = true; + var browser$5 = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config$1 = {}; + var config = {}; - function noop$2() {} + function noop() {} - var on = noop$2; - var addListener = noop$2; - var once$3 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; + var on = noop; + var addListener = noop; + var once$1 = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); @@ -5222,14 +5220,14 @@ var process = { nextTick: nextTick, title: title, - browser: browser$6, + browser: browser$5, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, - once: once$3, + once: once$1, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -5241,10 +5239,12 @@ hrtime: hrtime, platform: platform, release: release, - config: config$1, + config: config, uptime: uptime }; + var readable = {exports: {}}; + var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; @@ -5280,7 +5280,7 @@ EventEmitter.init.call(this); } events.exports = EventEmitter; - events.exports.once = once$2; + events.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; @@ -5672,7 +5672,7 @@ return ret; } - function once$2(emitter, name) { + function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); @@ -5723,13175 +5723,12988 @@ var EventEmitter$1 = events.exports; - var streamBrowser = events.exports.EventEmitter; - - var _nodeResolve_empty = {}; - - var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': _nodeResolve_empty - }); - - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - - var _require$2 = buffer, - Buffer$l = _require$2.Buffer; - - var _require2 = require$$3, - inspect$1 = _require2.inspect; - - var custom = inspect$1 && inspect$1.custom || 'inspect'; - - function copyBuffer(src, target, offset) { - Buffer$l.prototype.copy.call(src, target, offset); + var inherits$h; + if (typeof Object.create === 'function'){ + inherits$h = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$h = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; } + var inherits$i = inherits$h; - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$l.alloc(0); - var ret = Buffer$l.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$l.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; + 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]'; } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect$1(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); + default: + return x; } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); - } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull$1(x) || !isObject$1(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); } + } + return str; + } - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined$1(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); - } else { - nextTick(emitCloseNT, _this); + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); - } else { - nextTick(emitCloseNT, _this); + warned = true; } - }); + return fn.apply(this, arguments); + } - return this; + return deprecated; } - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined$1(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; } - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); + /** + * 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$1(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined$1(ctx.depth)) ctx.depth = 2; + if (isUndefined$1(ctx.colors)) ctx.colors = false; + if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + // 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] + }; - 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; + // 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 emitErrorNT(self, err) { - self.emit('error', err); - } - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + function stylizeNoColor(str, styleType) { + return str; } - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - var errorsBrowser = {}; + function arrayToHash(array) { + var hash = {}; - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + array.forEach(function(val, idx) { + hash[val] = true; + }); - var codes = {}; + return hash; + } - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); + 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$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== 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$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); } + return ret; } - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError$1(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate$1(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError$1(value)) { + return formatError(value); } - } else { - return "of ".concat(thing, " ").concat(String(expected)); } - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + var base = '', array = false, braces = ['{', '}']; - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; + // Make Array say that they are Array + if (isArray$2(value)) { + array = true; + braces = ['[', ']']; } - return str.substring(this_len - search.length, this_len) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + // Make RegExps say that they are RegExps + if (isRegExp$1(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; + // Make dates with properties first say the date + if (isDate$1(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; + // Make error with message first say the error + if (isError$1(value)) { + base = ' ' + formatError(value); } - } - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; + if (recurseTimes < 0) { + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } } - var msg; + ctx.seen.push(value); - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); } - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg; - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - errorsBrowser.codes = codes; - - var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + ctx.seen.pop(); - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + return reduceToSingleString(output, base, braces); } - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } // Default value + function formatPrimitive(ctx, value) { + if (isUndefined$1(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber$1(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean$1(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull$1(value)) + return ctx.stylize('null', 'null'); + } - return state.objectMode ? 16 : 16 * 1024; + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } - var state = { - getHighWaterMark: getHighWaterMark$2 - }; - - /** - * Module exports. - */ - var browser$5 = deprecate$1; + 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; + } - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - function deprecate$1 (fn, msg) { - if (config('noDeprecation')) { - return fn; + 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'); + } } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull$1(recurseTimes)) { + str = formatValue(ctx, desc.value, null); } else { - console.warn(msg); + str = formatValue(ctx, desc.value, recurseTimes - 1); } - warned = true; + 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'); } - return fn.apply(this, arguments); } - - return deprecated; - } - - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!commonjsGlobal.localStorage) return false; - } catch (_) { - return false; + if (isUndefined$1(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'); + } } - var val = commonjsGlobal.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; - } - var _stream_writable = Writable$2; - // there will be only 2 of these for each stream + return name + ': ' + str; + } - function CorkedRequest$1(state) { - var _this = this; + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - this.next = null; - this.entry = null; + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - this.finish = function () { - onCorkedFinish(_this, state); - }; + 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()`. + function isArray$2(ar) { + return Array.isArray(ar); + } - var Duplex$4; - /**/ + function isBoolean$1(arg) { + return typeof arg === 'boolean'; + } - Writable$2.WritableState = WritableState$1; - /**/ + function isNull$1(arg) { + return arg === null; + } - var internalUtil = { - deprecate: browser$5 - }; - /**/ + function isNumber$1(arg) { + return typeof arg === 'number'; + } - /**/ + function isString$1(arg) { + return typeof arg === 'string'; + } - var Stream$2 = streamBrowser; - /**/ + function isUndefined$1(arg) { + return arg === void 0; + } + function isRegExp$1(re) { + return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; + } - var Buffer$k = buffer.Buffer; + function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; + } - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + function isDate$1(d) { + return isObject$1(d) && objectToString$1(d) === '[object Date]'; + } - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$k.from(chunk); + function isError$1(e) { + return isObject$1(e) && + (objectToString$1(e) === '[object Error]' || e instanceof Error); } - function _isUint8Array$1(obj) { - return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; + function isFunction$1(arg) { + return typeof arg === 'function'; } - var destroyImpl$1 = destroy_1; + function objectToString$1(o) { + return Object.prototype.toString.call(o); + } - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$1(add)) return origin; - var _require$codes$3 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + 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 errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - inherits_browser.exports(Writable$2, Stream$2); + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - function nop$1() {} + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - function WritableState$1(options, stream, isDuplex) { - Duplex$4 = Duplex$4 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; - this.finalCalled = false; // drain event flag. + var string_decoder = {}; - this.needDrain = false; // at the start of calling end() + var StringDecoder_1; + // 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. - this.ending = false; // when end() has been called, and returned + var Buffer$j = buffer.Buffer; - this.ended = false; // when 'finish' is emitted + var isBufferEncoding = Buffer$j.isEncoding + || function(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; + } + }; - this.finished = false; // has it been destroyed - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$j(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; - this.length = 0; // a flag to see when we're in the middle of a write. - this.writing = false; // when true all writes will be buffered until .uncork() call + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$2.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); - this.onwrite = function (er) { - onwrite$1(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - this.writecb = null; // the amount that is being written when _write is called. + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - this.prefinished = false; // True if the error was already emitted and should not be thrown again + charStr += buffer.toString(this.encoding, 0, end); - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + // or just emit the charStr + return charStr; + }; - this.autoDestroy = !!options.autoDestroy; // count buffered requests + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; - this.corkedRequestsFree = new CorkedRequest$1(this); - } + // See http://en.wikipedia.org/wiki/UTF-8#Description - WritableState$1.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - while (current) { - out.push(current); - current = current.next; - } + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - return out; + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; }; - (function () { - try { - Object.defineProperty(WritableState$1.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. + StringDecoder$2.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + return res; + }; - var realHasInstance; + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$2, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$2) return false; - return object && object._writableState instanceof WritableState$1; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } - function Writable$2(options) { - Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$4; - if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); - this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } - this.writable = true; + Readable$2.ReadableState = ReadableState$1; - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; + var debug$4 = debuglog('stream'); + inherits$i(Readable$2, EventEmitter$1); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState$1(options, stream) { - Stream$2.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. + options = options || {}; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - Writable$2.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - function writeAfterEnd$1(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - function validChunk$1(stream, state, chunk, cb) { - var er; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); - } + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - return true; - } + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - var isBuf = !state.objectMode && _isUint8Array$1(chunk); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (isBuf && !Buffer$k.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; } + } + function Readable$2(options) { - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (!(this instanceof Readable$2)) return new Readable$2(options); - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop$1; - if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; + this._readableState = new ReadableState$1(options, this); - Writable$2.prototype.cork = function () { - this._writableState.corked++; - }; + // legacy + this.readable = true; - Writable$2.prototype.uncork = function () { - var state = this._writableState; + if (options && typeof options.read === 'function') this._read = options.read; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + EventEmitter$1.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$2.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$k.from(chunk, encoding); + encoding = ''; + } } + + return readableAddChunk$1(this, state, chunk, encoding, false); }; - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; + // Unshift should *always* be something directly out of read() + Readable$2.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk$1(this, state, chunk, '', true); }; - Object.defineProperty(Writable$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); + Readable$2.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$k.from(chunk, encoding); - } + function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid$1(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - return chunk; - } + if (!addToFront) state.reading = false; - Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk$1(state, chunk, encoding); + if (state.needReadable) emitReadable$1(stream); + } + } - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; + maybeReadMore$1(stream, state); } + } else if (!addToFront) { + state.reading = false; } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; + return needMoreData$1(state); + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData$1(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } + // backwards compatibility. + Readable$2.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; + }; - state.bufferedRequestCount += 1; + // Don't raise the hwm > 8MB + var MAX_HWM$1 = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM$1) { + n = MAX_HWM$1; } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } - - return ret; + return n; } - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; } - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error + // you can override either this method, or the async _read(n) below. + Readable$2.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - nextTick(finishMaybe$1, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error + if (n !== 0) state.emittedReadable = false; - finishMaybe$1(stream, state); + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; } - } - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + n = howMuchToRead$1(n, state); - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } - - if (sync) { - nextTick(afterWrite$1, stream, state, finished, cb); - } else { - afterWrite$1(stream, state, finished, cb); - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; } - } - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); } - } // if there's something in the buffer waiting, then process it - - - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest$1(state); - } + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - state.bufferedRequestCount = 0; + if (ret === null) { + state.needReadable = true; + n = 0; } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; + state.length -= n; } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; - - Writable$2.prototype._writev = null; - - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable$1(this); } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - + if (ret !== null) this.emit('data', ret); - if (!state.ending) endWritable$1(this, state, cb); - return this; + return ret; }; - Object.defineProperty(Writable$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + function chunkInvalid$1(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - }); - - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + return er; } - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy$1(stream, err); + function onEofChunk$1(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } + } + state.ended = true; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe$1(stream, state); - }); + // emit 'readable' now to make sure it gets picked up. + emitReadable$1(stream); } - function prefinish$2(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable$1(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); } } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - - if (need) { - prefinish$2(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + function emitReadable_$1(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow$1(stream); + } - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); } - - return need; } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + function maybeReadMore_$1(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } - - state.ended = true; - stream.writable = false; + state.readingMore = false; } - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$2.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + Readable$2.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - state.corkedRequestsFree.next = corkReq; - } + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - Object.defineProperty(Writable$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } + var doEnd = (!pipeOpts || pipeOpts.end !== false); - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } - this._writableState.destroyed = value; + function onend() { + debug$4('onend'); + dest.end(); } - }); - Writable$2.prototype.destroy = destroyImpl$1.destroy; - Writable$2.prototype._undestroy = destroyImpl$1.undestroy; - Writable$2.prototype._destroy = function (err, cb) { - cb(err); - }; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); - /**/ + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - var objectKeys = Object.keys || function (obj) { - var keys = []; + cleanedUp = true; - for (var key in obj) { - keys.push(key); + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - return keys; - }; - /**/ - + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } - var _stream_duplex = Duplex$3; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } - var Readable$2 = _stream_readable; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - var Writable$1 = _stream_writable; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - inherits_browser.exports(Duplex$3, Readable$2); + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - { - // Allow the keys array to be GC'ed. - var keys$1 = objectKeys(Writable$1.prototype); + // tell the dest that it's being piped to + dest.emit('pipe', src); - for (var v$1 = 0; v$1 < keys$1.length; v$1++) { - var method$1 = keys$1[v$1]; - if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); } - } - - function Duplex$3(options) { - if (!(this instanceof Duplex$3)) return new Duplex$3(options); - Readable$2.call(this, options); - Writable$1.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + return dest; + }; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend$1); + function pipeOnDrain$1(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow$1(src); } - } + }; } - Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); // the no-half-open enforcer + Readable$2.prototype.unpipe = function (dest) { + var state = this._readableState; - function onend$1() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - nextTick(onEndNT$1, this); - } + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - function onEndNT$1(self) { - self.end(); - } + if (!dest) dest = state.pipes; - Object.defineProperty(Duplex$3.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + // slow case. multiple pipe destinations. + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - this._readableState.destroyed = value; - this._writableState.destroyed = value; + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; } - }); - var string_decoder$1 = {}; + // try to find the right one. + var i = indexOf$1(state.pipes, dest); + if (i === -1) return this; - /**/ + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - var Buffer$j = safeBuffer.exports.Buffer; - /**/ + dest.emit('unpipe', this); - var isEncoding = Buffer$j.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; - } + return this; }; - 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$j.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$2.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. - string_decoder$1.StringDecoder = StringDecoder$3; - function StringDecoder$3(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; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable$1(this); + } + } } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer$j.allocUnsafe(nb); - } - StringDecoder$3.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 || ''; + return res; }; + Readable$2.prototype.addListener = Readable$2.prototype.on; - StringDecoder$3.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$3.prototype.text = utf8Text; + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); + } - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$3.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); + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$2.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; + return this; }; - // 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; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); } - 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'; - } - } + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); } - } - // 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); - 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; + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); } - // 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); + Readable$2.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - return r; - } + return this; + }; - 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 flow$1(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } - 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; - } + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$2.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); - } + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; - } + self.push(null); + }); - var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } + }); - callback.apply(this, args); - }; - } - - function noop$1() {} - - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$2(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } }; - var writableEnded = stream._writableState && stream._writableState.finished; + return self; + }; - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; + // exposed for testing purposes only. + Readable$2._fromList = fromList$1; - var readableEnded = stream._readableState && stream._readableState.endEmitted; + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - var onerror = function onerror(err) { - callback.call(stream, err); - }; + return ret; + } - var onclose = function onclose() { - var err; + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } + ++c; + } + list.length -= c; + return ret; + } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$k.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + ++c; } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; + list.length -= c; + return ret; } - var endOfStream = eos$1; - - var _Object$setPrototypeO; - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var finished = endOfStream; + function endReadable$1(stream) { + var state = stream._readableState; - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - function createIterResult(value, done) { - return { - value: value, - done: done - }; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } + function forEach$2(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } } - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } + // A bit simpler than readable streams. + Writable$2.WritableState = WritableState$1; + inherits$i(Writable$2, events.exports.EventEmitter); - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } + function nop() {} - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, + function WriteReq$1(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } - next: function next() { - var _this = this; + function WritableState$1(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - if (error !== null) { - return Promise.reject(error); - } + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - var lastPromise = this[kLastPromise]; - var promise; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - promise = new Promise(this[kHandlePromise]); - } + // a flag to see when we're in the middle of a write. + this.writing = false; - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var resolve = iterator[kLastResolve]; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite$1(stream, er); + }; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; + // the amount that is being written when _write is called. + this.writelen = 0; - var async_iterator = createReadableStreamAsyncIterator$1; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - var fromBrowser = function () { - throw new Error('Readable.from is not available in the browser') - }; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - var _stream_readable = Readable$1; - /**/ + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - var Duplex$2; - /**/ + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - Readable$1.ReadableState = ReadableState$1; - /**/ + // count buffered requests + this.bufferedRequestCount = 0; - events.exports.EventEmitter; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; + WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; }; - /**/ - - /**/ + function Writable$2(options) { + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); - var Stream$1 = streamBrowser; - /**/ + this._writableState = new WritableState$1(options, this); + // legacy. + this.writable = true; - var Buffer$i = buffer.Buffer; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + if (typeof options.writev === 'function') this._writev = options.writev; + } - function _uint8ArrayToBuffer(chunk) { - return Buffer$i.from(chunk); + events.exports.EventEmitter.call(this); } - function _isUint8Array(obj) { - return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ + // Otherwise people can pipe Writable streams, which is just wrong. + Writable$2.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + function writeAfterEnd$1(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } - var debugUtil = require$$3; + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk$1(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } - var debug$9; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - if (debugUtil && debugUtil.debuglog) { - debug$9 = debugUtil.debuglog('stream'); - } else { - debug$9 = function debug() {}; - } - /**/ + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - var BufferList$1 = buffer_list; + if (typeof cb !== 'function') cb = nop; - var destroyImpl = destroy_1; + if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, chunk, encoding, cb); + } - var _require = state, - getHighWaterMark = _require.getHighWaterMark; + return ret; + }; - var _require$codes$2 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + Writable$2.prototype.cork = function () { + var state = this._writableState; + state.corked++; + }; - var StringDecoder$2; - var createReadableStreamAsyncIterator; - var from; + Writable$2.prototype.uncork = function () { + var state = this._writableState; - inherits_browser.exports(Readable$1, Stream$1); + if (state.corked) { + state.corked--; - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; - function prependListener$1(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; } - function ReadableState$1(options, stream, isDuplex) { - Duplex$2 = Duplex$2 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer$1(stream, state, chunk, encoding, cb) { + chunk = decodeChunk$1(state, chunk, encoding); - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + state.length += len; - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - this.buffer = new BufferList$1(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); + } - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + return ret; + } - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + onwriteStateUpdate$1(state); - this.readingMore = false; - this.decoder = null; - this.encoding = null; + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state); - if (options.encoding) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - this.decoder = new StringDecoder$2(options.encoding); - this.encoding = options.encoding; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite$1, stream, state, finished, cb); + /**/ + } else { + afterWrite$1(stream, state, finished, cb); + } } } - function Readable$1(options) { - Duplex$2 = Duplex$2 || _stream_duplex; - if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$2; - this._readableState = new ReadableState$1(options, this, isDuplex); // legacy + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - - Stream$1.call(this); } - Object.defineProperty(Readable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } - }); - Readable$1.prototype.destroy = destroyImpl.destroy; - Readable$1.prototype._undestroy = destroyImpl.undestroy; + // if there's something in the buffer waiting, then process it + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - Readable$1.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - Readable$1.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - if (encoding !== state.encoding) { - chunk = Buffer$i.from(chunk, encoding); - encoding = ''; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; } - - skipChunkCheck = true; } - } else { - skipChunkCheck = true; - } - return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - Readable$1.prototype.unshift = function (chunk) { - return readableAddChunk$1(this, chunk, null, true, false); + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); }; - function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$9('readableAddChunk', chunk); - var state = stream._readableState; + Writable$2.prototype._writev = null; - if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore$1(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable$1(this, state, cb); + }; - return !state.ended && (state.length < state.highWaterMark || state.length === 0); + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable$1(stream); + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); } - - maybeReadMore$1(stream, state); } - function chunkInvalid$1(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } } + return need; + } - return er; + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; } - Readable$1.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; - Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - var decoder = new StringDecoder$2(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + inherits$i(Duplex$2, Readable$2); - var p = this._readableState.buffer.head; - var content = ''; + var keys = Object.keys(Writable$2.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; + } + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } + Readable$2.call(this, options); + Writable$2.call(this, options); - this._readableState.buffer.clear(); + if (options && options.readable === false) this.readable = false; - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB + if (options && options.writable === false) this.writable = false; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - var MAX_HWM$1 = 0x40000000; + this.once('end', onend$1); + } - function computeNewHighWaterMark$1(n) { - if (n >= MAX_HWM$1) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM$1; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } + // the no-half-open enforcer + function onend$1() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + function onEndNT(self) { + self.end(); + } - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + // a transform stream is a readable/writable stream where you do + inherits$i(Transform$4, Duplex$2); - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + function TransformState$1(stream) { + this.afterTransform = function (er, data) { + return afterTransform$1(stream, er, data); + }; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); - if (n <= state.length) return n; // Don't have enough + function afterTransform$1(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - if (!state.ended) { - state.needReadable = true; - return 0; - } + var cb = ts.writecb; - return state.length; - } // you can override either this method, or the async _read(n) below. + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + ts.writechunk = null; + ts.writecb = null; - Readable$1.prototype.read = function (n) { - debug$9('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + if (data !== null && data !== undefined) stream.push(data); - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$9('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } + } + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); - n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. + Duplex$2.call(this, options); - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + this._transformState = new TransformState$1(this); + // when the writable side finishes, then flush out anything remaining. + var stream = this; - var doRead = state.needReadable; - debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$9('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - if (state.ended || state.reading) { - doRead = false; - debug$9('reading or ended', doRead); - } else if (doRead) { - debug$9('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + if (typeof options.flush === 'function') this._flush = options.flush; + } - if (state.length === 0) state.needReadable = true; // call internal read method + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done$1(stream, er); + });else done$1(stream); + }); + } - this._read(state.highWaterMark); + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$2.prototype.push.call(this, chunk, encoding); + }; - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$4.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - if (!state.reading) n = howMuchToRead$1(nOrig, state); + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } + }; - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable$1(this); + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - - if (ret !== null) this.emit('data', ret); - return ret; }; - function onEofChunk$1(stream, state) { - debug$9('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } + function done$1(stream, er) { + if (er) return stream.emit('error', er); - state.ended = true; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable$1(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_$1(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + return stream.push(null); + } - function emitReadable$1(stream) { - var state = stream._readableState; - debug$9('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + inherits$i(PassThrough$1, Transform$4); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - if (!state.emittedReadable) { - debug$9('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_$1, stream); - } + Transform$4.call(this, options); } - function emitReadable_$1(stream) { - var state = stream._readableState; - debug$9('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + inherits$i(Stream$2, EventEmitter$1); + Stream$2.Readable = Readable$2; + Stream$2.Writable = Writable$2; + Stream$2.Duplex = Duplex$2; + Stream$2.Transform = Transform$4; + Stream$2.PassThrough = PassThrough$1; - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow$1(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. + // Backwards-compat with node 0.4.x + Stream$2.Stream = Stream$2; + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); - } + function Stream$2() { + EventEmitter$1.call(this); } - function maybeReadMore_$1(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug$9('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } + Stream$2.prototype.pipe = function(dest, options) { + var source = this; - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + source.on('data', ondata); - Readable$1.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - Readable$1.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + dest.on('drain', ondrain); - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - case 1: - state.pipes = [state.pipes, dest]; - break; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - default: - state.pipes.push(dest); - break; + dest.end(); } - state.pipesCount += 1; - debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug$9('onunpipe'); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } + if (typeof dest.destroy === 'function') dest.destroy(); } - function onend() { - debug$9('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); - var cleanedUp = false; + source.on('error', onerror); + dest.on('error', onerror); + // remove all the event listeners that were added. function cleanup() { - debug$9('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); + source.removeListener('data', ondata); dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); } - src.on('data', ondata); + source.on('end', cleanup); + source.on('close', cleanup); - function ondata(chunk) { - debug$9('ondata'); - var ret = dest.write(chunk); - debug$9('dest.write', ret); + dest.on('close', cleanup); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$9('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + dest.emit('pipe', source); - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream$2, + Readable: Readable$2, + Writable: Writable$2, + Duplex: Duplex$2, + Transform: Transform$4, + PassThrough: PassThrough$1, + Stream: Stream$2 + }); - function onerror(er) { - debug$9('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + var isarray = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; + }; - prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + var util$5 = {}; - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + // 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. - dest.once('close', onclose); + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. - function onfinish() { - debug$9('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + function isArray$1(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; + } + util$5.isArray = isArray$1; - dest.once('finish', onfinish); - - function unpipe() { - debug$9('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + util$5.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + util$5.isNull = isNull; - dest.emit('pipe', src); // start the flow if it hasn't been started already. + function isNullOrUndefined(arg) { + return arg == null; + } + util$5.isNullOrUndefined = isNullOrUndefined; - if (!state.flowing) { - debug$9('pipe resume'); - src.resume(); - } + function isNumber(arg) { + return typeof arg === 'number'; + } + util$5.isNumber = isNumber; - return dest; - }; + function isString(arg) { + return typeof arg === 'string'; + } + util$5.isString = isString; - function pipeOnDrain$1(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug$9('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + util$5.isSymbol = isSymbol; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow$1(src); - } - }; + function isUndefined(arg) { + return arg === void 0; } + util$5.isUndefined = isUndefined; - Readable$1.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + util$5.isRegExp = isRegExp; - if (state.pipesCount === 0) return this; // just one destination. most common case. + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + util$5.isObject = isObject; - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + util$5.isDate = isDate; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + util$5.isError = isError; + function isFunction(arg) { + return typeof arg === 'function'; + } + util$5.isFunction = isFunction; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + util$5.isPrimitive = isPrimitive; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + util$5.isBuffer = buffer.Buffer.isBuffer; - return this; - } // try to find the right one. + function objectToString(o) { + return Object.prototype.toString.call(o); + } + // 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 index = indexOf$1(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something + var _stream_readable = Readable$1; + /**/ + var isArray = isarray; + /**/ - Readable$1.prototype.on = function (ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); - var state = this._readableState; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + /**/ + var Buffer$i = buffer.Buffer; + /**/ - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug$9('on readable', state.length, state.reading); + Readable$1.ReadableState = ReadableState; - if (state.length) { - emitReadable$1(this); - } else if (!state.reading) { - nextTick(nReadingNextTick$1, this); - } - } - } + var EE = events.exports.EventEmitter; - return res; + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; }; + /**/ - Readable$1.prototype.addListener = Readable$1.prototype.on; + var Stream$1 = require$$1; - Readable$1.prototype.removeListener = function (ev, fn) { - var res = Stream$1.prototype.removeListener.call(this, ev, fn); + /**/ + var util$4 = util$5; + util$4.inherits = inherits_browser.exports; + /**/ - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + var StringDecoder$1; - return res; - }; + util$4.inherits(Readable$1, Stream$1); - Readable$1.prototype.removeAllListeners = function (ev) { - var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); + function ReadableState(options, stream) { + options = options || {}; - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - return res; - }; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } - } + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; - function nReadingNextTick$1(self) { - debug$9('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; - Readable$1.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$9('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - state.flowing = !state.readableListening; - resume$1(this, state); - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - state.paused = false; - return this; - }; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - function resume$1(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_$1, stream, state); - } - } + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - function resume_$1(stream, state) { - debug$9('resume', state.reading); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (!state.reading) { - stream.read(0); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; } - - state.resumeScheduled = false; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); } - Readable$1.prototype.pause = function () { - debug$9('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug$9('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; - }; - - function flow$1(stream) { - var state = stream._readableState; - debug$9('flow', state.flowing); + function Readable$1(options) { + if (!(this instanceof Readable$1)) + return new Readable$1(options); - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. + this._readableState = new ReadableState(options, this); + // legacy + this.readable = true; - Readable$1.prototype.wrap = function (stream) { - var _this = this; + Stream$1.call(this); + } + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$1.prototype.push = function(chunk, encoding) { var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug$9('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer$i(chunk, encoding); + encoding = ''; } + } - _this.push(null); - }); - stream.on('data', function (chunk) { - debug$9('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + return readableAddChunk(this, state, chunk, encoding, false); + }; - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + // Unshift should *always* be something directly out of read() + Readable$1.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; - var ret = _this.push(chunk); + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. + if (state.needReadable) + emitReadable(stream); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + return needMoreData(state); + } - this._read = function (n) { - debug$9('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); + } - return this; + // backwards compatibility. + Readable$1.prototype.setEncoding = function(enc) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this._readableState.decoder = new StringDecoder$1(enc); + this._readableState.encoding = enc; }; - if (typeof Symbol === 'function') { - Readable$1.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } - - return createReadableStreamAsyncIterator(this); - }; + // Don't raise the hwm > 128MB + var MAX_HWM = 0x800000; + function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; } - Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); // exposed for testing purposes only. + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; - Readable$1._fromList = fromList$1; - Object.defineProperty(Readable$1.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. + if (state.objectMode) + return n === 0 ? 0 : 1; - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; } - return ret; - } - function endReadable$1(stream) { - var state = stream._readableState; - debug$9('endReadable', state.endEmitted); + if (n <= 0) + return 0; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT$1, state, stream); + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; } - } - function endReadableNT$1(state, stream) { - debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + return n; + } - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + // you can override either this method, or the async _read(n) below. + Readable$1.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; } - } - if (typeof Symbol === 'function') { - Readable$1.from = function (iterable, opts) { - if (from === undefined) { - from = fromBrowser; + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; } - return from(Readable$1, iterable, opts); - }; - } + if (state.length === 0) + endReadable(this); - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + return ret; } - return -1; - } - - var _stream_transform = Transform$4; - - var _require$codes$1 = errorsBrowser.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - var Duplex$1 = _stream_duplex; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - inherits_browser.exports(Transform$4, Duplex$1); + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - function afterTransform$1(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; } - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; } - } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); - Duplex$1.call(this, options); - this._transformState = { - afterTransform: afterTransform$1.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + state.length -= n; - this._readableState.sync = false; + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + return ret; + }; - this.on('prefinish', prefinish$1); + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer$i.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } - function prefinish$1() { - var _this = this; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done$1(_this, er, data); - }); - } else { - done$1(this, null, null); + function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); } - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$1.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + state.emittedReadable = true; + if (state.sync) + nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } - Transform$4.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); - }; + function emitReadable_(stream) { + stream.emit('readable'); + } - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(function() { + maybeReadMore_(stream, state); + }); } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. + } + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; + } - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$1.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); + }; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; + Readable$1.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } - }; + state.pipesCount += 1; - Transform$4.prototype._destroy = function (err, cb) { - Duplex$1.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - function done$1(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + nextTick(endFn); + else + src.once('end', endFn); - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } - var _stream_passthrough = PassThrough$1; + function onend() { + dest.end(); + } - var Transform$3 = _stream_transform; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - inherits_browser.exports(PassThrough$1, Transform$3); + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$3.call(this, options); - } + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; - var eos; - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } - var _require$codes = errorsBrowser.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } + function unpipe() { + src.unpipe(dest); + } - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } + // tell the dest that it's being piped to + dest.emit('pipe', src); - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; - } + state.flowing = true; + nextTick(function() { + flow(src); + }); + } - function call(fn) { - fn(); - } + return dest; + }; - function pipe(from, to) { - return from.pipe(to); + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; } - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); - } + function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + while (state.pipesCount && null !== (chunk = src.read())) { - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } + if (state.pipesCount === 1) + write(state.pipes); + else + forEach$1(state.pipes, write); - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } + src.emit('data', chunk); - var pipeline_1 = pipeline; + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } - (function (module, exports) { - exports = module.exports = _stream_readable; - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - }(readableBrowser, readableBrowser.exports)); + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; - var Buffer$h = safeBuffer.exports.Buffer; - var Transform$2 = readableBrowser.exports.Transform; - var inherits$i = inherits_browser.exports; + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; + } + + function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); } } - function HashBase$2 (blockSize) { - Transform$2.call(this); - this._block = Buffer$h.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + Readable$1.prototype.unpipe = function(dest) { + var state = this._readableState; - this._finalized = false; - } + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; - inherits$i(HashBase$2, Transform$2); + if (!dest) + dest = state.pipes; - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; } - callback(error); - }; + // slow case. multiple pipe destinations. - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; } - callback(error); + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; }; - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$1.prototype.on = function(ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this); + } + } } - return this + return res; }; + Readable$1.prototype.addListener = Readable$1.prototype.on; - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$1.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); }; - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + Readable$1.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); + }; - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + function emitDataEvents(stream, startPaused) { + var state = stream._readableState; - return digest - }; + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + var paused = startPaused || false; + var readable = false; - var hashBase = HashBase$2; + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream$1.prototype.pipe; + stream.on = stream.addListener = Stream$1.prototype.on; - var inherits$h = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$g = safeBuffer.exports.Buffer; + stream.on('readable', function() { + readable = true; - var ARRAY16$1 = new Array(16); + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); - function MD5$2 () { - HashBase$1.call(this, 64); + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } + stream.pause = function() { + paused = true; + this.emit('pause'); + }; - inherits$h(MD5$2, HashBase$1); + stream.resume = function() { + paused = false; + if (readable) + nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + // now make it start, just in case it hadn't already. + stream.emit('readable'); + } - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$1.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + self.push(null); + }); - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$1(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - // produce result - var buffer = Buffer$g.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } + // exposed for testing purposes only. + Readable$1._fromList = fromList; - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } + // nothing in the list, definitely empty. + if (list.length === 0) + return null; - var md5_js = MD5$2; + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer$i.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer$i(n); - var Buffer$f = buffer.Buffer; - var inherits$g = inherits_browser.exports; - var HashBase = hashBase; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); - var ARRAY16 = new Array(16); + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); - var zl = [ - 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 - ]; + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); - var zr = [ - 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 - ]; + c += cpy; + } + } + } - var sl = [ - 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 - ]; + return ret; + } - var sr = [ - 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 - ]; + function endReadable(stream) { + var state = stream._readableState; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); - function RIPEMD160$3 () { - HashBase.call(this, 64); + if (!state.endEmitted && state.calledRead) { + state.ended = true; + nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } + } - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + function forEach$1 (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } - inherits$g(RIPEMD160$3, HashBase); + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + // 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 al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + var _stream_duplex = Duplex$1; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; + /**/ - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; - } + /**/ + var util$3 = util$5; + util$3.inherits = inherits_browser.exports; + /**/ - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; + var Readable = _stream_readable; + var Writable$1 = _stream_writable; - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + util$3.inherits(Duplex$1, Readable); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + forEach(objectKeys(Writable$1.prototype), function(method) { + if (!Duplex$1.prototype[method]) + Duplex$1.prototype[method] = Writable$1.prototype[method]; + }); - // produce result - var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer - }; + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) + return new Duplex$1(options); - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } + Readable.call(this, options); + Writable$1.call(this, options); - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + if (options && options.readable === false) + this.readable = false; - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + if (options && options.writable === false) + this.writable = false; - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); } - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(this.end.bind(this)); } - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } - var ripemd160$2 = RIPEMD160$3; + // 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 sha_js = {exports: {}}; + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. - var Buffer$e = safeBuffer.exports.Buffer; + var _stream_writable = Writable; - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$e.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } + /**/ + var Buffer$h = buffer.Buffer; + /**/ - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$e.from(data, enc); - } + Writable.WritableState = WritableState; - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + /**/ + var util$2 = util$5; + util$2.inherits = inherits_browser.exports; + /**/ - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } + var Stream = require$$1; - accum += remainder; - offset += remainder; + util$2.inherits(Writable, Stream); - if ((accum % blockSize) === 0) { - this._update(block); - } - } + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } - this._len += length; - return this - }; + function WritableState(options, stream) { + options = options || {}; - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - this._block[rem] = 0x80; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - var bits = this._len * 8; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + // a flag to see when we're in the middle of a write. + this.writing = false; - this._update(this._block); - var hash = this._hash(); + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - return enc ? hash.toString(enc) : hash - }; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; - var hash$3 = Hash$7; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + // the amount that is being written when _write is called. + this.writelen = 0; - var inherits$f = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$d = safeBuffer.exports.Buffer; + this.buffer = []; - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + } - var W$5 = new Array(80); + function Writable(options) { + var Duplex = _stream_duplex; - function Sha () { - this.init(); - this._w = W$5; + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); - Hash$6.call(this, 64, 56); - } + this._writableState = new WritableState(options, this); - inherits$f(Sha, Hash$6); + // legacy. + this.writable = true; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + Stream.call(this); + } - return this + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); }; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(function() { + cb(er); + }); } - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer$h.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; } - Sha.prototype._update = function (M) { - var W = this._w; + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + if (typeof cb !== 'function') + cb = function() {}; - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + return ret; }; - Sha.prototype._hash = function () { - var H = Buffer$d.allocUnsafe(20); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer$h(chunk, encoding); + } + return chunk; + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - return H - }; + state.length += len; - var sha$4 = Sha; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - var inherits$e = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + return ret; + } - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - var W$4 = new Array(80); + function onwriteError(stream, state, sync, er, cb) { + if (sync) + nextTick(function() { + cb(er); + }); + else + cb(er); - function Sha1 () { - this.init(); - this._w = W$4; + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - Hash$5.call(this, 64, 56); + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - inherits$e(Sha1, Hash$5); + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + onwriteStateUpdate(state); - return this - }; + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); - function rotl5 (num) { - return (num << 5) | (num >>> 27) + if (sync) { + nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } } - function rotl30 (num) { - return (num << 30) | (num >>> 2) + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } } - Sha1.prototype._update = function (M) { - var W = this._w; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + doWrite(stream, state, len, chunk, encoding, cb); - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; - - Sha1.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; + } - return H + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); }; - var sha1$1 = Sha1; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - var inherits$d = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); - var K$2 = [ - 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 - ]; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; - var W$3 = new Array(64); - function Sha256$1 () { - this.init(); + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); + } - this._w = W$3; // new Array(64) + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; + } - Hash$4.call(this, 64, 56); + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; } - inherits$d(Sha256$1, Hash$4); + // 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. + - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. - return this - }; + var _stream_transform = Transform$3; - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + var Duplex = _stream_duplex; - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + /**/ + var util$1 = util$5; + util$1.inherits = inherits_browser.exports; + /**/ - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } + util$1.inherits(Transform$3, Duplex); - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; } - Sha256$1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + var cb = ts.writecb; - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } + ts.writechunk = null; + ts.writecb = null; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; + if (data !== null && data !== undefined) + stream.push(data); - Sha256$1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(32); + if (cb) + cb(er); - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } - return H - }; - var sha256$2 = Sha256$1; + function Transform$3(options) { + if (!(this instanceof Transform$3)) + return new Transform$3(options); - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + Duplex.call(this, options); - var inherits$c = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + this._transformState = new TransformState(options, this); - var W$2 = new Array(64); + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function Sha224 () { - this.init(); + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - this._w = W$2; // new Array(64) + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - Hash$3.call(this, 64, 56); + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } - inherits$c(Sha224, Sha256); - - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + Transform$3.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - return this + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$3.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); }; - Sha224.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(28); + Transform$3.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } + }; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$3.prototype._read = function(n) { + var ts = this._transformState; - return H + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } }; - var sha224 = Sha224; - var inherits$b = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + function done(stream, er) { + if (er) + return stream.emit('error', er); - var K$1 = [ - 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 - ]; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + stream._readableState; + var ts = stream._transformState; - var W$1 = new Array(160); + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); - function Sha512 () { - this.init(); - this._w = W$1; + if (ts.transforming) + throw new Error('calling transform done when still transforming'); - Hash$2.call(this, 128, 112); + return stream.push(null); } - inherits$b(Sha512, Hash$2); + // 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. - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + var _stream_passthrough = PassThrough; - return this - }; + var Transform$2 = _stream_transform; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + /**/ + var util = util$5; + util.inherits = inherits_browser.exports; + /**/ - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + util.inherits(PassThrough, Transform$2); - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + Transform$2.call(this, options); } - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + (function (module, exports) { + var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify + exports = module.exports = _stream_readable; + exports.Stream = Stream; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + }(readable, readable.exports)); - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$g = inherits_browser.exports; - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } } - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } + function HashBase$2 (blockSize) { + Transform$1.call(this); - Sha512.prototype._update = function (M) { - var W = this._w; + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + this._finalized = false; + } - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + inherits$g(HashBase$2, Transform$1); - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + callback(error); + }; - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + callback(error); + }; - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - W[i] = Wih; - W[i + 1] = Wil; + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + return this + }; - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + return digest }; - Sha512.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') }; - var sha512 = Sha512; + var hashBase = HashBase$2; - var inherits$a = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + var inherits$f = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - var W = new Array(160); + var ARRAY16$1 = new Array(16); - function Sha384 () { - this.init(); - this._w = W; + function MD5$2 () { + HashBase$1.call(this, 64); - Hash$1.call(this, 128, 112); + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; } - inherits$a(Sha384, SHA512$2); + inherits$f(MD5$2, HashBase$1); - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - return this - }; + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - Sha384.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(48); + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - return H + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; }; - var sha384 = Sha384; - - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - return new Algorithm() + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer }; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; - - var sha$3 = sha_js.exports; - - var inherits$8; - if (typeof Object.create === 'function'){ - inherits$8 = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$8 = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) } - var inherits$9 = inherits$8; - - var formatRegExp = /%[sdj%]/g; - function format(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; + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 } - // 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 } - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } - /** - * 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 - _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); + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 } - // 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' - }; + var md5_js = MD5$2; + var Buffer$e = buffer.Buffer; + var inherits$e = inherits_browser.exports; + var HashBase = hashBase; - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + var ARRAY16 = new Array(16); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } + var zl = [ + 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 zr = [ + 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 + ]; - function stylizeNoColor(str, styleType) { - return str; - } + var sl = [ + 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 sr = [ + 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 + ]; - function arrayToHash(array) { - var hash = {}; + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - array.forEach(function(val, idx) { - hash[val] = true; - }); + function RIPEMD160$3 () { + HashBase.call(this, 64); - return hash; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; } + inherits$e(RIPEMD160$3, HashBase); - 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 !== 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; - } + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } - // 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); - } + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - // 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); - } + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; } - var base = '', array = false, braces = ['{', '}']; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - ctx.seen.push(value); + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } - 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); - }); - } + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } - ctx.seen.pop(); + var ripemd160$2 = RIPEMD160$3; - return reduceToSingleString(output, base, braces); - } + var sha_js = {exports: {}}; + var Buffer$d = safeBuffer.exports.Buffer; - 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'); + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; } + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - 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)); + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; } - }); - return output; - } + accum += remainder; + offset += remainder; - 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 ((accum % blockSize) === 0) { + this._update(block); } } - 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'); - } + + this._len += length; + return this + }; + + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; + + this._block[rem] = 0x80; + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); + + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); } - return name + ': ' + str; - } + var bits = this._len * 8; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + this._update(this._block); + var hash = this._hash(); + return enc ? hash.toString(enc) : hash + }; - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - function isBoolean(arg) { - return typeof arg === 'boolean'; - } + var hash$3 = Hash$7; - function isNull(arg) { - return arg === null; - } + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - function isNumber(arg) { - return typeof arg === 'number'; - } + var inherits$d = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - function isString(arg) { - return typeof arg === 'string'; - } + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - function isUndefined(arg) { - return arg === void 0; - } + var W$5 = new Array(80); - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } + function Sha () { + this.init(); + this._w = W$5; - function isObject(arg) { - return typeof arg === 'object' && arg !== null; + Hash$6.call(this, 64, 56); } - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } + inherits$d(Sha, Hash$6); - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) } - function isFunction(arg) { - return typeof arg === 'function'; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) } - function objectToString(o) { - return Object.prototype.toString.call(o); + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + Sha.prototype._update = function (M) { + var W = this._w; - 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 a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; + return H }; - var string_decoder = {}; + var sha$4 = Sha; - var StringDecoder_1; - // 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. + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - var Buffer$7 = buffer.Buffer; + var inherits$c = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - var isBufferEncoding = Buffer$7.isEncoding - || function(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; - } - }; + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + var W$4 = new Array(80); - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); } - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + inherits$c(Sha1, Hash$5); - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$7(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this }; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$1.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + Sha1.prototype._update = function (M) { + var W = this._w; - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; } - charStr += buffer.toString(this.encoding, 0, end); + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - // or just emit the charStr - return charStr; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H }; - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + var sha1$1 = Sha1; - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - // See http://en.wikipedia.org/wiki/UTF-8#Description + var inherits$b = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + var K$2 = [ + 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 + ]; - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + var W$3 = new Array(64); - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + function Sha256$1 () { + this.init(); - StringDecoder$1.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + this._w = W$3; // new Array(64) - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + Hash$4.call(this, 64, 56); + } - return res; + inherits$b(Sha256$1, Hash$4); + + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; + + return this }; - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); + function ch (x, y, z) { + return z ^ (x & (y ^ z)) } - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) } - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } - Readable.ReadableState = ReadableState; - - var debug$8 = debuglog('stream'); - inherits$9(Readable, EventEmitter$1); - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } - function ReadableState(options, stream) { - options = options || {}; + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + Sha256$1.prototype._update = function (M) { + var W = this._w; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + return H + }; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + var sha256$2 = Sha256$1; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - if (!(this instanceof Readable)) return new Readable(options); + var inherits$a = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - this._readableState = new ReadableState(options, this); + var W$2 = new Array(64); - // legacy - this.readable = true; + function Sha224 () { + this.init(); - if (options && typeof options.read === 'function') this._read = options.read; + this._w = W$2; // new Array(64) - EventEmitter$1.call(this); + Hash$3.call(this, 64, 56); } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; + inherits$a(Sha224, Sha256); - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$m.from(chunk, encoding); - encoding = ''; - } - } + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - return readableAddChunk(this, state, chunk, encoding, false); + return this }; - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H }; - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + var sha224 = Sha224; - if (!addToFront) state.reading = false; + var inherits$9 = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + var K$1 = [ + 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 + ]; - if (state.needReadable) emitReadable(stream); - } - } + var W$1 = new Array(160); - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } + function Sha512 () { + this.init(); + this._w = W$1; - return needMoreData(state); + Hash$2.call(this, 128, 112); } - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } + inherits$9(Sha512, Hash$2); - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this }; - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; + function maj (x, y, z) { + return (x & y) | (z & (x | y)) } - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function (n) { - debug$8('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - if (n !== 0) state.emittedReadable = false; + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$8('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - n = howMuchToRead(n, state); + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$8('need readable', doRead); + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$8('length less than watermark', doRead); - } + Sha512.prototype._update = function (M) { + var W = this._w; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$8('reading or ended', doRead); - } else if (doRead) { - debug$8('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - if (ret !== null) this.emit('data', ret); + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - return ret; - }; + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - function chunkInvalid(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } + W[i] = Wih; + W[i + 1] = Wil; } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$8('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); - } - } + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - function emitReadable_(stream) { - debug$8('emit readable'); - stream.emit('readable'); - flow(stream); - } + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } - } + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$8('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; - } + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; } - state.pipesCount += 1; - debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false); + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + }; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$8('onunpipe'); - if (readable === src) { - cleanup(); - } - } + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - function onend() { - debug$8('onend'); - dest.end(); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug$8('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - cleanedUp = true; + return H + }; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + var sha512 = Sha512; - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$8('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$8('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + var inherits$8 = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$8('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } + var W = new Array(160); - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + function Sha384 () { + this.init(); + this._w = W; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$8('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + Hash$1.call(this, 128, 112); + } - function unpipe() { - debug$8('unpipe'); - src.unpipe(dest); - } + inherits$8(Sha384, SHA512$2); - // tell the dest that it's being piped to - dest.emit('pipe', src); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$8('pipe resume'); - src.resume(); - } + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - return dest; + return this }; - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug$8('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } + return H + }; - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; + var sha384 = Sha384; - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - dest.emit('unpipe', this); + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - return this; + return new Algorithm() }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; + var sha$3 = sha_js.exports; - function nReadingNextTick(self) { - debug$8('readable nexttick read 0'); - self.read(0); - } + var Buffer$6 = safeBuffer.exports.Buffer; + var Transform = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; + var inherits$7 = inherits_browser.exports; - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$8('resume'); - state.flowing = true; - resume(this, state); + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; } - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + if (this._final) { + this.__final = this._final; + this._final = null; } + this._decoder = null; + this._encoding = null; } + inherits$7(CipherBase, Transform); - function resume_(stream, state) { - if (!state.reading) { - debug$8('resume read 0'); - stream.read(0); + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer$6.from(data, inputEnc); } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } + var outData = this._update(data); + if (this.hashMode) return this - Readable.prototype.pause = function () { - debug$8('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$8('pause'); - this._readableState.flowing = false; - this.emit('pause'); + if (outputEnc) { + outData = this._toString(outData, outputEnc); } - return this; + + return outData }; - function flow(stream) { - var state = stream._readableState; - debug$8('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} - } + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; - var self = this; - stream.on('end', function () { - debug$8('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; - self.push(null); - }); + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); + } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } - stream.on('data', function (chunk) { - debug$8('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer$6.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + if (this._encoding !== enc) throw new Error('can\'t switch encodings') - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); } - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + return out + }; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$8('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + var cipherBase = CipherBase; - return self; + var inherits$6 = inherits_browser.exports; + var MD5$1 = md5_js; + var RIPEMD160$2 = ripemd160$2; + var sha$2 = sha_js.exports; + var Base$5 = cipherBase; + + function Hash (hash) { + Base$5.call(this, 'digest'); + + this._hash = hash; + } + + inherits$6(Hash, Base$5); + + Hash.prototype._update = function (data) { + this._hash.update(data); }; - // exposed for testing purposes only. - Readable._fromList = fromList; + Hash.prototype._final = function () { + return this._hash.digest() + }; - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + var browser$3 = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5$1() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + return new Hash(sha$2(alg)) + }; - return ret; - } + var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser$3 + }, [browser$3])); - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; } - return ret; - } - - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; } - break; + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; } - ++c; + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str } - list.length -= c; - return ret; - } - - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$m.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; } - break; + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; } - ++c; + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; + } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode } - list.length -= c; - return ret; } + var src$2 = base$2; - function endReadable(stream) { - var state = stream._readableState; + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + var bs58 = basex(ALPHABET$1); - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } + var base58 = bs58; + var Buffer$5 = safeBuffer.exports.Buffer; - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + return base58.encode(Buffer$5.concat([ + payload, + checksum + ], payload.length + 4)) } - } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$9(Writable, events.exports.EventEmitter); + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return - function nop() {} + return payload + } - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; + return decodeRaw(buffer) + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } + }; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var createHash$2 = browser$3; + var bs58checkBase = base$1; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() + } - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + var bs58check$5 = bs58checkBase(sha256x2); - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + function pathElementsToBuffer(paths) { + var buffer = Buffer$k.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } - // a flag to see when we're in the middle of a write. - this.writing = false; + var src$1 = {}; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var src = {}; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var bip32$1 = {}; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + var crypto$5 = {}; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + var inherits$5 = inherits_browser.exports; + var Buffer$4 = safeBuffer.exports.Buffer; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var Base$4 = cipherBase; - // the amount that is being written when _write is called. - this.writelen = 0; + var ZEROS$1 = Buffer$4.alloc(128); + var blocksize = 64; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + function Hmac$2 (alg, key) { + Base$4.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$4.from(key); + } - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + this._alg = alg; + this._key = key; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + if (key.length > blocksize) { + key = alg(key); + } else if (key.length < blocksize) { + key = Buffer$4.concat([key, ZEROS$1], blocksize); + } - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); + var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - // count buffered requests - this.bufferedRequestCount = 0; + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + this._hash = [ipad]; } - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable(options) { - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + inherits$5(Hmac$2, Base$4); - this._writableState = new WritableState(options, this); + Hmac$2.prototype._update = function (data) { + this._hash.push(data); + }; - // legacy. - this.writable = true; + Hmac$2.prototype._final = function () { + var h = this._alg(Buffer$4.concat(this._hash)); + return this._alg(Buffer$4.concat([this._opad, h])) + }; + var legacy = Hmac$2; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + var MD5 = md5_js; - if (typeof options.writev === 'function') this._writev = options.writev; - } + var md5$1 = function (buffer) { + return new MD5().update(buffer).digest() + }; - events.exports.EventEmitter.call(this); - } + var inherits$4 = inherits_browser.exports; + var Legacy = legacy; + var Base$3 = cipherBase; + var Buffer$3 = safeBuffer.exports.Buffer; + var md5 = md5$1; + var RIPEMD160$1 = ripemd160$2; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + var sha$1 = sha_js.exports; - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } + var ZEROS = Buffer$3.alloc(128); - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; + function Hmac$1 (alg, key) { + Base$3.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$3.from(key); } - return valid; - } - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + this._alg = alg; + this._key = key; + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + key = hash.update(key).digest(); + } else if (key.length < blocksize) { + key = Buffer$3.concat([key, ZEROS], blocksize); } - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; + var ipad = this._ipad = Buffer$3.allocUnsafe(blocksize); + var opad = this._opad = Buffer$3.allocUnsafe(blocksize); - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; } + this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + this._hash.update(ipad); + } - return ret; - }; - - Writable.prototype.cork = function () { - var state = this._writableState; + inherits$4(Hmac$1, Base$3); - state.corked++; + Hmac$1.prototype._update = function (data) { + this._hash.update(data); }; - Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } + Hmac$1.prototype._final = function () { + var h = this._hash.digest(); + var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); + return hash.update(this._opad).update(h).digest() }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; + var browser$2 = function createHmac (alg, key) { + alg = alg.toLowerCase(); + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac$1('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac$1(alg, key) }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); - } - return chunk; + Object.defineProperty(crypto$5, "__esModule", { value: true }); + const createHash$1 = browser$3; + const createHmac$1 = browser$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } } + crypto$5.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$5.hmacSHA512 = hmacSHA512; - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; + var bn$1 = {exports: {}}; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + (function (module) { + (function (module, exports) { - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); } - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + // 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; + } - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + // BN - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + this.negative = 0; + this.words = null; + this.length = 0; - onwriteStateUpdate(state); + // Reduction context + this.red = null; - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); + this._init(number || 0, base || 10, endian || 'be'); } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; } else { - afterWrite(stream, state, finished, cb); - } + Buffer = require('buffer').Buffer; + } + } catch (e) { } - } - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); } - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + if (base === 'hex') { + base = 16; } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + assert(base === (base | 0) && base >= 2 && base <= 36); - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; } - if (entry === null) state.lastBufferedRequest = null; - } + 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); + } + } + } + }; - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + 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; + } - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + if (endian !== 'le') return; - Writable.prototype._writev = null; + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; + 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; + } - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + 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; + } - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } + 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 finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); + 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 { - prefinish(stream, state); + return (c - 48) & 0xf; } } - return need; - } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; } - state.ended = true; - stream.writable = false; - } - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + 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; + } - this.next = null; - this.entry = null; + // 24-bits chunks + var off = 0; + var j = 0; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; + 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 { - state.corkedRequestsFree = _this; + 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(); }; - } - inherits$9(Duplex, Readable); + 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; - var keys = Object.keys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + r *= mul; - Readable.call(this, options); - Writable.call(this, options); + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - if (options && options.readable === false) this.readable = false; + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - if (options && options.writable === false) this.writable = false; + // '0' - '9' + } else { + r += c; + } + } + return r; + } - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - this.once('end', onend); - } + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - function onEndNT(self) { - self.end(); - } + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - // a transform stream is a readable/writable stream where you do - inherits$9(Transform$1, Duplex); + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; + for (i = 0; i < mod; i++) { + pow *= base; + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + this.strip(); + }; - var cb = ts.writecb; + 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; + }; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - ts.writechunk = null; - ts.writecb = null; + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; - if (data !== null && data !== undefined) stream.push(data); + // 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(); + }; - cb(er); + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform$1(options) { - if (!(this instanceof Transform$1)) return new Transform$1(options); + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - Duplex.call(this, options); + /* - this._transformState = new TransformState(this); + var zeros = []; + var groupSizes = []; + var groupBases = []; - // when the writable side finishes, then flush out anything remaining. - var stream = this; + 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; + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + */ - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + 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' + ]; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + 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 + ]; - if (typeof options.flush === 'function') this._flush = options.flush; - } + 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 + ]; - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); - } + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; - Transform$1.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + 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; + } - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$1.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + 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); - Transform$1.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; + 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; + } - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$1.prototype._read = function (n) { - var ts = this._transformState; + assert(false, 'Base should be between 2 and 36'); + }; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; + 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; + }; - function done(stream, er) { - if (er) return stream.emit('error', er); + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + 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'); - return stream.push(null); - } + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); - inherits$9(PassThrough, Transform$1); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } - Transform$1.call(this, options); - } + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - inherits$9(Stream, EventEmitter$1); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform$1; - Stream.PassThrough = PassThrough; + res[i] = b; + } - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; + for (; i < reqLength; i++) { + res[i] = 0; + } + } - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + return res; + }; - function Stream() { - EventEmitter$1.call(this); - } + 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; + }; + } - Stream.prototype.pipe = function(dest, options) { - var source = this; + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } + 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; + }; - source.on('data', ondata); + // 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 ondrain() { - if (source.readable && source.resume) { - source.resume(); + 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; } - dest.on('drain', ondrain); + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } + 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; + }; - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - dest.end(); - } + 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(); + }; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - if (typeof dest.destroy === 'function') dest.destroy(); - } + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; } - } - source.on('error', onerror); - dest.on('error', onerror); + return this; + }; - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - source.removeListener('end', onend); - source.removeListener('close', onclose); + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + return this.strip(); + }; - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - dest.removeListener('close', cleanup); - } + // 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); + }; - source.on('end', cleanup); - source.on('close', cleanup); + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - dest.on('close', cleanup); + // 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; + } - dest.emit('pipe', source); + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + this.length = b.length; - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream, - Readable: Readable, - Writable: Writable, - Duplex: Duplex, - Transform: Transform$1, - PassThrough: PassThrough, - Stream: Stream - }); + return this.strip(); + }; - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; - var Buffer$6 = safeBuffer.exports.Buffer; - var Transform = require$$1.Transform; - var StringDecoder = string_decoder.StringDecoder; - var inherits$7 = inherits_browser.exports; + // 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); + }; - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$7(CipherBase, Transform); + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$6.from(data, inputEnc); - } + // 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; + } - var outData = this._update(data); - if (this.hashMode) return this + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - return outData - }; + this.length = a.length; - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; + return this.strip(); + }; - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; + // 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); + }; - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer$6.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - if (this._encoding !== enc) throw new Error('can\'t switch encodings') + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } + if (bitsLeft > 0) { + bytesNeeded--; + } - return out - }; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - var cipherBase = CipherBase; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - var inherits$6 = inherits_browser.exports; - var MD5$1 = md5_js; - var RIPEMD160$2 = ripemd160$2; - var sha$2 = sha_js.exports; - var Base$5 = cipherBase; + // And remove leading zeroes + return this.strip(); + }; - function Hash (hash) { - Base$5.call(this, 'digest'); + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - this._hash = hash; - } + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - inherits$6(Hash, Base$5); + var off = (bit / 26) | 0; + var wbit = bit % 26; - Hash.prototype._update = function (data) { - this._hash.update(data); - }; + this._expand(off + 1); - Hash.prototype._final = function () { - return this._hash.digest() - }; + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - var browser$3 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5$1() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() + return this.strip(); + }; - return new Hash(sha$2(alg)) - }; + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; - var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser$3 - }, [browser$3])); + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; - } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; + + 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; } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str - } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; + + 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]; } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; - } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } - } - var src$2 = base$2; - - var basex = src$2; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - - var bs58 = basex(ALPHABET$1); - - var base58 = bs58; - var Buffer$5 = safeBuffer.exports.Buffer; - - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); - - return base58.encode(Buffer$5.concat([ - payload, - checksum - ], payload.length + 4)) - } - - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); - - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return - - return payload - } - - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return - - return decodeRaw(buffer) - } - - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload - } - - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } - }; - var createHash$2 = browser$3; - var bs58checkBase = base$1; - - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$2('sha256').update(buffer).digest(); - return createHash$2('sha256').update(tmp).digest() - } - - var bs58check$5 = bs58checkBase(sha256x2); + return this; + }; - function pathElementsToBuffer(paths) { - var buffer = Buffer$m.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; - } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); - } + // 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; } - return []; - } - - var src$1 = {}; - - var src = {}; - - var bip32$1 = {}; - - var crypto$5 = {}; - - var inherits$5 = inherits_browser.exports; - var Buffer$4 = safeBuffer.exports.Buffer; - - var Base$4 = cipherBase; - - var ZEROS$1 = Buffer$4.alloc(128); - var blocksize = 64; - - function Hmac$2 (alg, key) { - Base$4.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$4.from(key); - } - - this._alg = alg; - this._key = key; - - if (key.length > blocksize) { - key = alg(key); - } else if (key.length < blocksize) { - key = Buffer$4.concat([key, ZEROS$1], blocksize); - } - - var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); - var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; - } - - this._hash = [ipad]; - } - - inherits$5(Hmac$2, Base$4); - - Hmac$2.prototype._update = function (data) { - this._hash.push(data); - }; - Hmac$2.prototype._final = function () { - var h = this._alg(Buffer$4.concat(this._hash)); - return this._alg(Buffer$4.concat([this._opad, h])) - }; - var legacy = Hmac$2; - - var MD5 = md5_js; - - var md5$1 = function (buffer) { - return new MD5().update(buffer).digest() - }; - - var inherits$4 = inherits_browser.exports; - var Legacy = legacy; - var Base$3 = cipherBase; - var Buffer$3 = safeBuffer.exports.Buffer; - var md5 = md5$1; - var RIPEMD160$1 = ripemd160$2; - - var sha$1 = sha_js.exports; - - var ZEROS = Buffer$3.alloc(128); - - function Hmac$1 (alg, key) { - Base$3.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$3.from(key); - } - - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; - - this._alg = alg; - this._key = key; - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - key = hash.update(key).digest(); - } else if (key.length < blocksize) { - key = Buffer$3.concat([key, ZEROS], blocksize); - } - - var ipad = this._ipad = Buffer$3.allocUnsafe(blocksize); - var opad = this._opad = Buffer$3.allocUnsafe(blocksize); - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; - } - this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - this._hash.update(ipad); - } - - inherits$4(Hmac$1, Base$3); - - Hmac$1.prototype._update = function (data) { - this._hash.update(data); - }; + if (this.length > num.length) return this.clone().iadd(num); - Hmac$1.prototype._final = function () { - var h = this._hash.digest(); - var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); - return hash.update(this._opad).update(h).digest() - }; + return num.clone().iadd(this); + }; - var browser$2 = function createHmac (alg, key) { - alg = alg.toLowerCase(); - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac$1('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac$1(alg, key) - }; + // 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(); - Object.defineProperty(crypto$5, "__esModule", { value: true }); - const createHash$1 = browser$3; - const createHmac$1 = browser$2; - function hash160$2(buffer) { - const sha256Hash = createHash$1('sha256') - .update(buffer) - .digest(); - try { - return createHash$1('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$1('ripemd160') - .update(sha256Hash) - .digest(); + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); } - } - crypto$5.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); - } - crypto$5.hmacSHA512 = hmacSHA512; - - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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 + // At this point both numbers are positive + var cmp = this.cmp(num); - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; } - this.negative = 0; - this.words = null; - this.length = 0; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - // Reduction context - this.red = null; + 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; + } - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; + // 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._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 = require('buffer').Buffer; - } - } catch (e) { - } + this.length = Math.max(this.length, i); - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; + if (a !== this) { + this.negative = 1; } - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + return this.strip(); }; - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); }; - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + 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; - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + // 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; - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - if (base === 'hex') { - base = 16; + 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; } - 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; - } - } + if (carry !== 0) { + out.words[k] = carry | 0; } 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; + out.length--; } - 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; + return out.strip(); } - */ - - 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); - }; + // 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; - 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); + 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; + }; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - res[reqLength - i - 1] = b; + 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 { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + out.length--; + } - res[i] = b; - } + return out.strip(); + } - for (; i < reqLength; i++) { - res[i] = 0; - } + 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; }; - 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; - }; - } + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + function FFTM (x, y) { + this.x = x; + this.y = y; + } - 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; + 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); } - if ((t & 0x1) === 0) { - r++; + + 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 r; + + return rb; }; - // 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; + // 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]]; + } }; - function toBitArray (num) { - var w = new Array(num.bitLength()); + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - return w; - } + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - 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; - }; + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + var rx = rtwdf_ * ro - itwdf_ * io; - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + 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; + } + } + } } - return this.clone(); }; - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + 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 this.clone(); - }; - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; + return 1 << i + 1 + odd; }; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); + 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; + } }; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; + 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 this; + return ws; }; - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; + 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; } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; } - return this.strip(); + assert(carry === 0); + assert((carry & ~0x1fff) === 0); }; - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } - // 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); + return ph; }; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); - // 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; - } + var rbt = this.makeRBT(N); - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + 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.length = b.length; + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); - return this.strip(); + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); }; - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); + // 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); }; - // 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); + // 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); }; - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, 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; - } + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + // 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 (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - this.length = a.length; - - return this.strip(); + return this; }; - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); + BN.prototype.muln = function muln (num) { + return this.clone().imuln(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); + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); }; - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); }; - // 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); + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); - if (bitsLeft > 0) { - bytesNeeded--; + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; } - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + res = res.mul(q); + } } - // And remove leading zeroes - return this.strip(); + return res; }; - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + // 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; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + if (r !== 0) { + var carry = 0; - var off = (bit / 26) | 0; - var wbit = bit % 26; + 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); + } - this._expand(off + 1); + if (carry) { + this.words[i] = carry; + this.length++; + } + } - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); + 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(); }; - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + // 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; + } - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); + 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; } - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; + if (s === 0) ; else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } } else { - a = num; - b = this; + this.words[0] = 0; + this.length = 1; } 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 (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; } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; } - 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]; - } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; } - return this; + return this.strip(); }; - // 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; + 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 (this.length > num.length) return this.clone().iadd(num); + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); - return num.clone().iadd(this); + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); }; - // 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(); + // 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 - num = -(this + num) - } else if (this.negative !== 0) { this.negative = 0; - this.iadd(num); + this.isubn(num); this.negative = 1; - return this._normSign(); + return this; } - // At this point both numbers are positive - var cmp = this.cmp(num); + // Add without checks + return this._iaddn(num); + }; - // Optimization - zeroify - if (cmp === 0) { + 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.length = 1; - this.words[0] = 0; + this.iaddn(num); + this.negative = 1; return this; } - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; } else { - a = num; - b = this; + // 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 (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; + 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; } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; } - this.length = Math.max(this.length, i); + if (carry === 0) return this.strip(); - if (a !== this) { - this.negative = 1; + // 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(); }; - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; - 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; + var a = this.clone(); + var b = num; - // 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; + // 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; + } - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + // Initialize quotient + var m = a.length - b.length; + var q; - 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; + 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; } - out.words[k] = rword | 0; - carry = ncarry | 0; } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } } - return out.strip(); - } + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); - // 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; + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - 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++; + 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(); } - return out; + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; }; - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } + // 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()); - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; + 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; - 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; + 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; + } - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + return this.strip(); + }; - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + 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); } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; } - if (carry !== 0) { - out.words[k] = carry; + + 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 { - out.length--; + a = a.clone(); } - return out.strip(); - } + var x1 = new BN(1); + var x2 = new BN(0); - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } + 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); + } + } - 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); + if (a.cmpn(1) === 0) { + res = x1; } else { - res = jumboMulTo(this, num, out); + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); } return res; }; - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); - function FFTM (x, y) { - this.x = x; - this.y = y; - } + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; - 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); + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); } - return t; + 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); }; - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; + 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; } - return rb; + // 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; }; - // 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]]; + 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; }; - 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; + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; - var rx = rtwdf_ * ro - itwdf_ * io; + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; - rtws[p + j] = re + ro; - itws[p + j] = ie + io; + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; }; - 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++; - } + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; - return 1 << i + 1 + odd; + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); }; - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; + 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); + }; - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; - t = iws[i]; + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); }; - 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; + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - ws[i] = w & 0x3ffffff; + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - return ws; + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); }; - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); + 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); + }; - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } + 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); + }; - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; - assert(carry === 0); - assert((carry & ~0x1fff) === 0); + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); }; - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } + // 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); + }; - return ph; + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); }; - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); + // 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); + }; - var rbt = this.makeRBT(N); + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; - var _ = this.stub(N); + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); + // 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); - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + this.tmp = this._tmp(); + } - var rmws = out.words; - rmws.length = N; + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); + 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; - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); - 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; + 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(); + } } - 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(); + return r; }; - // 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); + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, 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); + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); }; - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - // 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; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; } + output.length = outLen; - if (carry !== 0) { - this.words[i] = carry; - this.length++; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; } - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); + 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; + } }; - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; + // 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); } - 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); + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; } } - - return res; + return num; }; - // 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; + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); - if (r !== 0) { - var carry = 0; + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); - 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); - } + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); - if (carry) { - this.words[i] = carry; - this.length++; - } + 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; + }; - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; - for (i = 0; i < s; i++) { - this.words[i] = 0; - } + 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; - this.length += s; + 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; } + } - return this.strip(); + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); }; - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); + 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'); }; - // 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; + 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(); } - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; + return this.m.sub(a)._forceRed(this); + }; - h -= s; - h = Math.max(0, h); + Red.prototype.add = function add (a, b) { + this._verify2(a, b); - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); } + return res._forceRed(this); + }; - if (s === 0) ; 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; - } + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); - 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; + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); } + return res; + }; - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); } - - return this.strip(); + return res._forceRed(this); }; - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; }; - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); }; - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); }; - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); }; - // 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]; + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; - return !!(w & q); + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); }; - // 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; + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); - assert(this.negative === 0, 'imaskn works only with positive numbers'); + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); - if (this.length <= s) { - return this; + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); } - if (r !== 0) { + // 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); } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + assert(!q.isZero()); - return this.strip(); - }; + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + // 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); - // 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); + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - // 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; + 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)); - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; } - // Add without checks - return this._iaddn(num); + return r; }; - 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]++; - } + 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); } - 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); + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; + 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); } - this.words[0] -= num; + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - 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; + 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 this.strip(); + return res; }; - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); + return r === num ? r.clone() : r; }; - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; }; - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + // + // Montgomery method engine + // - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + BN.mont = function mont (num) { + return new Mont(num); + }; - this._expand(len); + function Mont (m) { + Red.call(this, m); - 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; + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); } - if (carry === 0) return this.strip(); + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - // 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; + 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); - return this.strip(); + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); }; - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - // 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; + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; } - // 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 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; - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); } - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + return res._forceRed(this); + }; - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - 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(); + 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); } - a.strip(); - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } + return res._forceRed(this); + }; - return { - div: q || null, - mod: a - }; + 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); }; + })(module, commonjsGlobal); + }(bn$1)); - // 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()); + var elliptic = {}; - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } + var name = "elliptic"; + var version = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0$1 = { + name: name, + version: version, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); + var utils$n = {}; - if (mode !== 'mod') { - div = res.div.neg(); - } + var bn = {exports: {}}; - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } + (function (module) { + (function (module, exports) { - return { - div: div, - mod: mod - }; - } + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + // 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; + } - if (mode !== 'mod') { - div = res.div.neg(); - } + // BN - return { - div: div, - mod: res.mod - }; + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + this.negative = 0; + this.words = null; + this.length = 0; - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; } - return { - div: res.div, - mod: mod - }; + this._init(number || 0, base || 10, endian || 'be'); } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - // Both numbers are positive at this point + BN.BN = BN; + BN.wordSize = 26; - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; } + } catch (e) { + } - // 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])) - }; + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; } - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; }; - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; }; - // 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; + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(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.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; + 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; } - return acc; + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); }; - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); + 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; + } - 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.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(); }; - 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); + 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 { - x = x.clone(); + return (c - 48) & 0xf; } + } - // 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; + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; } + return r; + } - var yp = y.clone(); - var xp = x.clone(); + 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; + } - 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); - } + // 24-bits chunks + var off = 0; + var j = 0; - A.iushrn(1); - B.iushrn(1); + 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; } } - - 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); + } 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; } } - - 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.strip(); }; - // 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); - } + 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; - x1.iushrn(1); - } - } + r *= mul; - 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); - } + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - x2.iushrn(1); - } - } + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); + // '0' - '9' } else { - b.isub(a); - x2.isub(x1); + r += c; } } + return r; + } - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - if (res.cmpn(0) < 0) { - res.iadd(p); + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; } + limbLen--; + limbPow = (limbPow / base) | 0; - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - 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; + for (i = 0; i < mod; i++) { + pow *= base; } - a.isub(b); - } while (true); - - return b.iushln(shift); - }; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); + this.strip(); }; - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; + 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.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; }; - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; }; - // 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; + // 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(); + }; - // 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++; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; } return this; }; - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; + BN.prototype.inspect = function inspect () { + return (this.red ? ''; }; - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + /* - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + var zeros = []; + var groupSizes = []; + var groupBases = []; - this.strip(); + 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 res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } + */ - assert(num <= 0x3ffffff, 'Number is too big'); + 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 w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; + 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 + ]; - // 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 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 + ]; - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; - // 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 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; + } - 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 (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 (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } } - break; + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - return res; - }; - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; + assert(false, 'Base should be between 2 and 36'); }; - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; + 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.gten = function gten (num) { - return this.cmpn(num) >= 0; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); }; - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); }; - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); }; - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; + 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'); - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + res[i] = b; + } - 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); - }; + for (; i < reqLength; i++) { + res[i] = 0; + } + } - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); + return res; }; - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; + 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.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); + 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; }; - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); + // 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; }; - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + function toBitArray (num) { + var w = new Array(num.bitLength()); - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } - 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); - }; + return w; + } - 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); - }; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); + 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.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); }; - // 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.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); }; - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); }; - // 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.isNeg = function isNeg () { + return this.negative !== 0; }; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); }; - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; }; - // 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); + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - this.tmp = this._tmp(); - } + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; + return this.strip(); }; - 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; + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + // 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); + }; - 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); + 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 { - if (r.strip !== undefined) { - // r is BN v4 instance - r.strip(); - } else { - // r is BN v5 instance - r._strip(); - } + b = this; } - return r; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); }; - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); }; - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); + // 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); }; - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; + // 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; + } - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; } - output.length = outLen; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } } - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + this.length = a.length; - 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; - } + return this.strip(); }; - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - // 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); - } + // 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); + }; - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); }; - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - 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; + if (bitsLeft > 0) { + bytesNeeded--; + } - num.words[i] = lo; - carry = hi; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; } - if (carry !== 0) { - num.words[num.length++] = carry; + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } - return num; + + // And remove leading zeroes + return this.strip(); }; - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - 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(); + // 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 { - throw new Error('Unknown prime ' + name); + this.words[off] = this.words[off] & ~(1 << wbit); } - primes[name] = prime; - return prime; + return this.strip(); }; - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; + // 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 { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; + a = num; + b = this; } - } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + 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; + } - 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'); - }; + 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]; + } + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); + return this; }; - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); + // 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; } - return this.m.sub(a)._forceRed(this); + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); }; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + // 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(); - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); } - return res._forceRed(this); - }; - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + // At this point both numbers are positive + var cmp = this.cmp(num); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; } - return res; - }; - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + 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; } - return res._forceRed(this); - }; - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; } - return res; - }; - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); + return this.strip(); }; - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); }; - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + 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; - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + // 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; - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + 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--; + } - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + 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; - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); + 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; + }; - // 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()); + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - // 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); + 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; - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; - 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(); + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; } - 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; + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; } - - 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(); + if (carry !== 0) { + out.words[k] = carry; } 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; + out.length--; } - 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; - } + return out.strip(); + } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; + 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; }; - 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); + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - 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); + function FFTM (x, y) { + this.x = x; + this.y = y; } - 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); + 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 res._forceRed(this); + return t; }; - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; - 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); + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; } - 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); + return rb; }; - })(module, commonjsGlobal); - }(bn)); - - var elliptic = {}; - - var name = "elliptic"; - var version = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0$1 = { - name: name, - version: version, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; - - var utils$n = {}; - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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); + // 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]]; } - } - 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; - }; - }(utils$m)); + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - (function (exports) { + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - utils.assert = minAssert; - utils.toArray = minUtils.toArray; - utils.zero2 = minUtils.zero2; - utils.toHex = minUtils.toHex; - utils.encode = minUtils.encode; + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - // 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); + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - var ws = 1 << (w + 1); - var k = num.clone(); + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; - 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; - } + var rx = rtwdf_ * ro - itwdf_ * io; - naf[i] = z; - k.iushrn(1); - } + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; - return naf; - } - utils.getNAF = getNAF; + rtws[p + j] = re + ro; + itws[p + j] = ie + io; - // Represent k1, k2 in a Joint Sparse Form - function getJSF(k1, k2) { - var jsf = [ - [], - [], - ]; + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; - 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; + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } } - 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; + 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++; } - 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 1 << i + 1 + odd; + }; - return jsf; - } - utils.getJSF = getJSF; + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; - 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; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; - function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; - } - utils.parseBytes = parseBytes; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; - function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); - } - utils.intFromLE = intFromLE; - }(utils$n)); + t = iws[i]; - var brorand = {exports: {}}; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; - var r$1; + 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; - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); + ws[i] = w & 0x3ffffff; - return r$1.generate(len); - }; + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } - function Rand(rand) { - this.rand = rand; - } - brorand.exports.Rand = Rand; + return ws; + }; - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; - }; + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } - 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; - }; + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; - // 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$4 = require('crypto'); - if (typeof crypto$4.randomBytes !== 'function') - throw new Error('Not supported'); + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } - Rand.prototype._rand = function _rand(n) { - return crypto$4.randomBytes(n); - }; - } catch (e) { - } - } + return ph; + }; - var curve = {}; + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; + var rbt = this.makeRBT(N); - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); + var _ = this.stub(N); - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); - // Curve configuration, optional - this.n = conf.n && new BN$8(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + var rmws = out.words; + rmws.length = N; - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); - this._bitLength = this.n ? this.n.bitLength() : 0; + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); - // 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); - } - } - var base = BaseCurve; + 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; + } - BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); - }; + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); - BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); - }; + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; - BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$e(p.precomputed); - var doubles = p._getDoubles(); + // 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); + }; - var naf = getNAF(k, 1, this._bitLength); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; + // 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); + }; - // 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); - } + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; - 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(); - }; + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); - BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; + // 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; + } - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } - // Get NAF form - var naf = getNAF(k, w, this._bitLength); + return this; + }; - // 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); + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; - if (i < 0) - break; - var z = naf[i]; - assert$e(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; - }; + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; - BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; - // 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; - } + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); - // 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; + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; } - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; - // 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()); + res = res.mul(q); + } } - 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 */ - ]; + return res; + }; - 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; + // 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; - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; + 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++; + } } - } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - var k = 0; + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } - while (i >= 0) { - var zero = true; - for (j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; + for (i = 0; i < s; i++) { + this.words[i] = 0; } - if (!zero) - break; - k++; - i--; + + this.length += s; } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - for (j = 0; j < len; j++) { - var z = tmp[j]; - 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(); + return this.strip(); + }; - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); + 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; } - } - // Zeroify references - for (i = 0; i < len; i++) - wnd[i] = null; - if (jacobianResult) - return acc; - else - return acc.toP(); - }; + 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); - function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; - } - BaseCurve.BasePoint = BasePoint; + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } - BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); - }; + if (s === 0) ; 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; + } - BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); - }; + 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; + } - BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$l.toArray(bytes, enc); + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } - var len = this.p.byteLength(); + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } - // 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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(bytes[bytes.length - 1] % 2 === 1); + return this.strip(); + }; - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; - 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'); - }; + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; - BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); - }; + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; - BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); - }; + // 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; - BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); - }; + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; - BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; + // Check bit and return + var w = this.words[s]; - var precomputed = { - doubles: null, - naf: null, - beta: null, + return !!(w & q); }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - return this; - }; + // 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; - BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; + assert(this.negative === 0, 'imaskn works only with positive numbers'); - var doubles = this.precomputed.doubles; - if (!doubles) - return false; + if (this.length <= s) { + return this; + } - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); - }; + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } - 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, + return this.strip(); }; - }; - - 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, + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); }; - }; - BasePoint.prototype._getBeta = function _getBeta() { - return null; - }; + // 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); - BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; - }; + // 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; + } - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$3 = inherits_browser.exports; - var Base$2 = base; + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } - var assert$d = utils$k.assert; + // Add without checks + return this._iaddn(num); + }; - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); + // 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); - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + return this; + }; - // 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$3(ShortCurve, Base$2); - var short = ShortCurve; + // 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); - ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN$7(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$7(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]; + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; } else { - lambda = lambdas[1]; - assert$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN$7(vec.a, 16), - b: new BN$7(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - return { - beta: beta, - lambda: lambda, - basis: basis, + return this.strip(); }; - }; - 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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; - var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; - }; + BN.prototype.iabs = function iabs () { + this.negative = 0; - ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + return this; + }; - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(1); + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; - // 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; + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; - 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)); + this._expand(len); - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + 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; } - prevR = r; - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; + if (carry === 0) return this.strip(); - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } + // 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; - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } + return this.strip(); + }; - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ]; - }; + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; - ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; + var a = this.clone(); + var b = num; - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); + // 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; + } - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); + // Initialize quotient + var m = a.length - b.length; + var q; - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; - }; + 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; + } + } - ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$7(x, 16); - if (!x.red) - x = x.toRed(this.red); + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } - 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'); + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); - // 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(); + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - return this.point(x, y); - }; + 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(); - ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } - var x = point.x; - var y = point.y; + return { + div: q || null, + mod: a + }; + }; - 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; - }; + // 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()); - 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 (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; + if (mode !== 'mod') { + div = res.div.neg(); } - 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; + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } } - return res; - }; - function Point$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); + return { + div: div, + mod: mod + }; } - 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$3(Point$2, Base$2.BasePoint); - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; + if (mode !== 'mod') { + div = res.div.neg(); + } - Point$2.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; + return { + div: div, + mod: res.mod + }; + } - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); - 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; - }; + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } - Point$2.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; + return { + div: res.div, + mod: mod + }; + } - 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), - }, - } ]; - }; + // Both numbers are positive at this point - Point$2.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; + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } - 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; - }; + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } - Point$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; + return this._wordDiv(num, mode); + }; - Point$2.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; - // P + O = P - if (p.inf) - return this; + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; - // P + P = 2P - if (this.eq(p)) - return this.dbl(); + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; - 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); - }; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - Point$2.prototype.dbl = function dbl() { - if (this.inf) - return this; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - var a = this.curve.a; + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; - 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); - }; + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } - Point$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; + return acc; + }; - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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); - }; + 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; + } - Point$2.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); - }; + return this.strip(); + }; - Point$2.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); - }; + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; - Point$2.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); - }; + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); - Point$2.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; + var x = this; + var y = p.clone(); - 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; - }; + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } - Point$2.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); - function JPoint(curve, x, y, z) { - Base$2.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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); + var g = 0; - this.zOne = this.z === this.curve.one; - } - inherits$3(JPoint, Base$2.BasePoint); + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } - ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); - }; + var yp = y.clone(); + var xp = x.clone(); - JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); + 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); + } - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); + A.iushrn(1); + B.iushrn(1); + } + } - return this.curve.point(ax, ay); - }; + 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); + } - JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }; + C.iushrn(1); + D.iushrn(1); + } + } - JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } - // P + O = P - if (p.isInfinity()) - return this; + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; - // 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)); + // 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 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 a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + var x1 = new BN(1); + var x2 = new BN(0); - 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); + var delta = b.clone(); - return this.curve.jpoint(nx, ny, nz); - }; + 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); + } - JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); + x1.iushrn(1); + } + } - // P + O = P - if (p.isInfinity()) - return this; + 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); + } - // 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); + x2.iushrn(1); + } + } - 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(); - } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - 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); + if (res.cmpn(0) < 0) { + res.iadd(p); + } - return this.curve.jpoint(nx, ny, nz); - }; + return res; + }; - JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (i = 0; i < pow; i++) - r = r.dbl(); - return r; - } + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } - // 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 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; + } - 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); + a.isub(b); + } while (true); - jx = nx; - jz = nz; - jyd = dny; - } + return b.iushln(shift); + }; - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); - }; + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; - JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); - }; + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; - 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 + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; - // 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); + // 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; - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } - // 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 + // 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; + }; - // 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(); + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; - // 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); - } + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; - return this.curve.jpoint(nx, ny, nz); - }; + this.strip(); - 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 + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - // 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 + assert(num <= 0x3ffffff, 'Number is too big'); - // 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); - } + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; - return this.curve.jpoint(nx, ny, nz); - }; + // 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; - JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); + // 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 jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; - 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); + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; - 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); + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; - JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; - // 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); + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; - return this.curve.jpoint(nx, ny, nz); - }; + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; - JPoint.prototype.mul = function mul(k, kbase) { - k = new BN$7(k, kbase); + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; - return this.curve._wnafMul(this, k); - }; + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; - JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; - if (this === p) - return true; + // + // 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; + }; - // 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; + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; - // 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; - }; + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; - 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; + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; - 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; + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; - JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; - JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + 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); + }; - var BN$6 = bn.exports; - var inherits$2 = inherits_browser.exports; - var Base$1 = base; + 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); + }; - var utils$j = utils$n; + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; - function MontCurve(conf) { - Base$1.call(this, 'mont', conf); + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); - } - inherits$2(MontCurve, Base$1); - var mont = MontCurve; + // 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); + }; - 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(); + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; - return y.redSqr().cmp(rhs) === 0; - }; + // 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); + }; - function Point$1(curve, x, z) { - Base$1.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$6(x, 16); - this.z = new BN$6(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$2(Point$1, Base$1.BasePoint); + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; + // 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); - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; + this.tmp = this._tmp(); + } - Point$1.prototype.precompute = function precompute() { - // No-op - }; + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; + 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; - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + 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(); + } + } - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; + return r; + }; - Point$1.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; - // 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); - }; + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; - Point$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); - Point$1.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - // 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); - }; + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; - Point$1.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 + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; - 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(); + 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 { - // 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(); + input.length -= 9; } - } - return b; - }; + }; - Point$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; + // 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); + } - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; - }; + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); - return this.x.fromRed(); - }; + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$1 = inherits_browser.exports; - var Base = base; + 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; - var assert$c = utils$i.assert; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; - 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; + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; - Base.call(this, 'edwards', conf); + 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; - this.a = new BN$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); + return prime; + }; - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits$1(EdwardsCurve, Base); - var edwards = EdwardsCurve; + // + // 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; + } + } - EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); - }; + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; - EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); - }; + 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'); + }; - // Just for compatibility with Short curve - EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); - }; + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; - EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN$5(x, 16); - if (!x.red) - x = x.toRed(this.red); + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } - 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)); + return this.m.sub(a)._forceRed(this); + }; - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + Red.prototype.add = function add (a, b) { + this._verify2(a, b); - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); + 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); - return this.point(x, y); - }; + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; - EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN$5(y, 16); - if (!y.red) - y = y.toRed(this.red); + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - // 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()); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; - return this.point(x, y); - }; + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; - EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; - 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))); + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; - return lhs.cmp(rhs) === 0; - }; + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); - 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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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; + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); - // 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()); + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); } - } - } - inherits$1(Point, Base.BasePoint); - EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); - }; + // 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()); - EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); - }; + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); - Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); - }; + // 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); - Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } - 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)); - }; + 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)); - Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } - // 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); - }; + return r; + }; - 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 + 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); + } + }; - // 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(); + 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 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); + 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); } - } 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; + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); - }; + 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); + } - Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - // 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); - }; + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } - // 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); - }; + return res; + }; - Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); - }; + return r === num ? r.clone() : r; + }; - Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); - }; + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; - Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); - }; + // + // Montgomery method engine + // - Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); - }; + BN.mont = function mont (num) { + return new Mont(num); + }; - Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; + function Mont (m) { + Red.call(this, m); - // 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; - }; + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } - Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); - }; + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); - }; + 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); - Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); - }; + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; - Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; - }; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - 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; + 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; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - }; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } - // Compatibility with BaseCurve - Point.prototype.toP = Point.prototype.normalize; - Point.prototype.mixedAdd = Point.prototype.add; + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - (function (exports) { + 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); + } - var curve = exports; + return res._forceRed(this); + }; - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); + 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); + }; + })(module, commonjsGlobal); + }(bn)); - var curves$2 = {}; + var minimalisticAssert = assert$f; - var hash$2 = {}; + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } - var utils$h = {}; + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; - var assert$b = minimalisticAssert; - var inherits = inherits_browser.exports; + var utils$m = {}; - utils$h.inherits = inherits; + (function (exports) { - 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; - } + var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) @@ -18899,46 +18712,39 @@ 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++) + 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$h.toArray = toArray; + utils.toArray = toArray; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils.zero2 = zero2; function toHex(msg) { var res = ''; @@ -18946,17559 +18752,16763 @@ res += zero2(msg[i].toString(16)); return res; } - utils$h.toHex = toHex; + utils.toHex = toHex; - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.htonl = htonl; + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + }(utils$m)); - 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; - } - utils$h.toHex32 = toHex32; + (function (exports) { - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils$h.zero2 = zero2; + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; - 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; - } - utils$h.zero8 = zero8; + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.join32 = join32; + // 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); - 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; + 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 { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; + z = 0; } + + naf[i] = z; + k.iushrn(1); } - return res; - } - utils$h.split32 = split32; - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); + return naf; } - utils$h.rotr32 = rotr32$1; + utils.getNAF = getNAF; - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [], + ]; - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; + 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); - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; + 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); - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; + return jsf; } - utils$h.sum32_5 = sum32_5$2; - - function sum64$1(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; + utils.getJSF = getJSF; - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; + 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$h.sum64 = sum64$1; + utils.cachedProperty = cachedProperty; - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; } - utils$h.sum64_hi = sum64_hi$1; + utils.parseBytes = parseBytes; - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); } - utils$h.sum64_lo = sum64_lo$1; + utils.intFromLE = intFromLE; + }(utils$n)); - function sum64_4_hi$1(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 brorand = {exports: {}}; - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; - } - utils$h.sum64_4_hi = sum64_4_hi$1; + var r$1; - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); - function sum64_5_hi$1(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; + return r$1.generate(len); + }; - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; + function Rand(rand) { + this.rand = rand; } - utils$h.sum64_5_hi = sum64_5_hi$1; + brorand.exports.Rand = Rand; - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; + Rand.prototype.generate = function generate(len) { + return this._rand(len); + }; - return lo >>> 0; - } - utils$h.sum64_5_lo = sum64_5_lo$1; + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); - function rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - utils$h.rotr64_hi = rotr64_hi$1; + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.rotr64_lo = rotr64_lo$1; + 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; + }; - function shr64_hi$1(ah, al, num) { - return ah >>> num; - } - utils$h.shr64_hi = shr64_hi$1; + // 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$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { + } } - utils$h.shr64_lo = shr64_lo$1; - var common$5 = {}; + var curve = {}; - var utils$g = utils$h; - var assert$a = minimalisticAssert; + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; - function BlockHash$4() { - 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'; + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; - } - common$5.BlockHash = BlockHash$4; + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; + // Curve configuration, optional + this.n = conf.n && new BN$8(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - // 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; + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); - msg = utils$g.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); + 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); } + } + var base = BaseCurve; - return this; + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); }; - BlockHash$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); - - return this._digest(enc); + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); }; - BlockHash$4.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; + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$e(p.precomputed); + var doubles = p._getDoubles(); - 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; + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; - for (t = 8; t < this.padLength; t++) - res[i++] = 0; + // 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); } - return res; + 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(); }; - var sha = {}; + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; - var common$4 = {}; + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; + // Get NAF form + var naf = getNAF(k, w, this._bitLength); - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; + // 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); - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; + if (i < 0) + break; + var z = naf[i]; + assert$e(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; + }; - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; + // 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; + } - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; + // 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; + } - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b], /* 7 */ + ]; - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; + // 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()); + } - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - common$4.g1_256 = g1_256$1; + 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 utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; + 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; - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + var k = 0; - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); + 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; - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); + for (j = 0; j < len; j++) { + var z = tmp[j]; + 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; - utils$e.inherits(SHA1, BlockHash$3); - var _1 = SHA1; + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; - SHA1.blockSize = 512; - SHA1.outSize = 160; - SHA1.hmacStrength = 80; - SHA1.padLength = 64; + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; - SHA1.prototype._update = function _update(msg, start) { - var W = this.W; + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils$l.toArray(bytes, enc); - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; + var len = this.p.byteLength(); - for(; i < W.length; i++) - W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + // 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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(bytes[bytes.length - 1] % 2 === 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]; + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; + 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); } - - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); + throw new Error('Unknown point format'); }; - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); }; - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; - - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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$2 = common$2.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 - ]; + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); - function SHA256$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$1; + return [ 0x04 ].concat(x, this.getY().toArray('be', len)); + }; - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; + BasePoint.prototype.encode = function encode(enc, compact) { + return utils$l.encode(this._encode(compact), enc); + }; - SHA256$1.prototype._update = function _update(msg, start) { - var W = this.W; + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4$1(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + 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; - 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]; + return this; + }; - assert$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; + var doubles = this.precomputed.doubles; + if (!doubles) + return false; - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); - else - return utils$d.split32(this.h, 'big'); + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); }; - var utils$c = utils$h; - var SHA256 = _256; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils$c.inherits(SHA224, SHA256); - var _224 = SHA224; + 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, + }; + }; - SHA224.blockSize = 512; - SHA224.outSize = 224; - SHA224.hmacStrength = 192; - SHA224.padLength = 64; + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; - SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); + 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, + }; }; - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; - var BlockHash$1 = common$1.BlockHash; + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; - 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 - ]; + var assert$d = utils$k.assert; - function SHA512$1() { - if (!(this instanceof SHA512$1)) - return new SHA512$1(); + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); - BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); - var _512 = SHA512$1; + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); - SHA512$1.blockSize = 1024; - SHA512$1.outSize = 512; - SHA512$1.hmacStrength = 192; - SHA512$1.padLength = 128; + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - SHA512$1.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; + // 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$3(ShortCurve, Base$2); + var short = ShortCurve; - // 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]; + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; - 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); + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN$7(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$7(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$d(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } } - }; - - SHA512$1.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]; + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN$7(vec.a, 16), + b: new BN$7(vec.b, 16), + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } - assert$8(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); - 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]; + return { + beta: beta, + lambda: lambda, + basis: basis, + }; + }; - 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); + 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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + var s = new BN$7(3).toRed(red).redNeg().redSqrt().redMul(tinv); - 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); + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; + }; - hh = gh; - hl = gl; + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - gh = fh; - gl = fl; + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(1); - fh = eh; - fl = el; + // 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; - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); + 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)); - dh = ch; - dl = cl; + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; - ch = bh; - cl = bl; + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; - bh = ah; - bl = al; + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); } - 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); + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ]; }; - SHA512$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.split32(this.h, 'big'); - }; + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; - function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; - } + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); - function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; - } + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); - function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; - } + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; - function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$7(x, 16); + if (!x.red) + x = x.toRed(this.red); - 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 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'); - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + // 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(); - 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 + return this.point(x, y); + }; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; - 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 x = point.x; + var y = point.y; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + 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; + }; - 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 + 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(); - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } - 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); + 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); - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; + // 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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - 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); + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; - 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); + Point$2.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; - } + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; - 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 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; + }; - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; - } + Point$2.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; - var utils$a = utils$h; + 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), + }, + } ]; + }; - var SHA512 = _512; + Point$2.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 SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; - } - utils$a.inherits(SHA384, SHA512); - var _384 = SHA384; + 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; + }; - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; + Point$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; }; - sha.sha1 = _1; - sha.sha224 = _224; - sha.sha256 = _256; - sha.sha384 = _384; - sha.sha512 = _512; + Point$2.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; - var ripemd = {}; + // P + O = P + if (p.inf) + return this; - var utils$9 = utils$h; - var common = common$5; + // P + P = 2P + if (this.eq(p)) + return this.dbl(); - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; - var BlockHash = common.BlockHash; + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); - function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); - BlockHash.call(this); + 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); + }; - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; - } - utils$9.inherits(RIPEMD160, BlockHash); - ripemd.ripemd160 = RIPEMD160; + Point$2.prototype.dbl = function dbl() { + if (this.inf) + return this; - RIPEMD160.blockSize = 512; - RIPEMD160.outSize = 160; - RIPEMD160.hmacStrength = 192; - RIPEMD160.padLength = 64; + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); - 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; + 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); }; - RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); - else - return utils$9.split32(this.h, 'little'); + Point$2.prototype.getX = function getX() { + return this.x.fromRed(); }; - 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)); + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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 x ^ (y | (~z)); - } + return this.curve._wnafMul(this, k); + }; - 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; + Point$2.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 0xa953fd4e; - } + return this.curve._wnafMulAdd(1, points, coeffs, 2); + }; - 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; + Point$2.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 0x00000000; - } + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); + }; - 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 - ]; + Point$2.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); + }; - 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 - ]; + Point$2.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; - 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 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; + }; - 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 - ]; + Point$2.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; - 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; + function JPoint(curve, x, y, z) { + Base$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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._init(utils$8.toArray(key, enc)); + this.zOne = this.z === this.curve.one; } - var hmac = Hmac; + inherits$3(JPoint, Base$2.BasePoint); - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(key.length <= this.blockSize); + ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); + }; - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); + JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); + return this.curve.point(ax, ay); }; - Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; + JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; - Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); - }; + JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; - (function (exports) { - var hash = exports; + // P + O = P + if (p.isInfinity()) + return this; - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha; - hash.ripemd = ripemd; - hash.hmac = hmac; + // 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)); - // 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; - }(hash$2)); + 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(); + } - (function (exports) { + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); - var curves = exports; + 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); - var hash = hash$2; - var curve$1 = curve; - var utils = utils$n; + 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 assert = utils.assert; + 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); - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; + return this.curve.jpoint(nx, ny, nz); + }; - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); - } - curves.PresetCurve = PresetCurve; + JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); - 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; - }, - }); - } + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow; i++) + r = r.dbl(); + return r; + } - 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', - ], - }); + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; - 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', - ], - }); + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); - 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', - ], - }); + // 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)); - 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', - ], - }); + 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); - 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', - ], - }); + jx = nx; + jz = nz; + jyd = dny; + } - 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', - ], - }); + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); + }; - 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', + JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658', - ], - }); + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); + }; - var pre; - try { - pre = require('./precomputed/secp256k1'); - } catch (e) { - pre = undefined; - } + 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 - 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, + // 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); - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3', - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15', - }, - ], + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre, - ], - }); - }(curves$2)); + // 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 - var hash$1 = hash$2; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; + // 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(); - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(options); - this.hash = options.hash; - this.predResist = !!options.predResist; + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; + // 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); + } - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; + return this.curve.jpoint(nx, ny, nz); + }; - var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; + 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 - HmacDRBG$1.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); + // 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 - 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; + // 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); } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 + return this.curve.jpoint(nx, ny, nz); }; - HmacDRBG$1.prototype._hmac = function hmac() { - return new hash$1.hmac(this.hash, this.K); - }; + JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; - HmacDRBG$1.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; + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); - }; + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); - HmacDRBG$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); + 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); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + 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); - this._update(entropy.concat(add || [])); - this._reseed = 1; + return this.curve.jpoint(nx, ny, nz); }; - HmacDRBG$1.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; - } + JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); - // Optional additional data - if (add) { - add = utils$7.toArray(add, addEnc || 'hex'); - this._update(add); - } + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } + // 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); - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils$7.encode(res, enc); + return this.curve.jpoint(nx, ny, nz); }; - var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; - - function KeyPair$4(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; + JPoint.prototype.mul = function mul(k, kbase) { + k = new BN$7(k, kbase); - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); - } - var key$1 = KeyPair$4; + return this.curve._wnafMul(this, k); + }; - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; + JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); - }; + if (this === p) + return true; - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; + // 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; - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); + // 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; }; - KeyPair$4.prototype.validate = function validate() { - var pub = this.getPublic(); + 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; - 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' }; + 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; - return { result: true, reason: null }; + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } }; - KeyPair$4.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } + JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); + JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; - if (!enc) - return this.pub; + var BN$6 = bn.exports; + var inherits$2 = inherits_browser.exports; + var Base$1 = base; - return this.pub.encode(enc, compact); - }; + var utils$j = utils$n; - KeyPair$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(key, enc || 16); + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$2(MontCurve, Base$1); + var mont = MontCurve; - // 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); - }; + 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(); - KeyPair$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(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); + return y.redSqr().cmp(rhs) === 0; }; - // ECDH - KeyPair$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); + function Point$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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); } - return pub.mul(this.priv).getX(); - }; + } + inherits$2(Point$1, Base$1.BasePoint); - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); }; - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); }; - KeyPair$4.prototype.inspect = function inspect() { - return ''; + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); }; - var BN$3 = bn.exports; + Point$1.prototype.precompute = function precompute() { + // No-op + }; - var utils$5 = utils$n; - var assert$4 = utils$5.assert; + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; - if (this._importDER(options, enc)) - return; + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; - function Position() { - this.place = 0; - } + Point$1.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A - function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; + // 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); + }; - // Indefinite length or overflow - if (octetLen === 0 || octetLen > 4) { - return false; - } + Point$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - val >>>= 0; - } + Point$1.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A - // Leading zeroes - if (val <= 0x7f) { - return false; - } + // 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); + }; - p.place = off; - return val; - } + Point$1.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 - 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); - } + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); - Signature$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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); + 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 { - // Leading zeroes - return false; + // 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(); } } - - this.r = new BN$3(r); - this.s = new BN$3(s); - this.recoveryParam = null; - - return true; + return b; }; - 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$3.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$5.encode(res, enc); + Point$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); }; - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; - - var KeyPair$3 = key$1; - var Signature$2 = signature$1; - - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); - - options = curves$1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.PresetCurve) - options = { curve: options }; + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; - } - var ec = EC$1; + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); + return this.x.fromRed(); }; - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); - }; + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$1 = inherits_browser.exports; + var Base = base; - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); - }; + var assert$c = utils$i.assert; - EC$1.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; + 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; - // 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(), - }); + Base.call(this, 'edwards', conf); - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN$2(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; + this.a = new BN$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$1(EdwardsCurve, Base); + var edwards = EdwardsCurve; - EC$1.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); + EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); else - return msg; + return this.a.redMul(num); }; - EC$1.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; + EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); + }; - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN$2(msg, 16)); + // Just for compatibility with Short curve + EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); + }; - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); + EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN$5(x, 16); + if (!x.red) + x = x.toRed(this.red); - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); + 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)); - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - }); + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); - // Number of bytes to generate - var ns1 = this.n.sub(new BN$2(1)); + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; + return this.point(x, y); + }; - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; + EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN$5(y, 16); + if (!y.red) + y = y.toRed(this.red); - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; + // 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()); - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); - return new Signature$2({ r: r, s: s, recoveryParam: recoveryParam }); - } + return this.point(x, y); }; - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(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; + EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; - // 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; + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); - if (!this.curve._maxwellTrick) { - p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + 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 p.getX().umod(this.n).cmp(r) === 0; - } + return lhs.cmp(rhs) === 0; + }; - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K + 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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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; - p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; + // 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$1(Point, Base.BasePoint); - // 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); + EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); }; - EC$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); + EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); + }; - var n = this.n; - var e = new BN$2(msg); - var r = signature.r; - var s = signature.s; + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); + }; - // 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'); + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; - // 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); + 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)); + }; - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); + Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); + // 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); }; - EC$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; + 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 - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } + // 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(); - if (Qprime.eq(Q)) - return i; + 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); } - throw new Error('Unable to find valid recovery factor'); + return this.curve.point(nx, ny, nz); }; - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.cachedProperty; + Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; - /** - * @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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); else - this._pubBytes = parseBytes$2(params.pub); - } - - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); + return this._projDbl(); }; - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); + 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); }; - KeyPair$2.prototype.secret = function secret() { - return this._secret; + 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); }; - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); + Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); + }; - cachedProperty$1(KeyPair$2, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; + Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); + }; - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; + Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); + }; - return a; - }); + Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + }; - cachedProperty$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); + Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); + // 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; + }; - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); + Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); + }; - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); }; - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); + Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); }; - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); + Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; }; - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); + 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; + } }; - var key = KeyPair$2; + // Compatibility with BaseCurve + Point.prototype.toP = Point.prototype.normalize; + Point.prototype.mixedAdd = Point.prototype.add; - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.parseBytes; + (function (exports) { - /** - * @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$1(eddsa, sig) { - this.eddsa = eddsa; + var curve = exports; - if (typeof sig !== 'object') - sig = parseBytes$1(sig); + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; - } + var curves$2 = {}; - assert$1(sig.R && sig.S, 'Signature without R or S'); + var hash$2 = {}; - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - this._S = sig.S; + var utils$h = {}; - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + var assert$b = minimalisticAssert; + var inherits = inherits_browser.exports; + + utils$h.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; } - cachedProperty(Signature$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); + 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; + } + utils$h.toArray = toArray; - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.htonl = htonl; - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); + 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; + } + utils$h.toHex32 = toHex32; - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.zero2 = zero2; - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; + 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; + } + utils$h.zero8 = zero8; - var signature = Signature$1; + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.join32 = join32; - var hash = hash$2; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; + 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; + } + utils$h.split32 = split32; - function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; - if (!(this instanceof EDDSA)) - return new EDDSA(curve); + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; - curve = curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; } + utils$h.sum32_3 = sum32_3$1; - var eddsa = EDDSA; + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; - /** - * @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 }); - }; + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; - /** - * @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); - }; + function sum64$1(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; - EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils$1.intFromLE(hash.digest()).umod(this.curve.n); - }; + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; + } + utils$h.sum64 = sum64$1; - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.fromSecret(this, secret); - }; + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; - EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); - }; + function sum64_4_hi$1(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; - /** - * * 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; - }; + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; + } + utils$h.sum64_4_hi = sum64_4_hi$1; - EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils$1.parseBytes(bytes); + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + function sum64_5_hi$1(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 y = utils$1.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); - }; + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; + } + utils$h.sum64_5_hi = sum64_5_hi$1; - EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); - }; + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; - EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils$1.intFromLE(bytes); - }; + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; - (function (exports) { + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; - var elliptic = exports; + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; - elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); + var common$5 = {}; - const createHmac = browser$2; + var utils$g = utils$h; + var assert$a = minimalisticAssert; - const ONE1 = Buffer$m.alloc(1, 1); - const ZERO1 = Buffer$m.alloc(1, 0); + function BlockHash$4() { + 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'; - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer$m.alloc(32, 0); - let v = Buffer$m.alloc(32, 1); + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; + } + common$5.BlockHash = BlockHash$4; - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; - // Step E - v = createHmac('sha256', k).update(v).digest(); + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); + // 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; - // Step G - v = createHmac('sha256', k).update(v).digest(); + msg = utils$g.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); + } - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); + return this; + }; - let T = v; + BlockHash$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); + return this._digest(enc); + }; - v = createHmac('sha256', k).update(v).digest(); + BlockHash$4.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; - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; - } + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; - return T - } + 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; - var rfc6979 = deterministicGenerateK$1; + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } - const BN = bn.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; + return res; + }; - const ZERO32 = Buffer$m.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + var sha = {}; - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; + var common$4 = {}; - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; - function isScalar (x) { - return isBuffer(x) && x.length === 32 + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); } + common$4.ft_1 = ft_1$1; - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); } + common$4.ch32 = ch32$1; - function isPoint (p) { - if (!isBuffer(p)) return false - if (p.length < 33) return false - - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } - - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); } + common$4.maj32 = maj32$1; - function __isPointCompressed (p) { - return p[0] !== 0x04 + function p32(x, y, z) { + return x ^ y ^ z; } + common$4.p32 = p32; - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } + common$4.s0_256 = s0_256$1; - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } + common$4.s1_256 = s1_256$1; - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); } + common$4.g0_256 = g0_256$1; - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); } + common$4.g1_256 = g1_256$1; - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); } - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + utils$e.inherits(SHA1, BlockHash$3); + var _1 = SHA1; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + SHA1.blockSize = 512; + SHA1.outSize = 160; + SHA1.hmacStrength = 80; + SHA1.padLength = 64; - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null + SHA1.prototype._update = function _update(msg, start) { + var W = this.W; - return getEncoded(uu, compressed) - } + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + for(; i < W.length; i++) + W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + 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]; - const compressed = assumeCompression(__compressed, p); + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } - return getEncoded(pp, compressed) - } + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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; - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + var BlockHash$2 = common$2.BlockHash; - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null + 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 + ]; - return getEncoded(qq, compressed) + function SHA256$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null + SHA256$1.prototype._update = function _update(msg, start) { + var W = this.W; - return dt - } + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4$1(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + 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]; - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null + assert$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } - return dt - } + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; - function sign (hash, x) { - return __sign(hash, x) - } + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } + utils$c.inherits(SHA224, SHA256); + var _224 = SHA224; - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); + SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; - if (Q.isInfinity()) return false + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; - r = Q.x.umod(n); - if (r.isZero() === 0) return false + var BlockHash$1 = common$1.BlockHash; - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false + 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 + ]; - return true - }; + function SHA512$1() { + if (!(this instanceof SHA512$1)) + return new SHA512$1(); - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); + var _512 = SHA512$1; - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); + SHA512$1.blockSize = 1024; + SHA512$1.outSize = 512; + SHA512$1.hmacStrength = 192; + SHA512$1.padLength = 128; + + SHA512$1.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); } + }; - const buffer = Buffer$m.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer - } + SHA512$1.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + var W = this.W; - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + 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]; - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); + assert$8(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); + 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]; - if (strict && s.cmp(nDiv2) > 0) { - return false - } + 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); - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); + 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); - // Compute s^-1 - const sInv = s.invm(n); + hh = gh; + hl = gl; - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); + gh = fh; + gl = fl; - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); + fh = eh; + fl = el; - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; + dh = ch; + dl = cl; - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); + ch = bh; + cl = bl; - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } + bh = ah; + bl = al; - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign, - signWithEntropy, - verify - }; + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } + 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); }; - // TODO: deprecate - types$c.Null = types$c.Nil; + SHA512$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.split32(this.h, 'big'); + }; - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); + function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; } - var native$1 = types$c; - - var native = native$1; - - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; } - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) + function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; } - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value + 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 captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } + 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 tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' + 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 - return type !== undefined ? type : '' + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); + 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 - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; } - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); + 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 - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; + 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); - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + 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 TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } + 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); - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; } - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + 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); - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; } - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; + var utils$a = utils$h; - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); + var SHA512 = _512; - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } + function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); - captureStackTrace(e); - return e + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; } + utils$a.inherits(SHA384, SHA512); + var _384 = SHA384; - var errors = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); }; - var NATIVE$1 = native$1; - var ERRORS$1 = errors; + sha.sha1 = _1; + sha.sha224 = _224; + sha.sha256 = _256; + sha.sha384 = _384; + sha.sha512 = _512; - function _Buffer (value) { - return isBuffer(value) - } + var ripemd = {}; - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } + var utils$9 = utils$h; + var common = common$5; - function _LengthN (type, length) { - var name = type.toJSON(); + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; + var BlockHash = common.BlockHash; - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true + function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; + BlockHash.call(this); - return Length + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; } + utils$9.inherits(RIPEMD160, BlockHash); + ripemd.ripemd160 = RIPEMD160; - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); + RIPEMD160.blockSize = 512; + RIPEMD160.outSize = 160; + RIPEMD160.hmacStrength = 192; + RIPEMD160.padLength = 64; - function Range$m (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) + 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; } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - }; - return _range + 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$9.toHex32(this.h, 'little'); + else + return utils$9.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)); } - var INT53_MAX = Math.pow(2, 53) - 1; + 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 + ]; - function Finite (value) { - return typeof value === 'number' && isFinite(value) - } - function Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value - } - function UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value - } + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; - var types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$m, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; + 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; - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); + this._init(utils$8.toArray(key, enc)); } + var hmac = Hmac; - var extra = types$b; + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(key.length <= this.blockSize); - var ERRORS = errors; - var NATIVE = native$1; + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); + }; - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false + Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; + }; - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; + Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); + }; - return _arrayOf - }, + (function (exports) { + var hash = exports; - maybe: function maybe (type) { - type = compile(type); + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha; + hash.ripemd = ripemd; + hash.hmac = hmac; - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; + // 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; + }(hash$2)); - return _maybe - }, + (function (exports) { - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + var curves = exports; - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + var hash = hash$2; + var curve$1 = curve; + var utils = utils$n; - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } + var assert = utils.assert; - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } - } + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; - return true - } + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); + } + curves.PresetCurve = PresetCurve; - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; - } + 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; + }, + }); + } - return _map - }, + 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', + ], + }); - object: function object (uncompiled) { - var type = {}; + 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', + ], + }); - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } + 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', + ], + }); - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false + 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', + ], + }); - var propertyName; + 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', + ], + }); - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; + 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', + ], + }); - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } + 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', - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658', + ], + }); - throw new TfPropertyTypeError(undefined, propertyName) - } - } + var pre; + try { + pre = require('./precomputed/secp256k1'); + } catch (e) { + pre = undefined; + } - return true - } - _object.toJSON = function () { return tfJSON(type) }; + 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, - return _object - }, + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3', + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15', + }, + ], - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre, + ], + }); + }(curves$2)); - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + var hash$1 = hash$2; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; - return _anyOf - }, + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(options); + this.hash = options.hash; + this.predResist = !!options.predResist; - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; - return _allOf - }, + var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type }; + HmacDRBG$1.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); - return _quacksLike - }, + 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; + } - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 + }; - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false + HmacDRBG$1.prototype._hmac = function hmac() { + return new hash$1.hmac(this.hash, this.K); + }; - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + HmacDRBG$1.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; - return _tuple - }, + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); + }; - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected }; + HmacDRBG$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); - return _value - } + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; }; - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; + HmacDRBG$1.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } + // Optional additional data + if (add) { + add = utils$7.toArray(add, addEnc || 'hex'); + this._update(add); + } - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); } - return TYPES.value(type) - } + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils$7.encode(res, enc); + }; - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; - throw new TfTypeError(surrogate || type, value) - } + function KeyPair$4(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; - // JIT - return typeforce$b(compile(type), value, strict) + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); } + var key$1 = KeyPair$4; - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; - var typeforce_1 = typeforce$b; + KeyPair$4.prototype.validate = function validate() { + var pub = this.getPublic(); - var bs58check$4 = bs58check$5; + 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' }; - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + return { result: true, reason: null }; + }; - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false - } + KeyPair$4.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; } - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') - - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } + if (!enc) + return this.pub; - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$m(compressed ? 34 : 33); + return this.pub.encode(enc, compact); + }; - result.writeUInt8(version, 0); - privateKey.copy(result, 1); + KeyPair$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; - if (compressed) { - result[33] = 0x01; - } + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(key, enc || 16); - return result - } + // 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); + }; - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) - } + KeyPair$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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); + }; - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + // ECDH + KeyPair$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); }; - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$3 = crypto$5; - const bs58check$3 = bs58check$5; - const ecc$6 = js; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, + KeyPair$4.prototype.inspect = function inspect() { + return ''; }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; - } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$3.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer$m.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); - } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer$m.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$3.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; - } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); - } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); - } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); - } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } - } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); - } - return hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + var signature$1 = Signature$3; + + function Position() { + this.place = 0; } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); + + 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; } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + + 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); } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); + + Signature$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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$3(r); + this.s = new BN$3(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); } - bip32$1.fromSeed = fromSeed; - Object.defineProperty(src, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; + Signature$3.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); - var address$1 = {}; + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); - var networks$3 = {}; + r = rmPadding(r); + s = rmPadding(s); - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, + 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$5.encode(res, enc); }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); }; - var payments$4 = {}; + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; - var embed = {}; + EC$1.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; - var script$1 = {}; + // 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 script_number = {}; + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN$2(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); - } - } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; + priv.iaddn(1); + return this.keyFromPrivate(priv); } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); + }; + + EC$1.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$1.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer$m.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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; } - return buffer; - } - script_number.encode = encode$g; - var script_signature = {}; + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K - var types$a = {}; + p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; + // 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); }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, - }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use + EC$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); - var Buffer$2 = safeBuffer.exports.Buffer; + var n = this.n; + var e = new BN$2(msg); + var r = signature.r; + var s = signature.s; - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false + // 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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); + }; - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.cachedProperty; - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true + /** + * @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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); } - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } - } + cachedProperty$1(KeyPair$2, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; - var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); + return a; + }); - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); + cachedProperty$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); - return signature - } + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f - }; + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$m.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$m.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer$m.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$m.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); }; - var OPS$9 = require$$7; + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 - } + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); + var key = KeyPair$2; - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.parseBytes; - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); + /** + * @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$1(eddsa, sig) { + this.eddsa = eddsa; - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); + if (typeof sig !== 'object') + sig = parseBytes$1(sig); - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; } - return size - } + assert$1(sig.R && sig.S, 'Signature without R or S'); - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + this._S = sig.S; - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + } - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; + cachedProperty(Signature$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); - number = buffer.readUInt32LE(offset + 1); - size = 5; - } + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); - return { - opcode: opcode, - number: number, - size: size - } - } + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); }; - var OPS$8 = require$$7; + var signature = Signature$1; - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } + var hash = hash$2; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; - var map_1 = map; + function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = js; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer$m.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; - } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; - } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode - } else { - chunks.push(opcode); - i += 1; - } - } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); - } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer$m.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); + if (!(this instanceof EDDSA)) + return new EDDSA(curve); - var lazy$7 = {}; + curve = curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; - }; + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; } - lazy$7.value = value; - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } - } - return Object.assign(o, a); - } - embed.p2data = p2data; + var eddsa = EDDSA; - var p2ms$3 = {}; + /** + * @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 }); + }; - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = js; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); - } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); - } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); - } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); - } - } - return Object.assign(o, a); - } - p2ms$3.p2ms = p2ms$2; + /** + * @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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; - var p2pk$3 = {}; + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = js; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); - } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); - } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); - } - } - return Object.assign(o, a); - } - p2pk$3.p2pk = p2pk$2; + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.fromSecret(this, secret); + }; - var p2pkh$4 = {}; + EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); + }; - var crypto$2 = {}; + /** + * * 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; + }; - Object.defineProperty(crypto$2, '__esModule', { value: true }); - const createHash = browser$3; - function ripemd160$1(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); - } - } - crypto$2.ripemd160 = ripemd160$1; - function sha1(buffer) { - return createHash('sha1') - .update(buffer) + EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0$1.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = browser$2; + + const ONE1 = Buffer$k.alloc(1, 1); + const ZERO1 = Buffer$k.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$k.alloc(32, 0); + let v = Buffer$k.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') .digest(); - } - crypto$2.sha1 = sha1; - function sha256$1(buffer) { - return createHash('sha256') - .update(buffer) + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') .digest(); - } - crypto$2.sha256 = sha256$1; - function hash160$1(buffer) { - return ripemd160$1(sha256$1(buffer)); - } - crypto$2.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$1(sha256$1(buffer)); - } - crypto$2.hash256 = hash256$1; - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); - const bcrypto$6 = crypto$2; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = js; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - } - if (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2pkh$4.p2pkh = p2pkh$3; + // Step G + v = createHmac('sha256', k).update(v).digest(); - var p2sh$1 = {}; + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$2; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } - } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); - } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - } + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; } - return Object.assign(o, a); + + return T } - p2sh$1.p2sh = p2sh; - var p2wpkh$2 = {}; + var rfc6979 = deterministicGenerateK$1; - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + const BN = bn$1.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); + const ZERO32 = Buffer$k.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 } - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G } - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false - chk = polymodStep(chk) ^ (c >> 5); + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true } - chk = polymodStep(chk); - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false } - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + function __isPointCompressed (p) { + return p[0] !== 0x04 + } - prefix = prefix.toLowerCase(); + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) + } - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G + } - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 + } - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) - return result + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) } - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' + return getEncoded(uu, compressed) + } - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); - } + const compressed = assumeCompression(__compressed, p); - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } + return getEncoded(pp, compressed) } - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - } + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null - throw new Error(res) + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) } - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } + return getEncoded(qq, compressed) + } - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' - } + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - return result + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt } - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt } - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res + function sign (hash, x) { + return __sign(hash, x) + } - throw new Error(res) + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) } - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); + + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); + + if (Q.isInfinity()) return false + + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer$k.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer } - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) - throw new Error(res) + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) } - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign, + signWithEntropy, + verify }; - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); - const bcrypto$4 = crypto$2; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = js; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$m.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); + } + + var native$1 = types$c; + + var native = native$1; + + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } + + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); } - return Object.assign(o, a); } - p2wpkh$2.p2wpkh = p2wpkh$1; - var p2wsh$1 = {}; + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$2; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = js; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$m.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); + return type !== undefined ? type : '' } - function chunkHasUncompressedPubkey(chunk) { - if ( - isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; + + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') + } + + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); + + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + } + + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); } else { - return false; + this.message = 'Unexpected property "' + property + '"'; } + + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; - } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), - }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); - } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); - } - } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); - } + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); } - return Object.assign(o, a); + + captureStackTrace(e); + return e } - p2wsh$1.p2wsh = p2wsh; - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; + var errors = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; + var NATIVE$1 = native$1; + var ERRORS$1 = errors; + + function _Buffer (value) { + return isBuffer(value) } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer$m.from(data), + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` }; + return _range } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; } - } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; + return str + }; - var ecpair = {}; + return _arrayOf + }, - var browser$1 = {exports: {}}; + maybe: function maybe (type) { + type = compile(type); - // limit of Crypto.getRandomValues() - // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues - var MAX_BYTES = 65536; + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) }; - // Node supports requesting up to this number of bytes - // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 - var MAX_UINT32 = 4294967295; + return _maybe + }, - function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') - } + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); - var Buffer$1 = safeBuffer.exports.Buffer; - var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false - if (crypto$1 && crypto$1.getRandomValues) { - browser$1.exports = randomBytes$1; - } else { - browser$1.exports = oldBrowser; - } + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } - function randomBytes$1 (size, cb) { - // phantomjs needs to throw - if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } - var bytes = Buffer$1.allocUnsafe(size); + return true + } - if (size > 0) { // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues - // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - for (var generated = 0; generated < size; generated += MAX_BYTES) { - // buffer.slice automatically checks if the end is past the end of - // the buffer so we don't have to here - crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); - } + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; } else { - crypto$1.getRandomValues(bytes); + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; } - } - if (typeof cb === 'function') { - return nextTick(function () { - cb(null, bytes); - }) - } + return _map + }, - return bytes - } + object: function object (uncompiled) { + var type = {}; - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = js; - const randomBytes = browser$1.exports; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); - } - return sig; + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); } - } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; - var block = {}; + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false - var bufferutils = {}; + var propertyName; - var Buffer = safeBuffer.exports.Buffer; + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$5 = 9007199254740991; + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) + } - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') - } + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue - function encode$b (number, buffer, offset) { - checkUInt53$1(number); + throw new TfPropertyTypeError(undefined, propertyName) + } + } - if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + return true + } + _object.toJSON = function () { return tfJSON(type) }; - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; + return _object + }, - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } + return _anyOf + }, - return buffer - } + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); - function decode$a (buffer, offset) { - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - var first = buffer.readUInt8(offset); + return _allOf + }, - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) + return _quacksLike + }, - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false - return number + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected }; + + return _value } - } + }; - function encodingLength$1 (number) { - checkUInt53$1(number); + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) } - return buffer; + + // JIT + return typeforce$b(compile(type), value, strict) } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer$m.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); - } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true } } - bufferutils.BufferReader = BufferReader$1; - var transaction = {}; + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$k(compressed ? 34 : 33); - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$2; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) } - const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw }; - function isOutput(out) { - return out.value !== undefined; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$3 = crypto$5; + const bs58check$3 = bs58check$5; + const ecc$6 = js; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); + get depth() { + return this.__DEPTH; } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); + get index() { + return this.__INDEX; } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); - } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; + get privateKey() { + return this.__D; } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; - } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); + get identifier() { + return crypto$3.hash160(this.publicKey); } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; + get fingerprint() { + return this.identifier.slice(0, 4); } - // serialize and hash - const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer$m.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); + get compressed() { + return true; + } + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; + } + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$k.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$k.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$3.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$k.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer$m.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); } - tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); - } else { - bufferWriter.writeSlice(txOut.valueBuffer); - } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; - } + return hd; } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; - var length = values.length; - var results = values.concat(); + var address$1 = {}; - while (length > 1) { - var j = 0; + var networks$3 = {}; - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$m.concat([left, right]); + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; - results[j] = digestFn(data); - } + var payments$4 = {}; - length = j; - } + var embed = {}; - return results[0] - }; + var script$1 = {}; - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$2; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer$m.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer$m.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$m && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer$m && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); - } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$k.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; } + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' ); } - function anyTxHasWitness(transactions) { - return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) - ); + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; - var psbt$1 = {}; + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use - var psbt = {}; + var Buffer$2 = safeBuffer.exports.Buffer; - var combiner = {}; + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false - var parser = {}; + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false - var fromBuffer = {}; + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false - var converter = {}; + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - var typeFields = {}; + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - var globalXpub$1 = {}; + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$4 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$4(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) } - return data; } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$m.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$k.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); + return x; } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$k.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$k.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$k.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); } - globalXpub$1.canAddToArray = canAddToArray$1; + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; - var unsignedTx$1 = {}; + var OPS$9 = require$$7; - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), - }; + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 } - unsignedTx$1.encode = encode$9; - var finalScriptSig$1 = {}; + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, - }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); - var finalScriptWitness$1 = {}; + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); - return { - key, - value: data, - }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); + + return size } - finalScriptWitness$1.canAdd = canAdd$4; - var nonWitnessUtxo$1 = {}; + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, - }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; - } - nonWitnessUtxo$1.canAdd = canAdd$3; + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; - var partialSig$1 = {}; + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, - }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer$m.concat([head, pSig.pubkey]), - value: pSig.signature, - }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) - ); - } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; - var porCommitment$1 = {}; + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); + number = buffer.readUInt32LE(offset + 1); + size = 5; } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { - key, - value: Buffer$m.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; + opcode: opcode, + number: number, + size: size + } } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; + + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; } - porCommitment$1.canAdd = canAdd$2; - var sighashType$1 = {}; + var map_1 = map; - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.readUInt32LE(0); + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = js; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$m.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; } - sighashType$1.canAdd = canAdd$1; - - var witnessUtxo$1 = {}; - - var tools = {}; - - var varint$1 = {}; - - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$4 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) - throw new RangeError('value out of range'); + function chunksIsBuffer(buf) { + return isBuffer(buf); } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } - return buffer; + function chunksIsArray(buf) { + return types.Array(buf); } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; - } + function singleChunkIsBuffer(buf) { + return isBuffer(buf); } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$k.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; } - varint$1.encodingLength = encodingLength; - - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } } - return buffer; + return chunks; } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$m.from([0])); - return Buffer$m.concat(buffers); + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$m.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$k.from(chunkStr, 'hex'); + }), ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; } - tools.writeUInt64LE = writeUInt64LE; + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); - } - return { - script, - value, - }; + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; }; } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); } - witnessUtxo$1.canAdd = canAdd; + embed.p2data = p2data; - var bip32Derivation$1 = {}; + var p2ms$3 = {}; - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$3 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = js; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); } - return data; - } - function encode(data) { - const head = Buffer$m.from([TYPE_BYTE]); - const key = Buffer$m.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - return { - decode, - encode, - check, - expected, - canAddToArray, - }; + return Object.assign(o, a); } - bip32Derivation$1.makeConverter = makeConverter$2; + p2ms$3.p2ms = p2ms$2; - var checkPubkey$1 = {}; + var p2pk$3 = {}; - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); - if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = js; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); } - return pubkey; } + return Object.assign(o, a); } - checkPubkey$1.makeChecker = makeChecker; + p2pk$3.p2pk = p2pk$2; - var redeemScript$1 = {}; + var p2pkh$4 = {}; - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; + var crypto$2 = {}; + + Object.defineProperty(crypto$2, '__esModule', { value: true }); + const createHash = browser$3; + function ripemd160$1(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); } - return { - decode, - encode, - check, - expected, - canAdd, - }; } - redeemScript$1.makeConverter = makeConverter$1; - - var witnessScript$1 = {}; + crypto$2.ripemd160 = ripemd160$1; + function sha1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$2.sha1 = sha1; + function sha256$1(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$2.sha256 = sha256$1; + function hash160$1(buffer) { + return ripemd160$1(sha256$1(buffer)); + } + crypto$2.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$1(sha256$1(buffer)); + } + crypto$2.hash256 = hash256$1; - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$2; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = js; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); } - return { - decode, - encode, - check, - expected, - canAdd, - }; + return Object.assign(o, a); } - witnessScript$1.makeConverter = makeConverter; + p2pkh$4.p2pkh = p2pkh$3; - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), - }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), - }; - converter.outputs = outputs; + var p2sh$1 = {}; - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$2; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); return { - key, - value, + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', - ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); - } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); } - inputKeyVals.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); } - outputKeyVals.push(output); } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); + return Object.assign(o, a); } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$m.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); + p2sh$1.p2sh = p2sh; + + var p2wpkh$2 = {}; + + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; - } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); - } + + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - } - } - inputs.push(input); + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - } - } - outputs.push(output); + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); } - return { globalMap, inputs, outputs }; + + return result } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - var toBuffer = {}; + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer$m.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$m.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$m.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); - } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); - }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along - return { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), - }; + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res } - toBuffer.psbtToKeyVals = psbtToKeyVals; - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); - } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, - }); + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); - }; + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); - }); - return set; + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res } - var utils = {}; + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; + throw new Error(res) } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); - } - if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 - ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$2; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = js; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$k.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$k.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } } + return Object.assign(o, a); } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } + p2wpkh$2.p2wpkh = p2wpkh$1; + + var p2wsh$1 = {}; + + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$2; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = js; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$k.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); }); - return count; } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; - } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); + function chunkHasUncompressedPubkey(chunk) { + if ( + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; } } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, ); - } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; - } + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$k.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); } } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$k.from(data), }; } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); - } - txBuf.writeUInt32LE(version, 0); - return txBuf; + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; + throw new Error(address + ' has no matching Script'); } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); + address$1.toOutputScript = toOutputScript; - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, - }; - } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); - } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); - return this; + var ecpair = {}; + + var browser$1 = {exports: {}}; + + // limit of Crypto.getRandomValues() + // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + var MAX_BYTES = 65536; + + // Node supports requesting up to this number of bytes + // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 + var MAX_UINT32 = 4294967295; + + function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') + } + + var Buffer$1 = safeBuffer.exports.Buffer; + var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + + if (crypto$1 && crypto$1.getRandomValues) { + browser$1.exports = randomBytes$1; + } else { + browser$1.exports = oldBrowser; + } + + function randomBytes$1 (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer$1.allocUnsafe(size); + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); + } + } else { + crypto$1.getRandomValues(bytes); + } } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); - return this; + + if (typeof cb === 'function') { + return nextTick(function () { + cb(null, bytes); + }) } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); - return this; + + return bytes + } + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = js; + const randomBytes = browser$1.exports; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); - return this; + get privateKey() { + return this.__D; } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - return this; + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - return this; + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$k.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); - return this; } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } - return this; + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number } } - psbt.Psbt = Psbt$1; - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$2; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, - }; + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$k.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); - } - static fromBase64(data, opts = {}) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, opts); + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); } - static fromHex(data, opts = {}) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, opts); + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); } - get inputCount() { - return this.data.inputs.length; + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); } - get version() { - return this.__CACHE.__TX.version; + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); } - set version(version) { - this.setVersion(version); + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; } - get locktime() { - return this.__CACHE.__TX.locktime; + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); } - set locktime(locktime) { - this.setLocktime(locktime); + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; + readVarSlice() { + return this.readSlice(this.readVarInt()); } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); - } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$2; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$k.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$k.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; } - addOutput(outputData) { + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); + hasWitnesses = true; + } else { + bufferReader.offset -= 2; } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); return tx; } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); - } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); - return this; - } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, - ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); - return this; - } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), - ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); - } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) - ); + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); + isCoinbase() { return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); - } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$2(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) ); - return results.reduce((final, res) => res === true && final, true); - } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); - } - return results.every(res => res === true); } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; } - return this; + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$2(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; }); } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; } - return this; + // serialize and hash + const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$k.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); }); - }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$k.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - }); - }); + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); } toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); + return this.toBuffer(undefined, undefined).toString('hex'); } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); } - return this; + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$k.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; + } + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$2; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; + static fromHex(hex) { + return Block.fromBuffer(Buffer$k.from(hex, 'hex')); } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$k.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$k && result.length === 32)) return null; + return result; } - } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$k && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; + hasWitness() { + return anyTxHasWitness(this.transactions); } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; } - addOutput(output) { - if ( - output.script === undefined || - output.value === undefined || - !isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); } - toBuffer() { - return this.tx.toBuffer(); + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); } - } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) ); } - } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } - }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } - }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } - }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, - ); + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); - } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 ); } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } - } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), ); } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, - ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', ); } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$k.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); return { - script: meaningfulScript, - sighashType, - hash, + key, + value, }; } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - } - return payment; + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } - } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; - } - return res; } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); - } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), ); } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; + return keyVal.value; } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); - } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; - } - function readVarSlice() { - return readSlice(readVarInt()); - } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; - } - return readVector(); + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; - } - return text; + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer$m.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); - } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); - } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); - } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); } - writeVector(witness); - return buffer; + return keyVal.value; } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, - }); + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; - } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); - } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); - } - return c[inputIndex]; + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); } + return keyVal.value; } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } if ( - !isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$k.concat([head, pSig.pubkey]), + value: pSig.signature, + }; } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', + key, + value: Buffer$k.from(data, 'utf8'), }; } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); } + return keyVal.value.readUInt32LE(0); } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$k.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; } - function range$2(n) { - return [...Array(n).keys()]; + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; } + sighashType$1.canAdd = canAdd$1; - var transaction_builder = {}; - - var classify$1 = {}; + var witnessUtxo$1 = {}; - var multisig$1 = {}; + var tools = {}; - var input$b = {}; + var varint$1 = {}; - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + return buffer; } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - - var output$e = {}; + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$k.from([0])); + return Buffer$k.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$k.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; - var nulldata = {}; + var bip32Derivation$1 = {}; - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$k.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - - var pubkey = {}; + bip32Derivation$1.makeConverter = makeConverter$2; - var input$9 = {}; + var checkPubkey$1 = {}; - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; + checkPubkey$1.makeChecker = makeChecker; - var output$b = {}; + var redeemScript$1 = {}; - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG - ); + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$k.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; - - var pubkeyhash = {}; + redeemScript$1.makeConverter = makeConverter$1; - var input$7 = {}; + var witnessScript$1 = {}; - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$k.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; + witnessScript$1.makeConverter = makeConverter; - var output$9 = {}; + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$k.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; - - var scripthash = {}; - - var input$5 = {}; + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - var output$7 = {}; + var toBuffer = {}; - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$k.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$k.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$k.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; - var output$6 = {}; - - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; - }; + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), - ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), ); } - // match types - if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; - } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; - }; - - var output$5 = {}; - - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL - ); + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; - }; - - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; - - var witnesscommitment = {}; - - var output$3 = {}; - - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer$m.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$m.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + function getTx(psbt) { + return psbt.globalMap.unsignedTx; } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; } - output$3.decode = decode; - - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; - - var witnesspubkeyhash = {}; - var input$3 = {}; + var utils = {}; - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; - - var witnessscripthash = {}; - - var input$1 = {}; - - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; - - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); } - classify$1.witness = classifyWitness; - - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$2; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); - } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$k.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; + static fromHex(data, txFromBuffer) { + const buffer = Buffer$k.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); + toBuffer() { + return parser_1.psbtToBuffer(this); } - build() { - return this.__build(false); + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; } - buildIncomplete() { - return this.__build(true); + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); - } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; - } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; - } - prevOutType = expanded.type; - } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); - } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; - } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; } } - return tx; + return this; } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$2; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, }); - }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + static fromBase64(data, opts = {}) { + const buffer = Buffer$k.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer$k.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; - } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); - }) - ); + set version(version) { + this.setVersion(version); } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; - } - return false; - }); - }); + get locktime() { + return this.__CACHE.__TX.locktime; } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; + set locktime(locktime) { + this.setLocktime(locktime); } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, }; - } - } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); - } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; } - return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; - } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); - } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); - return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, - }; - } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, - }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); - } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); - } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, ); } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; } - } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); - } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); - } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, ); } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); + } + return results.every(res => res === true); + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), ); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), ); } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; } - } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, ); - } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', - ); + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, ); - // updates inline - Object.assign(input, prepared); } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + return this; } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); - } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; } - - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; - const address = address$1; - src$1.address = address; - const crypto = crypto$2; - var crypto_1 = src$1.crypto = crypto; - const ECPair = ecpair; - src$1.ECPair = ECPair; - const networks = networks$3; - src$1.networks = networks; - const payments = payments$4; - src$1.payments = payments; - const script = script$1; - src$1.script = script; - var block_1 = block; - src$1.Block = block_1.Block; - var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$1.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - - var re$b = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION$1 = '2.0.0'; - - const MAX_LENGTH$5 = 256; - const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - - var constants$1 = { - SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, - MAX_LENGTH: MAX_LENGTH$5, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, - MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 - }; - - const debug$7 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1$1 = debug$7; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; - const debug = debug_1$1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$b, re$b.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts$1 = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$9 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts$1.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1$1 = parseOptions$9; - - const numeric$1 = /^[0-9]+$/; - const compareIdentifiers$3 = (a, b) => { - const anum = numeric$1.test(a); - const bnum = numeric$1.test(b); - - if (anum && bnum) { - a = +a; - b = +b; + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - - var identifiers$1 = { - compareIdentifiers: compareIdentifiers$3, - rcompareIdentifiers: rcompareIdentifiers$1 - }; - - const debug$6 = debug_1$1; - const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; - const { re: re$a, t: t$9 } = re$b.exports; - - const parseOptions$8 = parseOptions_1$1; - const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; - class SemVer$t { - constructor (version, options) { - options = parseOptions$8(options); - - if (version instanceof SemVer$t) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$4) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$4} characters` - ) - } - - debug$6('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER$2) { - return num - } - } - return id - }); + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); } - return this.version + this.tx.addOutput(output.script, output.value); } - - toString () { - return this.version + toBuffer() { + return this.tx.toBuffer(); } - - compare (other) { - debug$6('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$t)) { - if (typeof other === 'string' && other === this.version) { - return 0 + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + throws = true; } - other = new SemVer$t(other, this.options); + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); } - - if (other.version === this.version) { - return 0 + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); } - - return this.compareMain(other) || this.comparePre(other) + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); } - - compareMain (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); } - - return ( - compareIdentifiers$2(this.major, other.major) || - compareIdentifiers$2(this.minor, other.minor) || - compareIdentifiers$2(this.patch, other.patch) - ) + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); } - - comparePre (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + if (p2sh) { + finalScriptSig = p2sh.input; } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) + return { + finalScriptSig, + finalScriptWitness, + }; + } + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); } - this.format(); - this.raw = this.version; - return this + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); } + return { + script: meaningfulScript, + sighashType, + hash, + }; } - - var semver$3 = SemVer$t; - - const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; - const { re: re$9, t: t$8 } = re$b.exports; - const SemVer$s = semver$3; - - const parseOptions$7 = parseOptions_1$1; - const parse$b = (version, options) => { - options = parseOptions$7(options); - - if (version instanceof SemVer$s) { - return version + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; } - - if (typeof version !== 'string') { - return null + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } } - - if (version.length > MAX_LENGTH$3) { - return null + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; } - - const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; - if (!r.test(version)) { - return null + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); } - - try { - return new SemVer$s(version, options) - } catch (er) { - return null + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); } - }; - - var parse_1$1 = parse$b; - - const parse$a = parse_1$1; - const valid$3 = (version, options) => { - const v = parse$a(version, options); - return v ? v.version : null - }; - var valid_1$1 = valid$3; - - const parse$9 = parse_1$1; - const clean$1 = (version, options) => { - const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1$1 = clean$1; - - const SemVer$r = semver$3; - - const inc$1 = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; + } + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); } - - try { - return new SemVer$r(version, options).inc(release, identifier).version - } catch (er) { - return null + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; } - }; - var inc_1$1 = inc$1; - - const SemVer$q = semver$3; - const compare$l = (a, b, loose) => - new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - - var compare_1$1 = compare$l; - - const compare$k = compare_1$1; - const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; - var eq_1$1 = eq$5; - - const parse$8 = parse_1$1; - const eq$4 = eq_1$1; - - const diff$1 = (version1, version2) => { - if (eq$4(version1, version2)) { - return null - } else { - const v1 = parse$8(version1); - const v2 = parse$8(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined + function readVarSlice() { + return readSlice(readVarInt()); } - }; - var diff_1$1 = diff$1; - - const SemVer$p = semver$3; - const major$1 = (a, loose) => new SemVer$p(a, loose).major; - var major_1$1 = major$1; - - const SemVer$o = semver$3; - const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; - var minor_1$1 = minor$1; - - const SemVer$n = semver$3; - const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; - var patch_1$1 = patch$1; - - const parse$7 = parse_1$1; - const prerelease$1 = (version, options) => { - const parsed = parse$7(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1$1 = prerelease$1; - - const compare$j = compare_1$1; - const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); - var rcompare_1$1 = rcompare$1; - - const compare$i = compare_1$1; - const compareLoose$1 = (a, b) => compare$i(a, b, true); - var compareLoose_1$1 = compareLoose$1; - - const SemVer$m = semver$3; - const compareBuild$5 = (a, b, loose) => { - const versionA = new SemVer$m(a, loose); - const versionB = new SemVer$m(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1$1 = compareBuild$5; - - const compareBuild$4 = compareBuild_1$1; - const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); - var sort_1$1 = sort$1; - - const compareBuild$3 = compareBuild_1$1; - const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); - var rsort_1$1 = rsort$1; - - const compare$h = compare_1$1; - const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; - var gt_1$1 = gt$7; - - const compare$g = compare_1$1; - const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; - var lt_1$1 = lt$5; - - const compare$f = compare_1$1; - const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; - var neq_1$1 = neq$3; - - const compare$e = compare_1$1; - const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; - var gte_1$1 = gte$5; - - const compare$d = compare_1$1; - const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; - var lte_1$1 = lte$5; - - const eq$3 = eq_1$1; - const neq$2 = neq_1$1; - const gt$6 = gt_1$1; - const gte$4 = gte_1$1; - const lt$4 = lt_1$1; - const lte$4 = lte_1$1; - - const cmp$3 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq$3(a, b, loose) - - case '!=': - return neq$2(a, b, loose) - - case '>': - return gt$6(a, b, loose) - - case '>=': - return gte$4(a, b, loose) - - case '<': - return lt$4(a, b, loose) - - case '<=': - return lte$4(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; } - }; - var cmp_1$1 = cmp$3; - - const SemVer$l = semver$3; - const parse$6 = parse_1$1; - const {re: re$8, t: t$7} = re$b.exports; - - const coerce$1 = (version, options) => { - if (version instanceof SemVer$l) { - return version + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; } - - if (typeof version === 'number') { - version = String(version); + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$k.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); } - - if (typeof version !== 'string') { - return null + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$8[t$7.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$8[t$7.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; } - re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); } - // leave it in a clean state - re$8[t$7.COERCERTL].lastIndex = -1; + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); } - - if (match === null) - return null - - return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1$1 = coerce$1; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); - } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; } - - return self + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; - } - - if (prev) { - prev.next = next; - } - - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } - - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); } + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; + var transaction_builder = {}; - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; + var classify$1 = {}; - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; + var multisig$1 = {}; - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } + var input$b = {}; - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); } - this.length--; - return res + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; }; - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } + var output$e = {}; - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; }; - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; + var nulldata = {}; - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; }; + const output$c = { check: check$b }; + nulldata.output = output$c; - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; + var pubkey = {}; - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; + var input$9 = {}; - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; }; - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } + var output$b = {}; - return acc + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; }; - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; - return acc - }; + var pubkeyhash = {}; - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; + var input$7 = {}; - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; }; - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; + var output$9 = {}; - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; }; - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } - - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; + var scripthash = {}; - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this - }; + var input$5 = {}; - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); + var output$7 = {}; - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; - self.length++; + var output$6 = {}; - return inserted + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); } - self.length++; + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; - this.list = list; - this.value = value; + var witnesscommitment = {}; - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } + var output$3 = {}; - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$k.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$k.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; - const naiveLength = () => 1; + var witnesspubkeyhash = {}; - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; + var input$3 = {}; - if (!options) - options = {}; + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } + var witnessscripthash = {}; - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') + var input$1 = {}; - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; - this[MAX_AGE] = mA; - trim(this); + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$2; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); } - get maxAge () { - return this[MAX_AGE] + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, }); - } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } - } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list + this.__USE_LOW_R = setting; + return setting; } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); + } + this.__TX.locktime = locktime; } - - dumpLru () { - return this[LRU_LIST] + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); } - - get (key) { - return get$1(this, key, true) + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); } - - peek (key) { - return get$1(this, key, false) + build() { + return this.__build(false); } - - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null - - del(this, node); - return node.value + buildIncomplete() { + return this.__build(true); } - - del (key) { - del(this, this[CACHE].get(key)); + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; } + prevOutType = expanded.type; } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); - } - } - - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); } } - return hit.value + return tx; } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; - - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; } } - - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; - - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$l { - constructor (range, options) { - options = parseOptions$6(options); - - if (range instanceof Range$l) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$l(range.raw, options) - } - } - - if (range instanceof Comparator$7) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet$1(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny$1(c[0])) { - this.set = [c]; - break - } - } - } + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache$1.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); - debug$5('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); - debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator$1(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0$1(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$7(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet$1(comp)) - return [comp] - rangeMap.set(comp.value, comp); + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache$1.set(memoKey, result); - return result } - - intersects (range, options) { - if (!(range instanceof Range$l)) { - throw new TypeError('a Range is required') + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable$1(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable$1(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; } - - if (typeof version === 'string') { - try { - version = new SemVer$k(version, this.options); - } catch (er) { - return false - } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; } - - for (let i = 0; i < this.set.length; i++) { - if (testSet$1(this.set[i], version, this.options)) { - return true - } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; } - return false } + return { type }; } - var range$1 = Range$l; - - const LRU$1 = lruCache; - const cache$1 = new LRU$1({ max: 1000 }); - - const parseOptions$6 = parseOptions_1$1; - const Comparator$7 = comparator$1; - const debug$5 = debug_1$1; - const SemVer$k = semver$3; - const { - re: re$7, - t: t$6, - comparatorTrimReplace: comparatorTrimReplace$1, - tildeTrimReplace: tildeTrimReplace$1, - caretTrimReplace: caretTrimReplace$1 - } = re$b.exports; - - const isNullSet$1 = c => c.value === '<0.0.0-0'; - const isAny$1 = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable$1 = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator$1 = (comp, options) => { - debug$5('comp', comp, options); - comp = replaceCarets$1(comp, options); - debug$5('caret', comp); - comp = replaceTildes$1(comp, options); - debug$5('tildes', comp); - comp = replaceXRanges$1(comp, options); - debug$5('xrange', comp); - comp = replaceStars$1(comp, options); - debug$5('stars', comp); - return comp - }; - - const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde$1(comp, options) - }).join(' '); - - const replaceTilde$1 = (comp, options) => { - const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$5('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - debug$5('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret$1(comp, options) - }).join(' '); - - const replaceCaret$1 = (comp, options) => { - debug$5('caret', comp, options); - const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('caret', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$5('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$5('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); } - - debug$5('caret return', ret); - return ret - }) - }; - - const replaceXRanges$1 = (comp, options) => { - debug$5('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange$1(comp, options) - }).join(' ') - }; - - const replaceXRange$1 = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$5('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX$1(M); - const xm = xM || isX$1(m); - const xp = xm || isX$1(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; } - - debug$5('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars$1 = (comp, options) => { - debug$5('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$7[t$6.STAR], '') - }; - - const replaceGTE0$1 = (comp, options) => { - debug$5('replaceGTE0', comp, options); - return comp.trim() - .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace$1 = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX$1(fM)) { - from = ''; - } else if (isX$1(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX$1(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - if (isX$1(tM)) { - to = ''; - } else if (isX$1(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX$1(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - return (`${from} ${to}`).trim() - }; - - const testSet$1 = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$5(set[i].semver); - if (set[i].semver === Comparator$7.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$5 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$6 { - static get ANY () { - return ANY$5 - } - constructor (comp, options) { - options = parseOptions$5(options); - - if (comp instanceof Comparator$6) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); } - - debug$4('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$5) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); } - - debug$4('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); + } + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$5; - } else { - this.semver = new SemVer$j(m[2], this.options.loose); + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); } } - - toString () { - return this.value + } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); } - - test (version) { - debug$4('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$5 || version === ANY$5) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer$j(version, this.options); - } catch (er) { - return false + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); } - } - - return cmp$2(version, this.operator, this.semver, this.options) + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; } - - intersects (comp, options) { - if (!(comp instanceof Comparator$6)) { - throw new TypeError('a Comparator is required') + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); + } + if (keyPair === undefined) { + throw new Error('sign requires keypair'); + } + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); + } + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$k(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$k(this.value, options).test(comp.semver) + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp$2(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp$2(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; } - var comparator$1 = Comparator$6; - - const parseOptions$5 = parseOptions_1$1; - const {re: re$6, t: t$5} = re$b.exports; - const cmp$2 = cmp_1$1; - const debug$4 = debug_1$1; - const SemVer$j = semver$3; - const Range$k = range$1; - - const Range$j = range$1; - const satisfies$7 = (version, range, options) => { - try { - range = new Range$j(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1$1 = satisfies$7; - - const Range$i = range$1; + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$2; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; - // Mostly just for testing and legacy API reasons - const toComparators$1 = (range, options) => - new Range$i(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + var re$5 = {exports: {}}; - var toComparators_1$1 = toComparators$1; + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; - const SemVer$i = semver$3; - const Range$h = range$1; + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; - const maxSatisfying$1 = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$h(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$i(max, options); - } - } - }); - return max - }; - var maxSatisfying_1$1 = maxSatisfying$1; + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; - const SemVer$h = semver$3; - const Range$g = range$1; - const minSatisfying$1 = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$g(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$h(min, options); - } - } - }); - return min + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH }; - var minSatisfying_1$1 = minSatisfying$1; - - const SemVer$g = semver$3; - const Range$f = range$1; - const gt$5 = gt_1$1; - - const minVersion$1 = (range, loose) => { - range = new Range$f(range, loose); - - let minver = new SemVer$g('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$g('0.0.0-0'); - if (range.test(minver)) { - return minver - } - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$g(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$5(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$5(minver, setMin))) - minver = setMin; - } + var debug_1 = debug$3; - if (minver && range.test(minver)) { - return minver - } + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; - return null - }; - var minVersion_1$1 = minVersion$1; + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; - const Range$e = range$1; - const validRange$1 = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$e(range, options).range || '*' - } catch (er) { - return null - } + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); }; - var valid$2 = validRange$1; - const SemVer$f = semver$3; - const Comparator$5 = comparator$1; - const {ANY: ANY$4} = Comparator$5; - const Range$d = range$1; - const satisfies$6 = satisfies_1$1; - const gt$4 = gt_1$1; - const lt$3 = lt_1$1; - const lte$3 = lte_1$1; - const gte$3 = gte_1$1; - - const outside$5 = (version, range, hilo, options) => { - version = new SemVer$f(version, options); - range = new Range$d(range, options); + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt$4; - ltefn = lte$3; - ltfn = lt$3; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt$3; - ltefn = gte$3; - ltfn = gt$4; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. - // If it satisfies the range it is not outside - if (satisfies$6(version, range, options)) { - return false - } + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - let high = null; - let low = null; + // ## Main Version + // Three dot-separated numeric identifiers. - comparators.forEach((comparator) => { - if (comparator.semver === ANY$4) { - comparator = new Comparator$5('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true - }; + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. - var outside_1$1 = outside$5; + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); - // Determine if version is greater than all the versions possible in the range. - const outside$4 = outside_1$1; - const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); - var gtr_1$1 = gtr$1; + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); - const outside$3 = outside_1$1; - // Determine if version is less than all the versions possible in the range - const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); - var ltr_1$1 = ltr$1; + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. - const Range$c = range$1; - const intersects$1 = (r1, r2, options) => { - r1 = new Range$c(r1, options); - r2 = new Range$c(r2, options); - return r1.intersects(r2) - }; - var intersects_1$1 = intersects$1; + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$5 = satisfies_1$1; - const compare$c = compare_1$1; - var simplify$1 = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$c(a, b, options)); - for (const version of v) { - const included = satisfies$5(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. - const Range$b = range$1; - const Comparator$4 = comparator$1; - const { ANY: ANY$3 } = Comparator$4; - const satisfies$4 = satisfies_1$1; - const compare$b = compare_1$1; + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. - const subset$1 = (sub, dom, options = {}) => { - if (sub === dom) - return true + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - sub = new Range$b(sub, options); - dom = new Range$b(dom, options); - let sawNonNull = false; + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset$1(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. - const simpleSubset$1 = (sub, dom, options) => { - if (sub === dom) - return true + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); - if (sub.length === 1 && sub[0].semver === ANY$3) { - if (dom.length === 1 && dom[0].semver === ANY$3) - return true - else if (options.includePrerelease) - sub = [ new Comparator$4('>=0.0.0-0') ]; - else - sub = [ new Comparator$4('>=0.0.0') ]; - } + createToken('FULL', `^${src[t.FULLPLAIN]}$`); - if (dom.length === 1 && dom[0].semver === ANY$3) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator$4('>=0.0.0') ]; - } + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT$1(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT$1(lt, c, options); - else - eqSet.add(c.semver); - } + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - if (eqSet.size > 1) - return null + createToken('GTLT', '((?:<|>)?=?)'); - let gtltComp; - if (gt && lt) { - gtltComp = compare$b(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies$4(eq, String(gt), options)) - return null + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); - if (lt && !satisfies$4(eq, String(lt), options)) - return null + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); - for (const c of dom) { - if (!satisfies$4(eq, String(c), options)) - return false - } + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - return true - } + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT$1(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT$1(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; - return true - }; + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - // >=1.2.3 is lower than >1.2.3 - const higherGT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - // <=1.2.3 is higher than <1.2.3 - const lowerLT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; - var subset_1$1 = subset$1; + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); - // just pre-load all the stuff that index.js lazily exports - const internalRe$1 = re$b.exports; - var semver$2 = { - re: internalRe$1.re, - src: internalRe$1.src, - tokens: internalRe$1.t, - SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, - SemVer: semver$3, - compareIdentifiers: identifiers$1.compareIdentifiers, - rcompareIdentifiers: identifiers$1.rcompareIdentifiers, - parse: parse_1$1, - valid: valid_1$1, - clean: clean_1$1, - inc: inc_1$1, - diff: diff_1$1, - major: major_1$1, - minor: minor_1$1, - patch: patch_1$1, - prerelease: prerelease_1$1, - compare: compare_1$1, - rcompare: rcompare_1$1, - compareLoose: compareLoose_1$1, - compareBuild: compareBuild_1$1, - sort: sort_1$1, - rsort: rsort_1$1, - gt: gt_1$1, - lt: lt_1$1, - eq: eq_1$1, - neq: neq_1$1, - gte: gte_1$1, - lte: lte_1$1, - cmp: cmp_1$1, - coerce: coerce_1$1, - Comparator: comparator$1, - Range: range$1, - satisfies: satisfies_1$1, - toComparators: toComparators_1$1, - maxSatisfying: maxSatisfying_1$1, - minSatisfying: minSatisfying_1$1, - minVersion: minVersion_1$1, - validRange: valid$2, - outside: outside_1$1, - gtr: gtr_1$1, - ltr: ltr_1$1, - intersects: intersects_1$1, - simplifyRange: simplify$1, - subset: subset_1$1, - }; + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); - function unsafeTo64bitLE(n) { - // we want to represent the input as a 8-bytes array - if (n > Number.MAX_SAFE_INTEGER) { - throw new Error("Can't convert numbers > MAX_SAFE_INT"); - } - var byteArray = Buffer$m.alloc(8, 0); - for (var index = 0; index < byteArray.length; index++) { - var byte = n & 0xff; - byteArray[index] = byte; - n = (n - byte) / 256; - } - return byteArray; - } - function unsafeFrom64bitLE(byteArray) { - var value = 0; - if (byteArray.length != 8) { - throw new Error("Expected Bufffer of lenght 8"); - } - if (byteArray[7] != 0) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); - } - if (byteArray[6] > 0x1f) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); - } - for (var i = byteArray.length - 1; i >= 0; i--) { - value = value * 256 + byteArray[i]; - } - return value; - } - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$m.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - var bytes = unsafeTo64bitLE(i); - this.writeSlice(bytes); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$m.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer$m.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var buf = this.readSlice(8); - var n = unsafeFrom64bitLE(buf); - return n; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); - }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); - } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); - }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); - } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); - }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; - }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; - }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey - var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$m.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; - }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); - }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; - }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$m.concat([h, h, x])); - }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$m.concat([ - Buffer$m.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$m.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; - }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); - } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; - }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); - }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$m.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; - }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; - }; - return p2wpkh; - }(SingleKeyAccount)); + if (anum && bnum) { + a = +a; + b = +b; + } - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; - }; - Merkle.prototype.size = function () { - return this.leaves.length; - }; - Merkle.prototype.getLeaves = function () { - return this.leaves; - }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; - }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); - }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; - }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$m.concat([Buffer$m.from([1]), left, right])); - }; - return Merkle; - }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$m.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$m.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - if (isPowerOf2(n)) { - return n / 2; + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; - } - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md - */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$m.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; - } - /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). - */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$m.from([0, 1])); + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(psbt.getOutputAmount(i)); - tx.writeVarSlice(psbt.getOutputScript(i)); + + if (other.version === this.version) { + return 0 } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); - } - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); - }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - return NoSuchEntry; - }(Error)); - /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. - * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. - * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. - */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); - return unsafeFrom64bitLE(buf); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$m.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; - }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$m.from(k.substring(2), "hex")); + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; } - }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$m.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); - }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); - }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } } - throw new NoSuchEntry(key.toString()); + break + + default: + throw new Error(`invalid increment argument: ${release}`) } - // Make sure to return a copy, to protect the underlying data. - return Buffer$m.from(value); + this.format(); + this.raw = this.version; + return this + } } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); - keyPair.serialize(buf); + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); } - buf.writeUInt8(0); - } - function b() { - return Buffer$m.from([]); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$m.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - return unsafeTo64bitLE(n); - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); + } + + return self } - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); - } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); - } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$m.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; } - buf.writeSlice(data); - } + } - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$m.alloc(1); - buffer_1[0] = value; - return buffer_1; + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false } - if (value <= 0xffff) { - var buffer_2 = Buffer$m.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } } - var buffer = Buffer$m.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } } - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$m.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$m.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$m.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$m.concat([ - inputBuffer, - input.prevout, - Buffer$m.from([0x00]), - input.sequence, - ]) - : Buffer$m.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$m.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$m.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$m.alloc(0), - transaction.extraData || Buffer$m.alloc(0), - ]); + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; } - return Buffer$m.concat([ - transaction.version, - timestamp ? timestamp : Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver$2.major(appAndVersion.version) >= 2); - } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime != undefined) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$m.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence != undefined) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType != undefined) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - return [2 /*return*/]; - } - }); - }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } } + var range = Range$a; - var id$1 = 0; - var subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch(obj); + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = function (cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$1('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } - catch (e) { - console.error(e); + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; - } - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log, - listen: listen - }); + debug$1('caret return', ret); + return ret + }) + }; - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - return t; - }; - return __assign$4.apply(this, arguments); + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$1('xRange return', ret); + + return ret + }) }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); - } - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } } - } - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; + this.value = this.operator + this.semver.version; } - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; + debug('comp', this); } - }; - var browser = invariant; + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - }; - var __values$7 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$m.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$m.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$m.from([0x00]) - : Buffer$m.alloc(0); - data = Buffer$m.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$m.concat([ - output.amount, - isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$m.concat(endData); - extraPart = isDecred - ? data - : Buffer$m.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - }; - var __values$6 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$m.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$m.from([0x00]); - } - } - data = Buffer$m.concat([ - prefix, - inputValue, - isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$m.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) } - hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$m.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$m.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([sigHashType]), - ]) - : Buffer$m.concat([ - pathsBuffer, - Buffer$m.from([0x00]), - lockTimeBuffer, - Buffer$m.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$m.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } } + }); + return max }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } }); - } + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver$2.gte(version, "1.4.0"); - } + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$m.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$m.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$m.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$m.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$m.concat([ - Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$m.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$m.concat([ - Buffer$m.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer$m.alloc(1); - keySize = Buffer$m.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$m.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$m.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$m.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$m.concat([ - Buffer$m.from("02", "hex"), - Buffer$m.from([signatures[i].length]), - signatures[i], - Buffer$m.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$m.concat([witness, tmpScriptData]); - } - result = Buffer$m.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$m.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$m.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$m.alloc(0), - targetTransaction.extraData || Buffer$m.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$m.concat([ - decredWitness_1, - Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0xff, 0xff, 0xff, 0xff]), - Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$m.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } - }); - }); - } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$m.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + + function unsafeTo64bitLE(n) { + // we want to represent the input as a 8-bytes array + if (n > Number.MAX_SAFE_INTEGER) { + throw new Error("Can't convert numbers > MAX_SAFE_INT"); } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + var byteArray = Buffer$k.alloc(8, 0); + for (var index = 0; index < byteArray.length; index++) { + var byte = n & 0xff; + byteArray[index] = byte; + n = (n - byte) / 256; + } + return byteArray; + } + function unsafeFrom64bitLE(byteArray) { + var value = 0; + if (byteArray.length != 8) { + throw new Error("Expected Bufffer of lenght 8"); + } + if (byteArray[7] != 0) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + if (byteArray[6] > 0x1f) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + for (var i = byteArray.length - 1; i >= 0; i--) { + value = value * 256 + byteArray[i]; + } + return value; + } + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$k.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + var bytes = unsafeTo64bitLE(i); + this.writeSlice(bytes); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$k.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$k.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var buf = this.readSlice(8); + var n = unsafeFrom64bitLE(buf); + return n; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - startTime = Date.now(); - targetTransaction = { - inputs: [], - timestamp: Buffer$m.alloc(0), - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$m.from(trustedInput, "hex") - : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$m.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; + var __extends$4 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; } - }; + return BaseAccount; + }()); /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$4(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$4(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$4(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$k.concat([h, h, x])); }; /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); } - return createTransaction(this.transport, arg); + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$k.concat([ + Buffer$k.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$4(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); } - return signP2SHTransaction(this.transport, arg); + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$m.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$m.concat([ - Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$4(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$m.concat([ - asBufferUInt32BE(version), - Buffer$m.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$k.from([0]), buf, hashFunction); } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$k.concat([bufA, bufB])); } - function hash256(buffer) { - return sha256(sha256(buffer)); + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); } - function hash160(buffer) { - return ripemd160(sha256(buffer)); + function isPowerOf2(n) { + return (n & (n - 1)) == 0; } /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md */ - var MerkleMap = /** @class */ (function () { + var WalletPolicy = /** @class */ (function () { /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length + * For now, we only support default descriptor templates. */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$m.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); }; - return MerkleMap; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$k.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + } - var __extends$2 = (undefined && undefined.__extends) || (function () { + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$k.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(psbt.getOutputAmount(i)); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } + + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36513,837 +35523,725 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - finally { if (e) throw e.error; } - } - return ar; + return t; + }; + return __assign$5.apply(this, arguments); }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; } - return to.concat(ar || Array.prototype.slice.call(from)); - }; + return NoSuchEntry; + }(Error)); /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); }; - return MerkelizedPsbt; - }(PsbtV2)); - - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { - } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; - } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$m.from(request.subarray(1))); - this.progressCallback(); - return Buffer$m.from(""); + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = Buffer$m.from(request.subarray(1)); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$m.from([known_preimage[i]])); - } - } - return Buffer$m.concat([ - preimage_len_varint, - Buffer$m.from([payload_size]), - Buffer$m.from(known_preimage.subarray(0, payload_size)), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; - } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = Buffer$m.from(request.subarray(1)); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$m.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$m.from([proof.length]), - Buffer$m.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); + return unsafeFrom64bitLE(buf); }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; - } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = Buffer$m.from(request.subarray(1)); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + }; + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); } - } - return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); + }); }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; - } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); } - if (this.queue.length === 0) { - throw new Error("No elements to get"); + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$m.concat(__spreadArray$1([ - Buffer$m.from([n_returned_elements]), - Buffer$m.from([element_len]) - ], __read$1(returned_elements), false)); }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$k.from(k.substring(2), "hex")); } - finally { if (e_1) throw e_1.error; } - } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; + }); + return result; }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); - this.addKnownPreimage(preimage); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); - } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$k.from([])); + this.globalMap.set(key.toString(), value); }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); - } - return cmd.execute(request); + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); }; - return ClientCommandInterpreter; - }()); - - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ - Buffer$m.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$m.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ - Buffer$m.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - Buffer$m.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); }); }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.from([]))]; - }); + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); }; - return AppClient; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); + }; + return PsbtV2; }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); + // Make sure to return a copy, to protect the underlying data. + return Buffer$k.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); + }; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); + keyPair.serialize(buf); } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + buf.writeUInt8(0); + } + function b() { + return Buffer$k.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$k.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + return unsafeTo64bitLE(n); + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input ".concat(i, " present")); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); + } + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; + psbt.deleteInputEntries(inputIndex, keyTypes); } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$m.alloc(0); - var nExpiryHeight = Buffer$m.alloc(0); - var nVersionGroupId = Buffer$m.alloc(0); - var extraData = Buffer$m.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer$m.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$k.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$m.alloc(0); - var tree = Buffer$m.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; } - else { - locktime = transaction.slice(offset, offset + 4); + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$k.alloc(1); + buffer_1[0] = value; + return buffer_1; } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; + if (value <= 0xffff) { + var buffer_2 = Buffer$k.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; } - if (hasExtraData) { - extraData = transaction.slice(offset); + var buffer = Buffer$k.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$k.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$k.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$k.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$k.concat([ + inputBuffer, + input.prevout, + Buffer$k.from([0x00]), + input.sequence, + ]) + : Buffer$k.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$k.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$k.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$k.alloc(0), + transaction.extraData || Buffer$k.alloc(0), + ]); } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; + return Buffer$k.concat([ + transaction.version, + timestamp ? timestamp : Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); } - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37352,7 +36250,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37379,712 +36277,587 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } /** - * Bitcoin API. + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; } /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description * - * - legacy format with 44' paths + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** * - * - p2sh format with 49' paths + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. * - * - bech32 format with 84' paths + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: * - * - cashaddr in case of Bitcoin Cash + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + * We opted for adding a new function, which can greatly simplify client code. */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); + } + return [2 /*return*/, xpub]; + } + }); }); }; /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); }; /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * Get an address for the specified path. * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); }); }; /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime != undefined) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); }; /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$e(this, function (_a) { switch (_a.label) { case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; } }); }); }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence != undefined) { + psbt.setInputSequence(i, sequence); } - else { - return [2 /*return*/, this["new"]()]; + if (sigHashType != undefined) { + psbt.setInputSighashType(i, sigHashType); } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; } }); }); }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input ".concat(k)); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); + }); }; - return Btc; + return BtcNew; }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; - } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; - } - return false; + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); } - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } + var id$1 = 0; + var subscribers = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch(obj); }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = function (cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } + subscribers[i](log); } catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + console.error(e); } - finally { if (e_1) throw e_1.error; } - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); - var AmountRequired = createCustomErrorClass("AmountRequired"); - var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass("NetworkDown"); - var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass("FeeRequired"); - var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); - var SyncError = createCustomErrorClass("SyncError"); - var PairingFailed = createCustomErrorClass("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); - var DBNotReset = createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; } } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - var libEs = /*#__PURE__*/Object.freeze({ + var index = /*#__PURE__*/Object.freeze({ __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass, - addCustomErrorDeserializer: addCustomErrorDeserializer, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError, - StatusCodes: StatusCodes, - getAltStatusMessage: getAltStatusMessage, - TransportStatusError: TransportStatusError + log: log, + listen: listen }); - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var browser = invariant; + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38093,7 +36866,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38120,32 +36893,7 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values = (undefined && undefined.__values) || function(o) { + var __values$7 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38156,2341 +36904,3596 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$m.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$m.concat([ - Buffer$m.from([cla, ins, p1, p2]), - Buffer$m.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError(sw); - } - return [2 /*return*/, response]; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$k.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; - } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + else { + data = transactionData; } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$k.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ + transaction.version, + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$k.from([0x00]) + : Buffer$k.alloc(0); + data = Buffer$k.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); - - var hidFraming$1 = {}; - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$m.alloc(2); - b.writeUInt16BE(value, 0); - return b; + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$k.concat([ + output.amount, + isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$k.concat(endData); + extraPart = isDecred + ? data + : Buffer$k.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); } - var initialAcc = { - data: Buffer$m.alloc(0), - dataLength: 0, - sequence: 0 + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$m.concat([ - data, - Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$m.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$m.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$m.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - exports["default"] = createHIDframing; - - }(hidFraming$1)); - - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); - - var re$5 = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; - - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; - - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; - - const debug$3 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$3; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$k.concat([ + transaction.version, + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$k.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$k.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$k.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$k.from([0x00]); + } + } + data = Buffer$k.concat([ + prefix, + inputValue, + isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$k.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$k.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$k.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$k.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([sigHashType]), + ]) + : Buffer$k.concat([ + pathsBuffer, + Buffer$k.from([0x00]), + lockTimeBuffer, + Buffer$k.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$k.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; - if (anum && bnum) { - a = +a; - b = +b; - } + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); }; + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$k.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$k.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$k.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$k.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$k.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$k.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$k.concat([ + Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$k.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$k.concat([ + Buffer$k.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$k.alloc(1); + keySize = Buffer$k.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$k.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$k.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$k.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$k.concat([ + Buffer$k.from("02", "hex"), + Buffer$k.from([signatures[i].length]), + signatures[i], + Buffer$k.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$k.concat([witness, tmpScriptData]); + } + result = Buffer$k.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$k.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$k.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$k.alloc(0), + targetTransaction.extraData || Buffer$k.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$k.concat([ + decredWitness_1, + Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0xff, 0xff, 0xff, 0xff]), + Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$k.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; - - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); - - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) - } - - debug$2('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); - } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$k.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$k.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$k.from(trustedInput, "hex") + : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$k.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } + }); + }); } - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; - - var parse_1 = parse$5; - - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; - - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; - - const SemVer$c = semver$1; - - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - - const parse$2 = parse_1; - const eq$1 = eq_1; - - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - } - } - return defaultResult // may be undefined - } + return t; + }; + return __assign$1.apply(this, arguments); }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; - - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; - - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; - - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - var prerelease_1 = prerelease; - - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; - - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; - var compareBuild_1 = compareBuild$2; - - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; - - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; - - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; - - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; - - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; - - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; - - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; - - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; - - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt$2(a, b, loose) - - case '>=': - return gte$1(a, b, loose) - - case '<': - return lt$1(a, b, loose) - - case '<=': - return lte$1(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$k.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$k.concat([ + Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$k.concat([ + asBufferUInt32BE(version), + Buffer$k.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$k.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; }; - var coerce_1 = coerce; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } + finally { if (e) throw e.error; } } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false - } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$k.from(request.subarray(1))); + this.progressCallback(); + return Buffer$k.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = Buffer$k.from(request.subarray(1)); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$k.from([known_preimage[i]])); + } + } + return Buffer$k.concat([ + preimage_len_varint, + Buffer$k.from([payload_size]), + Buffer$k.from(known_preimage.subarray(0, payload_size)), + ]); + } + throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = Buffer$k.from(request.subarray(1)); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$k.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$k.from([proof.length]), + Buffer$k.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = Buffer$k.from(request.subarray(1)); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$k.concat(__spreadArray$1([ + Buffer$k.from([n_returned_elements]), + Buffer$k.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code ".concat(cmd.code)); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } } - return false - } - } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code ".concat(cmdCode)); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); - return comp }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$1('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - - debug$1('tilde return', ret); - return ret - }) }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$1('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$1('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$1('caret return', ret); - return ret - }) - }; - - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$k.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$k.alloc(32, 0), + Buffer$k.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } + } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$k.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; + }); + }); + }; + return AppClient; + }()); - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); } - - debug$1('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; - - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput ".concat(i, ":"); + str += " prevout ".concat(prevout.toString("hex")); + str += " script ".concat(script.toString("hex")); + str += " sequence ".concat(sequence.toString("hex")); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput ".concat(i, ":"); + str += " amount ".concat(amount.toString("hex")); + str += " script ".concat(script.toString("hex")); + }); + return str; + } - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$k.alloc(0); + var nExpiryHeight = Buffer$k.alloc(0); + var nVersionGroupId = Buffer$k.alloc(0); + var extraData = Buffer$k.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$k.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$k.alloc(0); + var tree = Buffer$k.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; } - } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 - } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); } - - debug('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); } - - debug('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) + else { + locktime = transaction.slice(offset, offset + 4); } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); + if (hasExtraData) { + extraData = transaction.slice(offset); } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + return t; + } - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 84' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; + return Btc; + }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } + return false; } - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; - - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } - } - }); - return max - }; - var maxSatisfying_1 = maxSatisfying; + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); - } - } - }); - return min + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; } - } - return true + return new Error(String(object)); }; - - var outside_1 = outside$2; - - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; - - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; - - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } } - } - if (min) - set.push([min, null]); + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range + var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); + var AmountRequired = createCustomErrorClass("AmountRequired"); + var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass("NetworkDown"); + var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass("FeeRequired"); + var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); + var SyncError = createCustomErrorClass("SyncError"); + var PairingFailed = createCustomErrorClass("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); + var DBNotReset = createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass, + addCustomErrorDeserializer: addCustomErrorDeserializer, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError, + StatusCodes: StatusCodes, + getAltStatusMessage: getAltStatusMessage, + TransportStatusError: TransportStatusError + }); - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false + finally { if (e) throw e.error; } } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + return to.concat(ar || Array.prototype.slice.call(from)); + }; + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$k.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$k.concat([ + Buffer$k.from([cla, ins, p1, p2]), + Buffer$k.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; + } + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); + }; + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); + }; + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); + }; + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + }; + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } + } + }; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + var hidFraming$1 = {}; - return true - }; + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$k.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$k.alloc(0), + dataLength: 0, + sequence: 0 }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$k.concat([ + data, + Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$k.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$k.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$k.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; }; + exports["default"] = createHIDframing; - var subset_1 = subset; + }(hidFraming$1)); - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -40926,7 +40929,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$m.from(r.data.buffer); + buffer = Buffer$k.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: From 4c9ce900e3720aea2eaf38f1126b6863a3929a4b Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 14 Feb 2022 17:47:34 +1100 Subject: [PATCH 56/78] add timestamps for peercoin --- js/ledger.js | 27671 ++++++++++++++++++++++++------------------------- 1 file changed, 13637 insertions(+), 14034 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index c20e37ca..be5d408b 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -999,7 +999,7 @@ var toString = {}.toString; - var isArray$3 = Array.isArray || function (arr) { + var isArray$1 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1029,12 +1029,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$k.TYPED_ARRAY_SUPPORT + return Buffer$m.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1043,14 +1043,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$k(length); + that = new Buffer$m(length); } that.length = length; } @@ -1068,9 +1068,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$k (arg, encodingOrOffset, length) { - if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { - return new Buffer$k(arg, encodingOrOffset, length) + function Buffer$m (arg, encodingOrOffset, length) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { + return new Buffer$m(arg, encodingOrOffset, length) } // Common case. @@ -1082,18 +1082,18 @@ } return allocUnsafe(this, arg) } - return from(this, arg, encodingOrOffset, length) + return from$1(this, arg, encodingOrOffset, length) } - Buffer$k.poolSize = 8192; // not used by this implementation + Buffer$m.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$k._augment = function (arr) { - arr.__proto__ = Buffer$k.prototype; + Buffer$m._augment = function (arr) { + arr.__proto__ = Buffer$m.prototype; return arr }; - function from (that, value, encodingOrOffset, length) { + function from$1 (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1117,13 +1117,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$k.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) + Buffer$m.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { - Buffer$k.prototype.__proto__ = Uint8Array.prototype; - Buffer$k.__proto__ = Uint8Array; + if (Buffer$m.TYPED_ARRAY_SUPPORT) { + Buffer$m.prototype.__proto__ = Uint8Array.prototype; + Buffer$m.__proto__ = Uint8Array; } function assertSize (size) { @@ -1154,14 +1154,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$k.alloc = function (size, fill, encoding) { + Buffer$m.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) { + if (!Buffer$m.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1172,13 +1172,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$k.allocUnsafe = function (size) { + Buffer$m.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$k.allocUnsafeSlow = function (size) { + Buffer$m.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1187,7 +1187,7 @@ encoding = 'utf8'; } - if (!Buffer$k.isEncoding(encoding)) { + if (!Buffer$m.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1234,10 +1234,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$m.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$3(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1284,12 +1284,12 @@ } return length | 0 } - Buffer$k.isBuffer = isBuffer; + Buffer$m.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$k.compare = function compare (a, b) { + Buffer$m.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1312,7 +1312,7 @@ return 0 }; - Buffer$k.isEncoding = function isEncoding (encoding) { + Buffer$m.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1331,13 +1331,13 @@ } }; - Buffer$k.concat = function concat (list, length) { - if (!isArray$3(list)) { + Buffer$m.concat = function concat (list, length) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$k.alloc(0) + return Buffer$m.alloc(0) } var i; @@ -1348,7 +1348,7 @@ } } - var buffer = Buffer$k.allocUnsafe(length); + var buffer = Buffer$m.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1404,7 +1404,7 @@ } } } - Buffer$k.byteLength = byteLength$1; + Buffer$m.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1478,7 +1478,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$k.prototype._isBuffer = true; + Buffer$m.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1486,7 +1486,7 @@ b[m] = i; } - Buffer$k.prototype.swap16 = function swap16 () { + Buffer$m.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1497,7 +1497,7 @@ return this }; - Buffer$k.prototype.swap32 = function swap32 () { + Buffer$m.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1509,7 +1509,7 @@ return this }; - Buffer$k.prototype.swap64 = function swap64 () { + Buffer$m.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1523,20 +1523,20 @@ return this }; - Buffer$k.prototype.toString = function toString () { + Buffer$m.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$k.prototype.equals = function equals (b) { + Buffer$m.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$k.compare(this, b) === 0 + return Buffer$m.compare(this, b) === 0 }; - Buffer$k.prototype.inspect = function inspect () { + Buffer$m.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1546,7 +1546,7 @@ return '' }; - Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1645,7 +1645,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$k.from(val, encoding); + val = Buffer$m.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1657,7 +1657,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$k.TYPED_ARRAY_SUPPORT && + if (Buffer$m.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1727,15 +1727,15 @@ return -1 } - Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1786,7 +1786,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$k.prototype.write = function write (string, offset, length, encoding) { + Buffer$m.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1858,7 +1858,7 @@ } }; - Buffer$k.prototype.toJSON = function toJSON () { + Buffer$m.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2011,7 +2011,7 @@ return res } - Buffer$k.prototype.slice = function slice (start, end) { + Buffer$m.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2033,12 +2033,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$k.prototype; + newBuf.__proto__ = Buffer$m.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$k(sliceLen, undefined); + newBuf = new Buffer$m(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2055,7 +2055,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2070,7 +2070,7 @@ return val }; - Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2086,22 +2086,22 @@ return val }; - Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2110,7 +2110,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2119,7 +2119,7 @@ this[offset + 3]) }; - Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2137,7 +2137,7 @@ return val }; - Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2155,25 +2155,25 @@ return val }; - Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2182,7 +2182,7 @@ (this[offset + 3] << 24) }; - Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2191,22 +2191,22 @@ (this[offset + 3]) }; - Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2217,7 +2217,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2236,7 +2236,7 @@ return offset + byteLength }; - Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2255,11 +2255,11 @@ return offset + byteLength }; - Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2272,11 +2272,11 @@ } } - Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2285,11 +2285,11 @@ return offset + 2 }; - Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2305,11 +2305,11 @@ } } - Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2320,11 +2320,11 @@ return offset + 4 }; - Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2335,7 +2335,7 @@ return offset + 4 }; - Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2358,7 +2358,7 @@ return offset + byteLength }; - Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2381,21 +2381,21 @@ return offset + byteLength }; - Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2404,11 +2404,11 @@ return offset + 2 }; - Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2417,11 +2417,11 @@ return offset + 2 }; - Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2432,12 +2432,12 @@ return offset + 4 }; - Buffer$k.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$m.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; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$m.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2461,11 +2461,11 @@ return offset + 4 } - Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2477,16 +2477,16 @@ return offset + 8 } - Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2518,7 +2518,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2538,7 +2538,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$k.prototype.fill = function fill (val, start, end, encoding) { + Buffer$m.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2558,7 +2558,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2587,7 +2587,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$k(val, encoding).toString()); + : utf8ToBytes(new Buffer$m(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -2763,102 +2763,13 @@ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } - /* - * Bitcoin BIP32 path helpers - * (C) 2016 Alex Beregszaszi - */ - - const HARDENED = 0x80000000; - - var BIPPath = function (path) { - if (!Array.isArray(path)) { - throw new Error('Input must be an Array') - } - if (path.length === 0) { - throw new Error('Path must contain at least one level') - } - for (var i = 0; i < path.length; i++) { - if (typeof path[i] !== 'number') { - throw new Error('Path element is not a number') - } - } - this.path = path; - }; - - BIPPath.validatePathArray = function (path) { - try { - BIPPath.fromPathArray(path); - return true - } catch (e) { - return false - } - }; - - BIPPath.validateString = function (text, reqRoot) { - try { - BIPPath.fromString(text, reqRoot); - return true - } catch (e) { - return false - } - }; - - BIPPath.fromPathArray = function (path) { - return new BIPPath(path) - }; - - BIPPath.fromString = function (text, reqRoot) { - // skip the root - if (/^m\//i.test(text)) { - text = text.slice(2); - } else if (reqRoot) { - throw new Error('Root element is required') - } - - var path = text.split('/'); - var ret = new Array(path.length); - for (var i = 0; i < path.length; i++) { - var tmp = /(\d+)([hH\']?)/.exec(path[i]); - if (tmp === null) { - throw new Error('Invalid input') - } - ret[i] = parseInt(tmp[1], 10); - - if (ret[i] >= HARDENED) { - throw new Error('Invalid child index') - } + var src$2 = {}; - if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { - ret[i] += HARDENED; - } else if (tmp[2].length != 0) { - throw new Error('Invalid modifier') - } - } - return new BIPPath(ret) - }; - - BIPPath.prototype.toPathArray = function () { - return this.path - }; - - BIPPath.prototype.toString = function (noRoot, oldStyle) { - var ret = new Array(this.path.length); - for (var i = 0; i < this.path.length; i++) { - var tmp = this.path[i]; - if (tmp & HARDENED) { - ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); - } else { - ret[i] = tmp; - } - } - return (noRoot ? '' : 'm/') + ret.join('/') - }; + var src$1 = {}; - BIPPath.prototype.inspect = function () { - return 'BIPPath <' + this.toString() + '>' - }; + var bip32$1 = {}; - var bip32Path = BIPPath; + var crypto$5 = {}; var inherits_browser = {exports: {}}; @@ -5021,6 +4932,8 @@ }; }(safeBuffer, safeBuffer.exports)); + var readableBrowser = {exports: {}}; + // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5156,23 +5069,23 @@ }; var title = 'browser'; var platform = 'browser'; - var browser$5 = true; + var browser$6 = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config = {}; + var config$1 = {}; - function noop() {} + function noop$2() {} - var on = noop; - var addListener = noop; - var once$1 = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; + var on = noop$2; + var addListener = noop$2; + var once$3 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; function binding(name) { throw new Error('process.binding is not supported'); @@ -5220,14 +5133,14 @@ var process = { nextTick: nextTick, title: title, - browser: browser$5, + browser: browser$6, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, - once: once$1, + once: once$3, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -5239,12 +5152,10 @@ hrtime: hrtime, platform: platform, release: release, - config: config, + config: config$1, uptime: uptime }; - var readable = {exports: {}}; - var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; @@ -5280,7 +5191,7 @@ EventEmitter.init.call(this); } events.exports = EventEmitter; - events.exports.once = once; + events.exports.once = once$2; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; @@ -5672,7 +5583,7 @@ return ret; } - function once(emitter, name) { + function once$2(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); @@ -5723,9522 +5634,7380 @@ var EventEmitter$1 = events.exports; - var inherits$h; - if (typeof Object.create === 'function'){ - inherits$h = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$h = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$i = inherits$h; + var streamBrowser = events.exports.EventEmitter; - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString$1(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + var _nodeResolve_empty = {}; - 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$1(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - } + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); - // 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined$1(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + 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; } - return deprecated; - } + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined$1(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - } + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - /** - * 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$1(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined$1(ctx.depth)) ctx.depth = 2; - if (isUndefined$1(ctx.colors)) ctx.colors = false; - if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - // 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] - }; + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - // 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 _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + var _require$2 = buffer, + Buffer$l = _require$2.Buffer; - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + var _require2 = require$$3, + inspect$1 = _require2.inspect; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } + var custom = inspect$1 && inspect$1.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$l.prototype.copy.call(src, target, offset); } + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); - function stylizeNoColor(str, styleType) { - return str; - } + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$l.alloc(0); + var ret = Buffer$l.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; - function arrayToHash(array) { - var hash = {}; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. - return hash; - } + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } - 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$1(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== 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$1(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } + break; + } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + ++c; + } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$l.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + break; + } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError$1(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + ++c; + } - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction$1(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate$1(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError$1(value)) { - return formatError(value); + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect$1(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); } - } + }]); - var base = '', array = false, braces = ['{', '}']; + return BufferList; + }(); - // Make Array say that they are Array - if (isArray$2(value)) { - array = true; - braces = ['[', ']']; - } + function destroy(err, cb) { + var _this = this; - // Make functions say that they are functions - if (isFunction$1(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - // Make RegExps say that they are RegExps - if (isRegExp$1(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); + } + } - // Make dates with properties first say the date - if (isDate$1(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - // Make error with message first say the error - if (isError$1(value)) { - base = ' ' + formatError(value); - } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; } - if (recurseTimes < 0) { - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); } else { - return ctx.stylize('[Object]', 'special'); + nextTick(emitCloseNT, _this); } - } - - 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); - }); - } + return this; + } - ctx.seen.pop(); + function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } - return reduceToSingleString(output, base, braces); + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - function formatPrimitive(ctx, value) { - if (isUndefined$1(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); + 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; } - if (isNumber$1(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean$1(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull$1(value)) - return ctx.stylize('null', 'null'); } + function emitErrorNT(self, err) { + self.emit('error', err); + } - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - 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; - } + var errorsBrowser = {}; + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - 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 + ']'; + var codes = {}; + + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull$1(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'); - } - } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; } else { - str = ctx.stylize('[Circular]', 'special'); + return message(arg1, arg2, arg3); } } - if (isUndefined$1(name)) { - if (array && key.match(/^\d+$/)) { - return str; + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; } - 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'); + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); + return "of ".concat(thing, " ").concat(expected[0]); } + } else { + return "of ".concat(thing, " ").concat(String(expected)); } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - return name + ': ' + str; - } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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]; + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + return str.substring(this_len - search.length, this_len) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$2(ar) { - return Array.isArray(ar); - } + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } - function isBoolean$1(arg) { - return typeof arg === 'boolean'; + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } } - function isNull$1(arg) { - return arg === null; - } + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; - function isNumber$1(arg) { - return typeof arg === 'number'; - } + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } - function isString$1(arg) { - return typeof arg === 'string'; - } + var msg; - function isUndefined$1(arg) { - return arg === void 0; - } + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } - function isRegExp$1(re) { - return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; - } + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + errorsBrowser.codes = codes; - function isObject$1(arg) { - return typeof arg === 'object' && arg !== null; - } + var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; - function isDate$1(d) { - return isObject$1(d) && objectToString$1(d) === '[object Date]'; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } - function isError$1(e) { - return isObject$1(e) && - (objectToString$1(e) === '[object Error]' || e instanceof Error); - } - - function isFunction$1(arg) { - return typeof arg === 'function'; - } + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - function objectToString$1(o) { - return Object.prototype.toString.call(o); - } + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; + return Math.floor(hwm); + } // Default value - 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); - } - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; + return state.objectMode ? 16 : 16 * 1024; } - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; + var state = { + getHighWaterMark: getHighWaterMark$2 }; - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + /** + * Module exports. + */ - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + var browser$5 = deprecate$1; - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; + function deprecate$1 (fn, msg) { + if (config('noDeprecation')) { + return fn; } - return ret; - }; - - var string_decoder = {}; - - var StringDecoder_1; - // 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$j = buffer.Buffer; + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - var isBufferEncoding = Buffer$j.isEncoding - || function(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; - } - }; + return deprecated; + } + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; } + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + var _stream_writable = Writable$2; + // there will be only 2 of these for each stream - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$j(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; + function CorkedRequest$1(state) { + var _this = this; - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$2.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; + this.next = null; + this.entry = null; - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + /**/ - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + var Duplex$4; + /**/ - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + Writable$2.WritableState = WritableState$1; + /**/ - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + var internalUtil = { + deprecate: browser$5 + }; + /**/ - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + /**/ - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + var Stream$2 = streamBrowser; + /**/ - charStr += buffer.toString(this.encoding, 0, end); - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + var Buffer$k = buffer.Buffer; - // or just emit the charStr - return charStr; - }; + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$k.from(chunk); + } - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + function _isUint8Array$1(obj) { + return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; + } - // See http://en.wikipedia.org/wiki/UTF-8#Description + var destroyImpl$1 = destroy_1; - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - StringDecoder$2.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + inherits_browser.exports(Writable$2, Stream$2); - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + function nop$1() {} - return res; - }; + function WritableState$1(options, stream, isDuplex) { + Duplex$4 = Duplex$4 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - Readable$2.ReadableState = ReadableState$1; + this.finalCalled = false; // drain event flag. - var debug$4 = debuglog('stream'); - inherits$i(Readable$2, EventEmitter$1); + this.needDrain = false; // at the start of calling end() - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState$1(options, stream) { + this.ending = false; // when end() has been called, and returned - options = options || {}; + this.ended = false; // when 'finish' is emitted - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + this.finished = false; // has it been destroyed - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + this.length = 0; // a flag to see when we're in the middle of a write. - // a flag to be able to tell if the onwrite cb is called immediately, + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. - this.sync = true; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + this.writecb = null; // the amount that is being written when _write is called. - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable$2(options) { + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - if (!(this instanceof Readable$2)) return new Readable$2(options); + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - this._readableState = new ReadableState$1(options, this); + this.prefinished = false; // True if the error was already emitted and should not be thrown again - // legacy - this.readable = true; + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - if (options && typeof options.read === 'function') this._read = options.read; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - EventEmitter$1.call(this); + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest$1(this); } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$2.prototype.push = function (chunk, encoding) { - var state = this._readableState; + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$k.from(chunk, encoding); - encoding = ''; - } + while (current) { + out.push(current); + current = current.next; } - return readableAddChunk$1(this, state, chunk, encoding, false); + return out; }; - // Unshift should *always* be something directly out of read() - Readable$2.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk$1(this, state, chunk, '', true); - }; + (function () { + try { + Object.defineProperty(WritableState$1.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. - Readable$2.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; - function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid$1(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + var realHasInstance; - if (!addToFront) state.reading = false; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$2, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$2) return false; + return object && object._writableState instanceof WritableState$1; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + function Writable$2(options) { + Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$4; + if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); + this._writableState = new WritableState$1(options, this, isDuplex); // legacy. - if (state.needReadable) emitReadable$1(stream); - } - } + this.writable = true; - maybeReadMore$1(stream, state); - } - } else if (!addToFront) { - state.reading = false; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - return needMoreData$1(state); - } + Stream$2.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData$1(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } - // backwards compatibility. - Readable$2.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; + Writable$2.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); }; - // Don't raise the hwm > 8MB - var MAX_HWM$1 = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM$1) { - n = MAX_HWM$1; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. + + + function validChunk$1(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); } - return n; - } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; + + return true; } - // you can override either this method, or the async _read(n) below. - Readable$2.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - if (n !== 0) state.emittedReadable = false; + var isBuf = !state.objectMode && _isUint8Array$1(chunk); - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; + if (isBuf && !Buffer$k.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); } - n = howMuchToRead$1(n, state); + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop$1; + if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); } + return ret; + }; - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + Writable$2.prototype.cork = function () { + this._writableState.corked++; + }; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$4('need readable', doRead); + Writable$2.prototype.uncork = function () { + var state = this._writableState; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); } + }; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead$1(nOrig, state); + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); } + }); - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$k.from(chunk, encoding); + } - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; + return chunk; + } + + Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk$1(state, chunk, encoding); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable$1(this); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } } - if (ret !== null) this.emit('data', ret); + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - return ret; - }; + if (!ret) state.needDrain = true; - function chunkInvalid$1(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; - function onEofChunk$1(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } + + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable$1(stream); + return ret; } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable$1(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); - } + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - function emitReadable_$1(stream) { - debug$4('emit readable'); - stream.emit('readable'); - flow$1(stream); - } + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe$1, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe$1(stream, state); } } - function maybeReadMore_$1(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$2.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate$1(state); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state) || stream.destroyed; - Readable$2.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; + if (sync) { + nextTick(afterWrite$1, stream, state, finished, cb); + } else { + afterWrite$1(stream, state, finished, cb); + } } - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + } - var doEnd = (!pipeOpts || pipeOpts.end !== false); + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$4('onunpipe'); - if (readable === src) { - cleanup(); - } + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } + } // if there's something in the buffer waiting, then process it - function onend() { - debug$4('onend'); - dest.end(); - } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - var cleanedUp = false; - function cleanup() { - debug$4('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; - cleanedUp = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + buffer.allBuffers = allBuffers; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$4('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; } - src.pause(); } - } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + if (entry === null) state.lastBufferedRequest = null; } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); + }; - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); - } + Writable$2.prototype._writev = null; - // tell the dest that it's being piped to - dest.emit('pipe', src); + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return dest; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable$1(this, state, cb); + return this; }; - function pipeOnDrain$1(src) { - return function () { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow$1(src); + Object.defineProperty(Writable$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); } - }; + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); } - Readable$2.prototype.unpipe = function (dest) { - var state = this._readableState; + function prefinish$2(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + if (need) { + prefinish$2(stream, state); - if (!dest) dest = state.pipes; + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } } - // slow case. multiple pipe destinations. + return need; + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } - // try to find the right one. - var i = indexOf$1(state.pipes, dest); - if (i === -1) return this; + state.ended = true; + stream.writable = false; + } - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - dest.emit('unpipe', this); + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - return this; - }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$2.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + state.corkedRequestsFree.next = corkReq; + } - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable$1(this); - } + Object.defineProperty(Writable$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; } + + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; } + }); + Writable$2.prototype.destroy = destroyImpl$1.destroy; + Writable$2.prototype._undestroy = destroyImpl$1.undestroy; - return res; + Writable$2.prototype._destroy = function (err, cb) { + cb(err); }; - Readable$2.prototype.addListener = Readable$2.prototype.on; - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); - } + /**/ - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$2.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$4('resume'); - state.flowing = true; - resume(this, state); + var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); } - return this; + + return keys; }; + /**/ - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + + var _stream_duplex = Duplex$3; + + var Readable$2 = _stream_readable; + + var Writable$1 = _stream_writable; + + inherits_browser.exports(Duplex$3, Readable$2); + + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Writable$1.prototype); + + for (var v$1 = 0; v$1 < keys$1.length; v$1++) { + var method$1 = keys$1[v$1]; + if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; } } - function resume_(stream, state) { - if (!state.reading) { - debug$4('resume read 0'); - stream.read(0); - } + function Duplex$3(options) { + if (!(this instanceof Duplex$3)) return new Duplex$3(options); + Readable$2.call(this, options); + Writable$1.call(this, options); + this.allowHalfOpen = true; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend$1); + } + } } - Readable$2.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); + Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; } - return this; - }; + }); + Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer - function flow$1(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + function onend$1() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + nextTick(onEndNT$1, this); } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$2.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + function onEndNT$1(self) { + self.end(); + } - var self = this; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); + Object.defineProperty(Duplex$3.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - self.push(null); - }); - - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } + this._readableState.destroyed = value; + this._writableState.destroyed = value; } + }); - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$2(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + var string_decoder$1 = {}; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$4('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + /**/ - return self; + var Buffer$j = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$j.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; + } }; - // exposed for testing purposes only. - Readable$2._fromList = fromList$1; + 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$j.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + string_decoder$1.StringDecoder = StringDecoder$3; + function StringDecoder$3(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$j.allocUnsafe(nb); + } - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); + StringDecoder$3.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 { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + i = 0; } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; + }; - return ret; - } + StringDecoder$3.prototype.end = utf8End; - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + // Returns only complete characters in a Buffer + StringDecoder$3.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$3.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); } - return ret; + 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; } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + // 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; } - ++c; + return nb; } - list.length -= c; - return ret; + return 0; } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$k.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); + // 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'; } - break; } - ++c; } - list.length -= c; - return ret; } - function endReadable$1(stream) { - var state = stream._readableState; + // 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); + 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; + } - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + // 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); + } - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } + // 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; } - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + // 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); } - function forEach$2(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + // 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 indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + 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 -1; + return buf.toString('base64', i, buf.length - n); } - // A bit simpler than readable streams. - Writable$2.WritableState = WritableState$1; - inherits$i(Writable$2, events.exports.EventEmitter); - - function nop() {} + 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; + } - function WriteReq$1(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); } - function WritableState$1(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + callback.apply(this, args); + }; + } - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + function noop$1() {} - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - // a flag to see when we're in the middle of a write. - this.writing = false; + var writableEnded = stream._writableState && stream._writableState.finished; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite$1(stream, er); + var onerror = function onerror(err) { + callback.call(stream, err); }; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var onclose = function onclose() { + var err; - // the amount that is being written when _write is called. - this.writelen = 0; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } - // count buffered requests - this.bufferedRequestCount = 0; + var endOfStream = eos$1; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); - } + var _Object$setPrototypeO; - WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable$2(options) { + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); + var finished = endOfStream; - this._writableState = new WritableState$1(options, this); + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); - // legacy. - this.writable = true; + function createIterResult(value, done) { + return { + value: value, + done: done + }; + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; - if (typeof options.writev === 'function') this._writev = options.writev; + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } } + } - events.exports.EventEmitter.call(this); + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); } - // Otherwise people can pipe Writable streams, which is just wrong. - Writable$2.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - function writeAfterEnd$1(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); + iter[kHandlePromise](resolve, reject); + }, reject); + }; } - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk$1(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; - } + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + next: function next() { + var _this = this; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (error !== null) { + return Promise.reject(error); + } - if (typeof cb !== 'function') cb = nop; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } - if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, chunk, encoding, cb); + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; - return ret; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; - Writable$2.prototype.cork = function () { - var state = this._writableState; + var async_iterator = createReadableStreamAsyncIterator$1; - state.corked++; + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') }; - Writable$2.prototype.uncork = function () { - var state = this._writableState; + var _stream_readable = Readable$1; + /**/ - if (state.corked) { - state.corked--; + var Duplex$2; + /**/ - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + Readable$1.ReadableState = ReadableState$1; + /**/ - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; + events.exports.EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; }; + /**/ - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); - } - return chunk; - } + /**/ - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer$1(stream, state, chunk, encoding, cb) { - chunk = decodeChunk$1(state, chunk, encoding); - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + var Stream$1 = streamBrowser; + /**/ - state.length += len; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + var Buffer$i = buffer.Buffer; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); - } + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - return ret; + function _uint8ArrayToBuffer(chunk) { + return Buffer$i.from(chunk); } - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; + function _isUint8Array(obj) { + return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; } + /**/ - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + var debugUtil = require$$3; - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + var debug$9; + + if (debugUtil && debugUtil.debuglog) { + debug$9 = debugUtil.debuglog('stream'); + } else { + debug$9 = function debug() {}; } + /**/ - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - onwriteStateUpdate$1(state); + var BufferList$1 = buffer_list; - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state); + var destroyImpl = destroy_1; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - if (sync) { - /**/ - nextTick(afterWrite$1, stream, state, finished, cb); - /**/ - } else { - afterWrite$1(stream, state, finished, cb); - } - } - } + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } + var StringDecoder$2; + var createReadableStreamAsyncIterator; + var from; + + inherits_browser.exports(Readable$1, Stream$1); + + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener$1(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - // if there's something in the buffer waiting, then process it - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + function ReadableState$1(options, stream, isDuplex) { + Duplex$2 = Duplex$2 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + this.buffer = new BufferList$1(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - if (entry === null) state.lastBufferedRequest = null; - } + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - Writable$2.prototype._writev = null; + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + this.readingMore = false; + this.decoder = null; + this.encoding = null; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); + if (options.encoding) { + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + this.decoder = new StringDecoder$2(options.encoding); + this.encoding = options.encoding; } + } - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable$1(this, state, cb); - }; + function Readable$1(options) { + Duplex$2 = Duplex$2 || _stream_duplex; + if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + var isDuplex = this instanceof Duplex$2; + this._readableState = new ReadableState$1(options, this, isDuplex); // legacy - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } + + Stream$1.call(this); } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); + Object.defineProperty(Readable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; } - } - return need; - } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; } - state.ended = true; - stream.writable = false; - } + }); + Readable$1.prototype.destroy = destroyImpl.destroy; + Readable$1.prototype._undestroy = destroyImpl.undestroy; - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + Readable$1.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; + Readable$1.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer$i.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; } - }; - } + } else { + skipChunkCheck = true; + } - inherits$i(Duplex$2, Readable$2); + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - var keys = Object.keys(Writable$2.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; - } - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$2.call(this, options); - Writable$2.call(this, options); + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); + }; - if (options && options.readable === false) this.readable = false; + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$9('readableAddChunk', chunk); + var state = stream._readableState; - if (options && options.writable === false) this.writable = false; + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - this.once('end', onend$1); - } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; - // the no-half-open enforcer - function onend$1() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore$1(stream, state); + } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } - function onEndNT(self) { - self.end(); + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - // a transform stream is a readable/writable stream where you do - inherits$i(Transform$4, Duplex$2); - - function TransformState$1(stream) { - this.afterTransform = function (er, data) { - return afterTransform$1(stream, er, data); - }; + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable$1(stream); + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; + maybeReadMore$1(stream, state); } - function afterTransform$1(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + function chunkInvalid$1(state, chunk) { + var er; - var cb = ts.writecb; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + return er; + } - ts.writechunk = null; - ts.writecb = null; + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - if (data !== null && data !== undefined) stream.push(data); - cb(er); + Readable$1.prototype.setEncoding = function (enc) { + if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; + var decoder = new StringDecoder$2(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - Duplex$2.call(this, options); + var p = this._readableState.buffer.head; + var content = ''; - this._transformState = new TransformState$1(this); + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } - // when the writable side finishes, then flush out anything remaining. - var stream = this; + this._readableState.buffer.clear(); - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + var MAX_HWM$1 = 0x40000000; - if (typeof options.flush === 'function') this._flush = options.flush; + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done$1(stream, er); - });else done$1(stream); - }); - } + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$2.prototype.push.call(this, chunk, encoding); - }; - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$4.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$4.prototype._read = function (n) { - var ts = this._transformState; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); + if (n <= state.length) return n; // Don't have enough - function done$1(stream, er) { - if (er) return stream.emit('error', er); + if (!state.ended) { + state.needReadable = true; + return 0; + } - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + return state.length; + } // you can override either this method, or the async _read(n) below. - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + Readable$1.prototype.read = function (n) { + debug$9('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - return stream.push(null); - } + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$9('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - inherits$i(PassThrough$1, Transform$4); - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - Transform$4.call(this, options); - } + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - inherits$i(Stream$2, EventEmitter$1); - Stream$2.Readable = Readable$2; - Stream$2.Writable = Writable$2; - Stream$2.Duplex = Duplex$2; - Stream$2.Transform = Transform$4; - Stream$2.PassThrough = PassThrough$1; + var doRead = state.needReadable; + debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - // Backwards-compat with node 0.4.x - Stream$2.Stream = Stream$2; + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$9('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - function Stream$2() { - EventEmitter$1.call(this); - } + if (state.ended || state.reading) { + doRead = false; + debug$9('reading or ended', doRead); + } else if (doRead) { + debug$9('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - Stream$2.prototype.pipe = function(dest, options) { - var source = this; + if (state.length === 0) state.needReadable = true; // call internal read method - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + this._read(state.highWaterMark); - source.on('data', ondata); + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } + if (!state.reading) n = howMuchToRead$1(nOrig, state); } - dest.on('drain', ondrain); + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - dest.end(); + if (nOrig !== n && state.ended) endReadable$1(this); } + if (ret !== null) this.emit('data', ret); + return ret; + }; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + function onEofChunk$1(stream, state) { + debug$9('onEofChunk'); + if (state.ended) return; - if (typeof dest.destroy === 'function') dest.destroy(); - } + if (state.decoder) { + var chunk = state.decoder.end(); - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } - source.on('error', onerror); - dest.on('error', onerror); + state.ended = true; - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable$1(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; - source.removeListener('end', onend); - source.removeListener('close', onclose); + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_$1(stream); + } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + function emitReadable$1(stream) { + var state = stream._readableState; + debug$9('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - dest.removeListener('close', cleanup); + if (!state.emittedReadable) { + debug$9('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); } + } - source.on('end', cleanup); - source.on('close', cleanup); + function emitReadable_$1(stream) { + var state = stream._readableState; + debug$9('emitReadable_', state.destroyed, state.length, state.ended); - dest.on('close', cleanup); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - dest.emit('pipe', source); - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow$1(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream$2, - Readable: Readable$2, - Writable: Writable$2, - Duplex: Duplex$2, - Transform: Transform$4, - PassThrough: PassThrough$1, - Stream: Stream$2 - }); - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } + } + + function maybeReadMore_$1(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$9('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. - var isarray = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; + + Readable$1.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); }; - var util$5 = {}; + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - // 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. + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. + case 1: + state.pipes = [state.pipes, dest]; + break; - function isArray$1(arg) { - if (Array.isArray) { - return Array.isArray(arg); + default: + state.pipes.push(dest); + break; } - return objectToString(arg) === '[object Array]'; - } - util$5.isArray = isArray$1; - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - util$5.isBoolean = isBoolean; + state.pipesCount += 1; + debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - function isNull(arg) { - return arg === null; - } - util$5.isNull = isNull; + function onunpipe(readable, unpipeInfo) { + debug$9('onunpipe'); - function isNullOrUndefined(arg) { - return arg == null; - } - util$5.isNullOrUndefined = isNullOrUndefined; + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } - function isNumber(arg) { - return typeof arg === 'number'; - } - util$5.isNumber = isNumber; + function onend() { + debug$9('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - function isString(arg) { - return typeof arg === 'string'; - } - util$5.isString = isString; - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - util$5.isSymbol = isSymbol; + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); + var cleanedUp = false; - function isUndefined(arg) { - return arg === void 0; - } - util$5.isUndefined = isUndefined; + function cleanup() { + debug$9('cleanup'); // cleanup event handlers once the pipe is broken - function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; - } - util$5.isRegExp = isRegExp; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - util$5.isObject = isObject; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - function isDate(d) { - return objectToString(d) === '[object Date]'; - } - util$5.isDate = isDate; + src.on('data', ondata); - function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); - } - util$5.isError = isError; + function ondata(chunk) { + debug$9('ondata'); + var ret = dest.write(chunk); + debug$9('dest.write', ret); - function isFunction(arg) { - return typeof arg === 'function'; - } - util$5.isFunction = isFunction; + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$9('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - util$5.isPrimitive = isPrimitive; + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - util$5.isBuffer = buffer.Buffer.isBuffer; - function objectToString(o) { - return Object.prototype.toString.call(o); - } + function onerror(er) { + debug$9('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - // 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 _stream_readable = Readable$1; + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - /**/ - var isArray = isarray; - /**/ + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); - /**/ - var Buffer$i = buffer.Buffer; - /**/ + function onfinish() { + debug$9('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } - Readable$1.ReadableState = ReadableState; + dest.once('finish', onfinish); - var EE = events.exports.EventEmitter; + function unpipe() { + debug$9('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - /**/ - if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ - var Stream$1 = require$$1; + dest.emit('pipe', src); // start the flow if it hasn't been started already. - /**/ - var util$4 = util$5; - util$4.inherits = inherits_browser.exports; - /**/ + if (!state.flowing) { + debug$9('pipe resume'); + src.resume(); + } - var StringDecoder$1; + return dest; + }; - util$4.inherits(Readable$1, Stream$1); + function pipeOnDrain$1(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$9('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; - function ReadableState(options, stream) { - options = options || {}; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow$1(src); + } + }; + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + if (state.pipesCount === 0) return this; // just one destination. most common case. - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + return this; + } // try to find the right one. - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + var index = indexOf$1(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); + var state = this._readableState; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - function Readable$1(options) { - if (!(this instanceof Readable$1)) - return new Readable$1(options); + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$9('on readable', state.length, state.reading); - this._readableState = new ReadableState(options, this); + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } + } - // legacy - this.readable = true; + return res; + }; - Stream$1.call(this); - } + Readable$1.prototype.addListener = Readable$1.prototype.on; - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$1.prototype.push = function(chunk, encoding) { - var state = this._readableState; + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$1.prototype.removeListener.call(this, ev, fn); - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer$i(chunk, encoding); - encoding = ''; - } + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); } - return readableAddChunk(this, state, chunk, encoding, false); + return res; }; - // Unshift should *always* be something directly out of read() - Readable$1.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } + return res; + }; - if (state.needReadable) - emitReadable(stream); + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); } - - return needMoreData(state); } + function nReadingNextTick$1(self) { + debug$9('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); - } + Readable$1.prototype.resume = function () { + var state = this._readableState; - // backwards compatibility. - Readable$1.prototype.setEncoding = function(enc) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this._readableState.decoder = new StringDecoder$1(enc); - this._readableState.encoding = enc; + if (!state.flowing) { + debug$9('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + + state.flowing = !state.readableListening; + resume$1(this, state); + } + + state.paused = false; + return this; }; - // Don't raise the hwm > 128MB - var MAX_HWM = 0x800000; - function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); } - return n; } - function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; + function resume_$1(stream, state) { + debug$9('resume', state.reading); - if (state.objectMode) - return n === 0 ? 0 : 1; + if (!state.reading) { + stream.read(0); + } - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable$1.prototype.pause = function () { + debug$9('call pause flowing=%j', this._readableState.flowing); + + if (this._readableState.flowing !== false) { + debug$9('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - if (n <= 0) - return 0; + this._readableState.paused = true; + return this; + }; - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); + function flow$1(stream) { + var state = stream._readableState; + debug$9('flow', state.flowing); - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; + while (state.flowing && stream.read() !== null) { } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. - return n; - } - // you can override either this method, or the async _read(n) below. - Readable$1.prototype.read = function(n) { + Readable$1.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; + var paused = false; + stream.on('end', function () { + debug$9('wrapped end'); - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$9('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - n = howMuchToRead(n, state); + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; + var ret = _this.push(chunk); + + if (!ret) { + paused = true; + stream.pause(); } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - if (state.length === 0) - endReadable(this); + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. - return ret; - } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; + this._read = function (n) { + debug$9('wrapped _read', n); - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; + if (paused) { + paused = false; + stream.resume(); + } + }; - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } + return this; + }; - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } - if (n > 0) - ret = fromList(n, state); - else - ret = null; + return createReadableStreamAsyncIterator(this); + }; + } - if (ret === null) { - state.needReadable = true; - n = 0; + Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; } + }); + Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); + Readable$1._fromList = fromList$1; + Object.defineProperty(Readable$1.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } return ret; - }; + } - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer$i.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + function endReadable$1(stream) { + var state = stream._readableState; + debug$9('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); } - return er; } + function endReadableNT$1(state, stream) { + debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } } } - state.ended = true; + } - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); - } - - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } - function emitReadable_(stream) { - stream.emit('readable'); + return from(Readable$1, iterable, opts); + }; } - - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(function() { - maybeReadMore_(stream, state); - }); + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; + return -1; } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$1.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); - }; - - Readable$1.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } + var _stream_transform = Transform$4; - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; + var _require$codes$1 = errorsBrowser.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex$1 = _stream_duplex; + inherits_browser.exports(Transform$4, Duplex$1); - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + function afterTransform$1(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - function unpipe() { - src.unpipe(dest); + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; - state.flowing = true; - nextTick(function() { - flow(src); - }); + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } - - return dest; - }; - - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; } - function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes); - else - forEach$1(state.pipes, write); - - src.emit('data', chunk); + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); + Duplex$1.call(this, options); + this._transformState = { + afterTransform: afterTransform$1.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } + this._readableState.sync = false; - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; + this.on('prefinish', prefinish$1); } - function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); + function prefinish$1() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done$1(_this, er, data); + }); + } else { + done$1(this, null, null); } } + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$1.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. - Readable$1.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - // slow case. multiple pipe destinations. + Transform$4.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; - }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$1.prototype.on = function(ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this); - } - } + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - - return res; - }; - Readable$1.prototype.addListener = Readable$1.prototype.on; - - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$1.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); }; - Readable$1.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); + Transform$4.prototype._destroy = function (err, cb) { + Duplex$1.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); }; - function emitDataEvents(stream, startPaused) { - var state = stream._readableState; + function done$1(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } - var paused = startPaused || false; - var readable = false; + var _stream_passthrough = PassThrough$1; - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream$1.prototype.pipe; - stream.on = stream.addListener = Stream$1.prototype.on; + var Transform$3 = _stream_transform; - stream.on('readable', function() { - readable = true; + inherits_browser.exports(PassThrough$1, Transform$3); - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform$3.call(this, options); + } - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - stream.pause = function() { - paused = true; - this.emit('pause'); - }; + var eos; - stream.resume = function() { - paused = false; - if (readable) - nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$1.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); + var _require$codes = errorsBrowser.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; + } - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$1(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); }; + } - return self; - }; + function call(fn) { + fn(); + } + function pipe(from, to) { + return from.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } - // exposed for testing purposes only. - Readable$1._fromList = fromList; + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer$i.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer$i(n); + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); + var pipeline_1 = pipeline; - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); + (function (module, exports) { + exports = module.exports = _stream_readable; + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + }(readableBrowser, readableBrowser.exports)); - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + var Buffer$h = safeBuffer.exports.Buffer; + var Transform$2 = readableBrowser.exports.Transform; + var inherits$i = inherits_browser.exports; - c += cpy; - } - } + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } - - return ret; } - function endReadable(stream) { - var state = stream._readableState; + function HashBase$2 (blockSize) { + Transform$2.call(this); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); + this._block = Buffer$h.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - if (!state.endEmitted && state.calledRead) { - state.ended = true; - nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } + this._finalized = false; } - function forEach$1 (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + inherits$i(HashBase$2, Transform$2); - function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - return -1; - } - - // 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. - // a duplex stream is just a stream that is both readable and writable. - // Since JS doesn't have multiple prototypal inheritance, this class - // prototypally inherits from Readable, and then parasitically from - // Writable. + callback(error); + }; - var _stream_duplex = Duplex$1; + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - /**/ - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; + callback(error); }; - /**/ + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); - /**/ - var util$3 = util$5; - util$3.inherits = inherits_browser.exports; - /**/ + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - var Readable = _stream_readable; - var Writable$1 = _stream_writable; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } - util$3.inherits(Duplex$1, Readable); + return this + }; - forEach(objectKeys(Writable$1.prototype), function(method) { - if (!Duplex$1.prototype[method]) - Duplex$1.prototype[method] = Writable$1.prototype[method]; - }); + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - function Duplex$1(options) { - if (!(this instanceof Duplex$1)) - return new Duplex$1(options); + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - Readable.call(this, options); - Writable$1.call(this, options); + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - if (options && options.readable === false) - this.readable = false; + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - if (options && options.writable === false) - this.writable = false; + return digest + }; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - this.once('end', onend); - } + var hashBase = HashBase$2; - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; + var inherits$h = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$g = safeBuffer.exports.Buffer; - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(this.end.bind(this)); - } + var ARRAY16$1 = new Array(16); - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + function MD5$2 () { + HashBase$1.call(this, 64); - // 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. + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } - // A bit simpler than readable streams. - // Implement an async ._write(chunk, cb), and it'll handle all - // the drain event emission and buffering. + inherits$h(MD5$2, HashBase$1); - var _stream_writable = Writable; + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - /**/ - var Buffer$h = buffer.Buffer; - /**/ - - Writable.WritableState = WritableState; + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - /**/ - var util$2 = util$5; - util$2.inherits = inherits_browser.exports; - /**/ + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - var Stream = require$$1; + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - util$2.inherits(Writable, Stream); + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - } + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; - function WritableState(options, stream) { - options = options || {}; + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + // produce result + var buffer = Buffer$g.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - // a flag to see when we're in the middle of a write. - this.writing = false; + var md5_js = MD5$2; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var Buffer$f = buffer.Buffer; + var inherits$g = inherits_browser.exports; + var HashBase = hashBase; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + var ARRAY16 = new Array(16); - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + var zl = [ + 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 + ]; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var zr = [ + 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 + ]; - // the amount that is being written when _write is called. - this.writelen = 0; + var sl = [ + 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 + ]; - this.buffer = []; + var sr = [ + 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 + ]; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - } + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - function Writable(options) { - var Duplex = _stream_duplex; + function RIPEMD160$3 () { + HashBase.call(this, 64); - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } - this._writableState = new WritableState(options, this); + inherits$g(RIPEMD160$3, HashBase); - // legacy. - this.writable = true; + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - Stream.call(this); - } + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); - }; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - } + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer$h.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - valid = false; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; } - return valid; - } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - return ret; + // produce result + var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer$h(chunk, encoding); - } - return chunk; + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) } - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - return ret; + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - function onwriteError(stream, state, sync, er, cb) { - if (sync) - nextTick(function() { - cb(er); - }); - else - cb(er); + var ripemd160$2 = RIPEMD160$3; - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + var sha_js = {exports: {}}; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + var Buffer$e = safeBuffer.exports.Buffer; - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$e.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; + } - onwriteStateUpdate(state); + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$e.from(data, enc); + } - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - if (sync) { - nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; } - } - } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); - } + accum += remainder; + offset += remainder; - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + if ((accum % blockSize) === 0) { + this._update(block); + } } - } + this._len += length; + return this + }; - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + this._block[rem] = 0x80; - doWrite(stream, state, len, chunk, encoding, cb); + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); } - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } + var bits = this._len * 8; - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); } - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); + this._update(this._block); + var hash = this._hash(); + + return enc ? hash.toString(enc) : hash + }; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') }; + var hash$3 = Hash$7; + + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits$f = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$d = safeBuffer.exports.Buffer; + + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$5 = new Array(80); + + function Sha () { + this.init(); + this._w = W$5; - function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); + Hash$6.call(this, 64, 56); } - function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; + inherits$f(Sha, Hash$6); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) } - // 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. + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + Sha.prototype._update = function (M) { + var W = this._w; - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - var _stream_transform = Transform$3; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - var Duplex = _stream_duplex; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - /**/ - var util$1 = util$5; - util$1.inherits = inherits_browser.exports; - /**/ + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } - util$1.inherits(Transform$3, Duplex); + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; + Sha.prototype._hash = function () { + var H = Buffer$d.allocUnsafe(20); - function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - } + return H + }; - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + var sha$4 = Sha; - var cb = ts.writecb; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + var inherits$e = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - ts.writechunk = null; - ts.writecb = null; + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - if (data !== null && data !== undefined) - stream.push(data); + var W$4 = new Array(80); - if (cb) - cb(er); + function Sha1 () { + this.init(); + this._w = W$4; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + Hash$5.call(this, 64, 56); } + inherits$e(Sha1, Hash$5); - function Transform$3(options) { - if (!(this instanceof Transform$3)) - return new Transform$3(options); - - Duplex.call(this, options); + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - this._transformState = new TransformState(options, this); + return this + }; - // when the writable side finishes, then flush out anything remaining. - var stream = this; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } - Transform$3.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + Sha1.prototype._update = function (M) { + var W = this._w; - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$3.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); - }; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - Transform$3.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } - }; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$3.prototype._read = function(n) { - var ts = this._transformState; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; } - }; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - function done(stream, er) { - if (er) - return stream.emit('error', er); + Sha1.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - stream._readableState; - var ts = stream._transformState; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); + return H + }; - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + var sha1$1 = Sha1; - return stream.push(null); - } + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - // 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 inherits$d = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. + var K$2 = [ + 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 _stream_passthrough = PassThrough; + var W$3 = new Array(64); - var Transform$2 = _stream_transform; + function Sha256$1 () { + this.init(); - /**/ - var util = util$5; - util.inherits = inherits_browser.exports; - /**/ + this._w = W$3; // new Array(64) - util.inherits(PassThrough, Transform$2); + Hash$4.call(this, 64, 56); + } - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + inherits$d(Sha256$1, Hash$4); - Transform$2.call(this, options); - } + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); + return this }; - (function (module, exports) { - var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify - exports = module.exports = _stream_readable; - exports.Stream = Stream; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - }(readable, readable.exports)); + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - var Buffer$g = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$g = inherits_browser.exports; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } - function HashBase$2 (blockSize) { - Transform$1.call(this); + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } - this._block = Buffer$g.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - this._finalized = false; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) } - inherits$g(HashBase$2, Transform$1); + Sha256$1.prototype._update = function (M) { + var W = this._w; - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - callback(error); - }; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; } - callback(error); + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; }; - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } + Sha256$1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(32); - return this - }; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') + return H }; - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + var sha256$2 = Sha256$1; - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + var inherits$c = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - return digest - }; + var W$2 = new Array(64); - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + function Sha224 () { + this.init(); - var hashBase = HashBase$2; + this._w = W$2; // new Array(64) - var inherits$f = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + Hash$3.call(this, 64, 56); + } - var ARRAY16$1 = new Array(16); + inherits$c(Sha224, Sha256); - function MD5$2 () { - HashBase$1.call(this, 64); + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } + return this + }; - inherits$f(MD5$2, HashBase$1); + Sha224.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(28); - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + return H + }; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + var sha224 = Sha224; - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + var inherits$b = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + var K$1 = [ + 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 + ]; - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + var W$1 = new Array(160); - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; + function Sha512 () { + this.init(); + this._w = W$1; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + Hash$2.call(this, 128, 112); + } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + inherits$b(Sha512, Hash$2); - // produce result - var buffer = Buffer$f.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + + return this }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + function maj (x, y, z) { + return (x & y) | (z & (x | y)) } - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) } - var md5_js = MD5$2; + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - var Buffer$e = buffer.Buffer; - var inherits$e = inherits_browser.exports; - var HashBase = hashBase; + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - var ARRAY16 = new Array(16); + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - var zl = [ - 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 - ]; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - var zr = [ - 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 - ]; + Sha512.prototype._update = function (M) { + var W = this._w; - var sl = [ - 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 ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - var sr = [ - 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 - ]; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - function RIPEMD160$3 () { - HashBase.call(this, 64); + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - inherits$e(RIPEMD160$3, HashBase); + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + W[i] = Wih; + W[i + 1] = Wil; + } - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; - } + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + Sha512.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(64); - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } + return H + }; - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } + var sha512 = Sha512; - var ripemd160$2 = RIPEMD160$3; + var inherits$a = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - var sha_js = {exports: {}}; + var W = new Array(160); - var Buffer$d = safeBuffer.exports.Buffer; + function Sha384 () { + this.init(); + this._w = W; - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; + Hash$1.call(this, 128, 112); } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); - } - - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } + inherits$a(Sha384, SHA512$2); - accum += remainder; - offset += remainder; + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - if ((accum % blockSize) === 0) { - this._update(block); - } - } + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - this._len += length; return this }; - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + Sha384.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(48); - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - var bits = this._len * 8; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + return H + }; - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + var sha384 = Sha384; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - this._update(this._block); - var hash = this._hash(); + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - return enc ? hash.toString(enc) : hash + return new Algorithm() }; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - var hash$3 = Hash$7; + var sha$3 = sha_js.exports; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - - var inherits$d = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; - - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; - - var W$5 = new Array(80); - - function Sha () { - this.init(); - this._w = W$5; - - Hash$6.call(this, 64, 56); + var inherits$8; + if (typeof Object.create === 'function'){ + inherits$8 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$8 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; } + var inherits$9 = inherits$8; - inherits$d(Sha, Hash$6); + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + 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; + } - return this - }; + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) + return deprecated; } - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; } - Sha.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; + /** + * 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 + _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); + } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + // 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] }; - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); - - return H + // 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' }; - var sha$4 = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - - var inherits$c = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - var W$4 = new Array(80); + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } - function Sha1 () { - this.init(); - this._w = W$4; - Hash$5.call(this, 64, 56); + function stylizeNoColor(str, styleType) { + return str; } - inherits$c(Sha1, Hash$5); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - return this - }; + function arrayToHash(array) { + var hash = {}; - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } + array.forEach(function(val, idx) { + hash[val] = true; + }); - function rotl5 (num) { - return (num << 5) | (num >>> 27) + return hash; } - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + 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 !== 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; + } - Sha1.prototype._update = function (M) { - var W = this._w; + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + // 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); + } - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + // 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); + } } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + var base = '', array = false, braces = ['{', '}']; - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - return H - }; + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - var sha1$1 = Sha1; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } - var inherits$b = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - var K$2 = [ - 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 - ]; + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - var W$3 = new Array(64); + ctx.seen.push(value); - function Sha256$1 () { - this.init(); + 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); + }); + } - this._w = W$3; // new Array(64) + ctx.seen.pop(); - Hash$4.call(this, 64, 56); + return reduceToSingleString(output, base, braces); } - inherits$b(Sha256$1, Hash$4); - - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; - - return this - }; - - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) + 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 sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) - } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + 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; } - Sha256$1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); + 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'); + } + } - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + return name + ': ' + str; + } - return H - }; - var sha256$2 = Sha256$1; + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - var inherits$a = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } - var W$2 = new Array(64); - function Sha224 () { - this.init(); + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } - this._w = W$2; // new Array(64) + function isBoolean(arg) { + return typeof arg === 'boolean'; + } - Hash$3.call(this, 64, 56); + function isNull(arg) { + return arg === null; } - inherits$a(Sha224, Sha256); + function isNumber(arg) { + return typeof arg === 'number'; + } - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + function isString(arg) { + return typeof arg === 'string'; + } - return this - }; + function isUndefined(arg) { + return arg === void 0; + } - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } - return H - }; + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } - var sha224 = Sha224; + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } - var inherits$9 = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + function isFunction(arg) { + return typeof arg === 'function'; + } - var K$1 = [ - 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 objectToString(o) { + return Object.prototype.toString.call(o); + } - var W$1 = new Array(160); + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - function Sha512 () { - this.init(); - this._w = W$1; + 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); + } - Hash$2.call(this, 128, 112); + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; } - inherits$9(Sha512, Hash$2); + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - return this + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; }; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } + var string_decoder = {}; - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + var StringDecoder_1; + // 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. - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + var Buffer$7 = buffer.Buffer; - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + var isBufferEncoding = Buffer$7.isEncoding + || function(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 Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } } - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 - } + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } - Sha512.prototype._update = function (M) { - var W = this._w; + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$7(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$1.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - W[i] = Wih; - W[i + 1] = Wil; + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + charStr += buffer.toString(this.encoding, 0, end); - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + // or just emit the charStr + return charStr; + }; - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + // See http://en.wikipedia.org/wiki/UTF-8#Description - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H + this.charReceived = i; }; - var sha512 = Sha512; + StringDecoder$1.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - var inherits$8 = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } - var W = new Array(160); + return res; + }; - function Sha384 () { - this.init(); - this._w = W; + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } - Hash$1.call(this, 128, 112); + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } - inherits$8(Sha384, SHA512$2); + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + Readable.ReadableState = ReadableState; - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + var debug$8 = debuglog('stream'); + inherits$9(Readable, EventEmitter$1); - return this - }; + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + options = options || {}; - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - return H - }; + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - var sha384 = Sha384; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - return new Algorithm() - }; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var sha$3 = sha_js.exports; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - var Buffer$6 = safeBuffer.exports.Buffer; - var Transform = require$$1.Transform; - var StringDecoder = string_decoder.StringDecoder; - var inherits$7 = inherits_browser.exports; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; } - this._decoder = null; - this._encoding = null; } - inherits$7(CipherBase, Transform); + function Readable(options) { - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$6.from(data, inputEnc); - } + if (!(this instanceof Readable)) return new Readable(options); - var outData = this._update(data); - if (this.hashMode) return this + this._readableState = new ReadableState(options, this); - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } + // legacy + this.readable = true; - return outData - }; + if (options && typeof options.read === 'function') this._read = options.read; - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') + EventEmitter$1.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$m.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); }; - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); }; - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; }; - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); } else { - this.push(this._update(data)); + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); } - } catch (e) { - err = e; - } finally { - next(err); + } else if (!addToFront) { + state.reading = false; } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } + return n; + } - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer$6.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } - return outData - }; + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug$8('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$8('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; } - if (this._encoding !== enc) throw new Error('can\'t switch encodings') + n = howMuchToRead(n, state); - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } - return out - }; + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - var cipherBase = CipherBase; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$8('need readable', doRead); - var inherits$6 = inherits_browser.exports; - var MD5$1 = md5_js; - var RIPEMD160$2 = ripemd160$2; - var sha$2 = sha_js.exports; - var Base$5 = cipherBase; + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$8('length less than watermark', doRead); + } - function Hash (hash) { - Base$5.call(this, 'digest'); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$8('reading or ended', doRead); + } else if (doRead) { + debug$8('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - this._hash = hash; - } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - inherits$6(Hash, Base$5); + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } - Hash.prototype._update = function (data) { - this._hash.update(data); - }; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - Hash.prototype._final = function () { - return this._hash.digest() - }; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } - var browser$3 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5$1() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() + if (ret !== null) this.emit('data', ret); - return new Hash(sha$2(alg)) + return ret; }; - var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser$3 - }, [browser$3])); - - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; - } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; - } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; - } - return vch + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$8('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') + } + + function emitReadable_(stream) { + debug$8('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$8('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } + state.readingMore = false; } - var src$2 = base$2; - var basex = src$2; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; - var bs58 = basex(ALPHABET$1); + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var base58 = bs58; - var Buffer$5 = safeBuffer.exports.Buffer; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); + var doEnd = (!pipeOpts || pipeOpts.end !== false); - return base58.encode(Buffer$5.concat([ - payload, - checksum - ], payload.length + 4)) + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$8('onunpipe'); + if (readable === src) { + cleanup(); + } } - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); + function onend() { + debug$8('onend'); + dest.end(); + } - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - return payload - } + var cleanedUp = false; + function cleanup() { + debug$8('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return + cleanedUp = true; - return decodeRaw(buffer) + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$8('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$8('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } } - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$8('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); } - }; - var createHash$2 = browser$3; - var bs58checkBase = base$1; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$2('sha256').update(buffer).digest(); - return createHash$2('sha256').update(tmp).digest() - } + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$8('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - var bs58check$5 = bs58checkBase(sha256x2); + function unpipe() { + debug$8('unpipe'); + src.unpipe(dest); + } - function pathElementsToBuffer(paths) { - var buffer = Buffer$k.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; - } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); - } - } - return []; - } + // tell the dest that it's being piped to + dest.emit('pipe', src); - var src$1 = {}; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$8('pipe resume'); + src.resume(); + } - var src = {}; + return dest; + }; - var bip32$1 = {}; + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug$8('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } - var crypto$5 = {}; + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - var inherits$5 = inherits_browser.exports; - var Buffer$4 = safeBuffer.exports.Buffer; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - var Base$4 = cipherBase; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var ZEROS$1 = Buffer$4.alloc(128); - var blocksize = 64; + if (!dest) dest = state.pipes; - function Hmac$2 (alg, key) { - Base$4.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$4.from(key); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; } - this._alg = alg; - this._key = key; - - if (key.length > blocksize) { - key = alg(key); - } else if (key.length < blocksize) { - key = Buffer$4.concat([key, ZEROS$1], blocksize); - } + // slow case. multiple pipe destinations. - var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); - var opad = this._opad = Buffer$4.allocUnsafe(blocksize); + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; } - this._hash = [ipad]; - } + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; - inherits$5(Hmac$2, Base$4); + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - Hmac$2.prototype._update = function (data) { - this._hash.push(data); - }; + dest.emit('unpipe', this); - Hmac$2.prototype._final = function () { - var h = this._alg(Buffer$4.concat(this._hash)); - return this._alg(Buffer$4.concat([this._opad, h])) + return this; }; - var legacy = Hmac$2; - - var MD5 = md5_js; - var md5$1 = function (buffer) { - return new MD5().update(buffer).digest() - }; + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - var inherits$4 = inherits_browser.exports; - var Legacy = legacy; - var Base$3 = cipherBase; - var Buffer$3 = safeBuffer.exports.Buffer; - var md5 = md5$1; - var RIPEMD160$1 = ripemd160$2; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } - var sha$1 = sha_js.exports; + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; - var ZEROS = Buffer$3.alloc(128); + function nReadingNextTick(self) { + debug$8('readable nexttick read 0'); + self.read(0); + } - function Hmac$1 (alg, key) { - Base$3.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$3.from(key); + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$8('resume'); + state.flowing = true; + resume(this, state); } + return this; + }; - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } - this._alg = alg; - this._key = key; - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - key = hash.update(key).digest(); - } else if (key.length < blocksize) { - key = Buffer$3.concat([key, ZEROS], blocksize); + function resume_(stream, state) { + if (!state.reading) { + debug$8('resume read 0'); + stream.read(0); } - var ipad = this._ipad = Buffer$3.allocUnsafe(blocksize); - var opad = this._opad = Buffer$3.allocUnsafe(blocksize); + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; + Readable.prototype.pause = function () { + debug$8('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$8('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - this._hash.update(ipad); + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug$8('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } - inherits$4(Hmac$1, Base$3); + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - Hmac$1.prototype._update = function (data) { - this._hash.update(data); - }; - - Hmac$1.prototype._final = function () { - var h = this._hash.digest(); - var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); - return hash.update(this._opad).update(h).digest() - }; - - var browser$2 = function createHmac (alg, key) { - alg = alg.toLowerCase(); - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac$1('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac$1(alg, key) - }; - - Object.defineProperty(crypto$5, "__esModule", { value: true }); - const createHash$1 = browser$3; - const createHmac$1 = browser$2; - function hash160$2(buffer) { - const sha256Hash = createHash$1('sha256') - .update(buffer) - .digest(); - try { - return createHash$1('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$1('ripemd160') - .update(sha256Hash) - .digest(); + var self = this; + stream.on('end', function () { + debug$8('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); } - } - crypto$5.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); - } - crypto$5.hmacSHA512 = hmacSHA512; - - var bn$1 = {exports: {}}; - - (function (module) { - (function (module, exports) { - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } + self.push(null); + }); - // 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; - } + stream.on('data', function (chunk) { + debug$8('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - // BN + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } + }); - 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'); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } } - 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 = require('buffer').Buffer; - } - } catch (e) { - } + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$8('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); } - - 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; - }; + return self; + }; - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + // exposed for testing purposes only. + Readable._fromList = fromList; - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + return ret; + } - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } + list.head = p; + p.data = str.slice(nb); } + break; } - }; + ++c; + } + list.length -= c; + return ret; + } - 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; + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$m.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } + ++c; + } + list.length -= c; + return ret; + } - 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; - } + function endReadable(stream) { + var state = stream._readableState; - 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; - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - 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(); - }; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } - 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 endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); } + } - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } + } - 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; - } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - // 24-bits chunks - var off = 0; - var j = 0; + // A bit simpler than readable streams. + Writable.WritableState = WritableState; + inherits$9(Writable, events.exports.EventEmitter); - 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; - } - } - } + function nop() {} - this.strip(); - }; + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } - 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; + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - r *= mul; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - // '0' - '9' - } else { - r += c; - } - } - return r; - } + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + // a flag to see when we're in the middle of a write. + this.writing = false; - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + // when true all writes will be buffered until .uncork() call + this.corked = 0; - for (i = 0; i < mod; i++) { - pow *= base; - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - this.strip(); + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); }; - 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; - }; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; + // the amount that is being written when _write is called. + this.writelen = 0; - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - // 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(); - }; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - /* + // count buffered requests + this.bufferedRequestCount = 0; - var zeros = []; - var groupSizes = []; - var groupBases = []; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - 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; + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } + return out; + }; + function Writable(options) { - */ + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - 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' - ]; + this._writableState = new WritableState(options, this); - 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 - ]; + // legacy. + this.writable = true; - 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 - ]; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + if (typeof options.writev === 'function') this._writev = options.writev; + } - 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; - } + events.exports.EventEmitter.call(this); + } - 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); + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; - 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; - } + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } - assert(false, 'Base should be between 2 and 36'); - }; + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } - 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; - }; + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + if (typeof cb !== 'function') cb = nop; - 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'); + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + return ret; + }; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + Writable.prototype.cork = function () { + var state = this._writableState; - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + state.corked++; + }; - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + Writable.prototype.uncork = function () { + var state = this._writableState; - res[i] = b; - } + if (state.corked) { + state.corked--; - for (; i < reqLength; i++) { - res[i] = 0; - } - } + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; - return res; - }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - 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; - }; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); } + return chunk; + } - 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; - }; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); - // 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; - }; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - function toBitArray (num) { - var w = new Array(num.bitLength()); + state.length += len; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } - - return w; + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); } - // 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; - }; + return ret; + } - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + onwriteStateUpdate(state); - return this; - }; + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } - return this.strip(); - }; + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } - // 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); - }; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - // 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; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; } else { - b = this; + state.corkedRequestsFree = new CorkedRequest(state); } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } } - this.length = b.length; + if (entry === null) state.lastBufferedRequest = null; + } - return this.strip(); - }; + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - // 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); - }; + Writable.prototype._writev = null; - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - // 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; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); } else { - a = num; - b = this; + prefinish(stream, state); } + } + return need; + } - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - this.length = a.length; + this.next = null; + this.entry = null; - return this.strip(); + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } }; + } - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; + inherits$9(Duplex, Readable); - // 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); - }; + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + Readable.call(this, options); + Writable.call(this, options); - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + if (options && options.readable === false) this.readable = false; - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + if (options && options.writable === false) this.writable = false; - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - if (bitsLeft > 0) { - bytesNeeded--; - } + this.once('end', onend); + } - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } - // And remove leading zeroes - return this.strip(); - }; + function onEndNT(self) { + self.end(); + } - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); + // a transform stream is a readable/writable stream where you do + inherits$9(Transform$1, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); }; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } - var off = (bit / 26) | 0; - var wbit = bit % 26; + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - this._expand(off + 1); + var cb = ts.writecb; - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - return this.strip(); - }; + ts.writechunk = null; + ts.writecb = null; - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + if (data !== null && data !== undefined) stream.push(data); - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + cb(er); - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform$1(options) { + if (!(this instanceof Transform$1)) return new Transform$1(options); - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + Duplex.call(this, options); - 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._transformState = new TransformState(this); - 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]; - } - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - return this; - }; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - // 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; - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - if (this.length > num.length) return this.clone().iadd(num); + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - return num.clone().iadd(this); - }; + if (typeof options.flush === 'function') this._flush = options.flush; + } - // 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.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + Transform$1.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - // At this point both numbers are positive - var cmp = this.cmp(num); + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$1.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + Transform$1.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$1.prototype._read = function (n) { + var ts = this._transformState; - 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; - } + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + function done(stream, er) { + if (er) return stream.emit('error', er); - this.length = Math.max(this.length, i); + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - if (a !== this) { - this.negative = 1; - } + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - return this.strip(); - }; + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + return stream.push(null); + } - 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; + inherits$9(PassThrough, Transform$1); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - // 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; + Transform$1.call(this, options); + } - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - 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) ; 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); + inherits$9(Stream, EventEmitter$1); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform$1; + Stream.PassThrough = PassThrough; - 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); - } + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; - x1.iushrn(1); - } - } + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - 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); - } + function Stream() { + EventEmitter$1.call(this); + } - x2.iushrn(1); - } - } + Stream.prototype.pipe = function(dest, options) { + var source = this; - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); } } + } - 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; - } + source.on('data', ondata); - // 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++; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); } - 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; - } + dest.on('drain', ondrain); - assert(num <= 0x3ffffff, 'Number is too big'); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - // 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; + dest.end(); + } - 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; + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - 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 (typeof dest.destroy === 'function') dest.destroy(); + } - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. } - 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); - }; + source.on('error', onerror); + dest.on('error', onerror); - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + source.removeListener('end', onend); + source.removeListener('close', onclose); - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + dest.removeListener('close', cleanup); + } - 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); - }; + source.on('end', cleanup); + source.on('close', cleanup); - 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); - }; + dest.on('close', cleanup); - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; + dest.emit('pipe', source); - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; - // 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); - }; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform$1, + PassThrough: PassThrough, + Stream: Stream + }); - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); - // 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); - }; + var Buffer$6 = safeBuffer.exports.Buffer; + var Transform = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; + var inherits$7 = inherits_browser.exports; - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits$7(CipherBase, Transform); - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer$6.from(data, inputEnc); + } - // 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); + var outData = this._update(data); + if (this.hashMode) return this - this.tmp = this._tmp(); + if (outputEnc) { + outData = this._toString(outData, outputEnc); } - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; + return outData + }; - 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; + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; - 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(); - } + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; + + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } - return r; - }; + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer$6.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; + if (this._encoding !== enc) throw new Error('can\'t switch encodings') - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); } - inherits(K256, MPrime); - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; + return out + }; - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; + var cipherBase = CipherBase; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } + var inherits$6 = inherits_browser.exports; + var MD5$1 = md5_js; + var RIPEMD160$2 = ripemd160$2; + var sha$2 = sha_js.exports; + var Base$5 = cipherBase; - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + function Hash (hash) { + Base$5.call(this, 'digest'); - 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; - } - }; + this._hash = hash; + } - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; + inherits$6(Hash, Base$5); - // 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); - } + Hash.prototype._update = function (data) { + this._hash.update(data); + }; - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; + Hash.prototype._final = function () { + return this._hash.digest() + }; - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); + var browser$3 = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5$1() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); + return new Hash(sha$2(alg)) + }; - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); + var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser$3 + }, [browser$3])); - 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; + var inherits$5 = inherits_browser.exports; + var Buffer$5 = safeBuffer.exports.Buffer; - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; + var Base$4 = cipherBase; - // 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 ZEROS$1 = Buffer$5.alloc(128); + var blocksize = 64; - 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; + function Hmac$2 (alg, key) { + Base$4.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$5.from(key); + } - return prime; - }; + this._alg = alg; + this._key = key; - // - // 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; - } + if (key.length > blocksize) { + key = alg(key); + } else if (key.length < blocksize) { + key = Buffer$5.concat([key, ZEROS$1], blocksize); } - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; + var ipad = this._ipad = Buffer$5.allocUnsafe(blocksize); + var opad = this._opad = Buffer$5.allocUnsafe(blocksize); - 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'); - }; + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; + this._hash = [ipad]; + } - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } + inherits$5(Hmac$2, Base$4); - return this.m.sub(a)._forceRed(this); - }; + Hmac$2.prototype._update = function (data) { + this._hash.push(data); + }; - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + Hmac$2.prototype._final = function () { + var h = this._alg(Buffer$5.concat(this._hash)); + return this._alg(Buffer$5.concat([this._opad, h])) + }; + var legacy = Hmac$2; - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; + var MD5 = md5_js; - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + var md5$1 = function (buffer) { + return new MD5().update(buffer).digest() + }; - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + var inherits$4 = inherits_browser.exports; + var Legacy = legacy; + var Base$3 = cipherBase; + var Buffer$4 = safeBuffer.exports.Buffer; + var md5 = md5$1; + var RIPEMD160$1 = ripemd160$2; - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + var sha$1 = sha_js.exports; - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; + var ZEROS = Buffer$4.alloc(128); - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); + function Hmac$1 (alg, key) { + Base$3.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$4.from(key); + } - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; + this._alg = alg; + this._key = key; + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + key = hash.update(key).digest(); + } else if (key.length < blocksize) { + key = Buffer$4.concat([key, ZEROS], blocksize); + } - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); + var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } + this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + this._hash.update(ipad); + } - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + inherits$4(Hmac$1, Base$3); - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; + Hmac$1.prototype._update = function (data) { + this._hash.update(data); + }; - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + Hmac$1.prototype._final = function () { + var h = this._hash.digest(); + var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); + return hash.update(this._opad).update(h).digest() + }; - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + var browser$2 = function createHmac (alg, key) { + alg = alg.toLowerCase(); + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac$1('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac$1(alg, key) + }; - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); + Object.defineProperty(crypto$5, "__esModule", { value: true }); + const createHash$2 = browser$3; + const createHmac$1 = browser$2; + function hash160$2(buffer) { + const sha256Hash = createHash$2('sha256') + .update(buffer) + .digest(); + try { + return createHash$2('rmd160') + .update(sha256Hash) + .digest(); } - - // 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); + catch (err) { + return createHash$2('ripemd160') + .update(sha256Hash) + .digest(); } - 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); + } + crypto$5.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$5.hmacSHA512 = hmacSHA512; - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; } - - 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(); + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; } - 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; + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; } - - 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); + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; } - }; - - 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); + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; } - - 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; + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } + } + var src = base$2; - 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); - }; + var basex = src; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - function Mont (m) { - Red.call(this, m); + var bs58 = basex(ALPHABET$1); - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + var base58 = bs58; + var Buffer$3 = safeBuffer.exports.Buffer; - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); - 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); + return base58.encode(Buffer$3.concat([ + payload, + checksum + ], payload.length + 4)) } - 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; + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return - return res._forceRed(this); - }; + return payload + } - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return - 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 decodeRaw(buffer) + } - return res._forceRed(this); - }; + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } - 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); - }; - })(module, commonjsGlobal); - }(bn$1)); + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } + }; - var elliptic = {}; + var createHash$1 = browser$3; + var bs58checkBase = base$1; - var name = "elliptic"; - var version = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0$1 = { - name: name, - version: version, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$1('sha256').update(buffer).digest(); + return createHash$1('sha256').update(tmp).digest() + } - var utils$n = {}; + var bs58check$5 = bs58checkBase(sha256x2); var bn = {exports: {}}; @@ -18688,6 +16457,81 @@ })(module, commonjsGlobal); }(bn)); + var elliptic = {}; + + var name = "elliptic"; + var version = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0$1 = { + name: name, + version: version, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; + + var utils$n = {}; + var minimalisticAssert = assert$f; function assert$f(val, msg) { @@ -23241,16 +21085,16 @@ const createHmac = browser$2; - const ONE1 = Buffer$k.alloc(1, 1); - const ZERO1 = Buffer$k.alloc(1, 0); + const ONE1 = Buffer$m.alloc(1, 1); + const ZERO1 = Buffer$m.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$k.alloc(32, 0); - let v = Buffer$k.alloc(32, 1); + let k = Buffer$m.alloc(32, 0); + let v = Buffer$m.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -23302,14 +21146,14 @@ var rfc6979 = deterministicGenerateK$1; - const BN = bn$1.exports; + const BN = bn.exports; const EC = elliptic.ec; const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$k.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$m.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -23381,9 +21225,9 @@ } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -23515,7 +21359,7 @@ s = n.sub(s); } - const buffer = Buffer$k.allocUnsafe(64); + const buffer = Buffer$m.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -23748,7 +21592,7 @@ var _HexN = _LengthN.bind(null, Hex); var _StringN = _LengthN.bind(null, NATIVE$1.String); - function Range$b (a, b, f) { + function Range$m (a, b, f) { f = f || NATIVE$1.Number; function _range (value, strict) { return f(value, strict) && (value > a) && (value < b) @@ -23794,7 +21638,7 @@ Int16: Int16, Int32: Int32, Int53: Int53, - Range: Range$b, + Range: Range$m, StringN: _StringN, UInt8: UInt8, UInt16: UInt16, @@ -24100,7 +21944,7 @@ } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$k(compressed ? 34 : 33); + var result = new Buffer$m(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -24219,7 +22063,7 @@ const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$k.allocUnsafe(78); + const buffer = Buffer$m.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -24253,7 +22097,7 @@ derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$k.allocUnsafe(37); + const data = Buffer$m.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -24333,7 +22177,7 @@ } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -24425,19 +22269,19 @@ if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); } bip32$1.fromSeed = fromSeed; - Object.defineProperty(src, "__esModule", { value: true }); + Object.defineProperty(src$1, "__esModule", { value: true }); var bip32_1 = bip32$1; - src.fromSeed = bip32_1.fromSeed; - src.fromBase58 = bip32_1.fromBase58; - src.fromPublicKey = bip32_1.fromPublicKey; - src.fromPrivateKey = bip32_1.fromPrivateKey; + src$1.fromSeed = bip32_1.fromSeed; + src$1.fromBase58 = bip32_1.fromBase58; + src$1.fromPublicKey = bip32_1.fromPublicKey; + src$1.fromPrivateKey = bip32_1.fromPrivateKey; var address$1 = {}; @@ -24532,7 +22376,7 @@ function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$k.allocUnsafe(size); + const buffer = Buffer$m.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -24727,18 +22571,18 @@ const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$k.alloc(1, 0); + const ZERO$1 = Buffer$m.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$k.alloc(32, 0); + const buffer = Buffer$m.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -24752,7 +22596,7 @@ const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$k.concat([r, s], 64); + const signature = Buffer$m.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -24767,11 +22611,11 @@ const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$k.allocUnsafe(1); + const hashTypeBuffer = Buffer$m.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -25160,7 +23004,7 @@ // opcode return accum + 1; }, 0.0); - const buffer = Buffer$k.allocUnsafe(bufferSize); + const buffer = Buffer$m.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -25245,7 +23089,7 @@ if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$k.from(chunkStr, 'hex'); + return Buffer$m.from(chunkStr, 'hex'); }), ); } @@ -25255,7 +23099,7 @@ typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -25584,7 +23428,7 @@ } p2pk$3.p2pk = p2pk$2; - var p2pkh$4 = {}; + var p2pkh$3 = {}; var crypto$2 = {}; @@ -25623,7 +23467,7 @@ } crypto$2.hash256 = hash256$1; - Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + Object.defineProperty(p2pkh$3, '__esModule', { value: true }); const bcrypto$6 = crypto$2; const networks_1$4 = networks$3; const bscript$l = script$1; @@ -25634,7 +23478,7 @@ const bs58check$2 = bs58check$5; // input: {signature} {pubkey} // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$3(a, opts) { + function p2pkh$2(a, opts) { if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) throw new TypeError('Not enough data'); opts = Object.assign({ validate: true }, opts || {}); @@ -25663,7 +23507,7 @@ const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -25702,7 +23546,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -25753,7 +23597,7 @@ } return Object.assign(o, a); } - p2pkh$4.p2pkh = p2pkh$3; + p2pkh$3.p2pkh = p2pkh$2; var p2sh$1 = {}; @@ -25821,7 +23665,7 @@ // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -25857,7 +23701,7 @@ return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -25940,7 +23784,7 @@ } p2sh$1.p2sh = p2sh; - var p2wpkh$2 = {}; + var p2wpkh$1 = {}; var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; @@ -26124,7 +23968,7 @@ fromWords: fromWords }; - Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + Object.defineProperty(p2wpkh$1, '__esModule', { value: true }); const bcrypto$4 = crypto$2; const networks_1$2 = networks$3; const bscript$j = script$1; @@ -26133,11 +23977,11 @@ const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$k.alloc(0); + const EMPTY_BUFFER$1 = Buffer$m.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} - function p2wpkh$1(a, opts) { + function p2wpkh(a, opts) { if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) throw new TypeError('Not enough data'); opts = Object.assign({ validate: true }, opts || {}); @@ -26161,7 +24005,7 @@ return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$m.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -26201,7 +24045,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26252,7 +24096,7 @@ } return Object.assign(o, a); } - p2wpkh$2.p2wpkh = p2wpkh$1; + p2wpkh$1.p2wpkh = p2wpkh; var p2wsh$1 = {}; @@ -26265,7 +24109,7 @@ const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$k.alloc(0); + const EMPTY_BUFFER = Buffer$m.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -26315,7 +24159,7 @@ return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$m.from(data), }; }); const _rchunks = lazy.value(() => { @@ -26380,7 +24224,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$m.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26470,11 +24314,11 @@ payments$4.p2ms = p2ms_1.p2ms; const p2pk_1 = p2pk$3; payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$4; + const p2pkh_1 = p2pkh$3; payments$4.p2pkh = p2pkh_1.p2pkh; const p2sh_1 = p2sh$1; payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$2; + const p2wpkh_1 = p2wpkh$1; payments$4.p2wpkh = p2wpkh_1.p2wpkh; const p2wsh_1 = p2wsh$1; payments$4.p2wsh = p2wsh_1.p2wsh; @@ -26503,13 +24347,13 @@ return { version: result.words[0], prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$m.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$m.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -26665,7 +24509,7 @@ return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$m.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -26737,10 +24581,10 @@ var Buffer = safeBuffer.exports.Buffer; // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$3 = 9007199254740991; + var MAX_SAFE_INTEGER$5 = 9007199254740991; function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') } function encode$b (number, buffer, offset) { @@ -26867,7 +24711,7 @@ } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$k.allocUnsafe(buffer.length); + const clone = Buffer$m.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -26990,17 +24834,17 @@ }, 0) ); } - const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$k.from( + const ZERO = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$k.from( + const ONE = Buffer$m.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -27062,7 +24906,7 @@ return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -27222,7 +25066,7 @@ txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -27232,13 +25076,13 @@ types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$k.from([]); + let tbuffer = Buffer$m.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -27251,7 +25095,7 @@ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -27265,7 +25109,7 @@ const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$k.allocUnsafe(txOutsSize); + tbuffer = Buffer$m.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -27277,13 +25121,13 @@ inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -27301,7 +25145,7 @@ } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -27323,7 +25167,7 @@ this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -27385,7 +25229,7 @@ for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$k.concat([left, right]); + var data = Buffer$m.concat([left, right]); results[j] = digestFn(data); } @@ -27452,12 +25296,12 @@ return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$k.from(hex, 'hex')); + return Block.fromBuffer(Buffer$m.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$k.alloc(32, 0); + const target = Buffer$m.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -27472,7 +25316,7 @@ const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -27484,18 +25328,18 @@ // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$k && result.length === 32)) return null; + if (!(result instanceof Buffer$m && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$k && + this.witnessCommit instanceof Buffer$m && this.witnessCommit.length === 32 ) return true; @@ -27531,7 +25375,7 @@ } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -27673,7 +25517,7 @@ Object.defineProperty(globalXpub$1, '__esModule', { value: true }); const typeFields_1$b = typeFields; - const range$3 = n => [...Array(n).keys()]; + const range$4 = n => [...Array(n).keys()]; function decode$9(keyVal) { if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { throw new Error( @@ -27698,7 +25542,7 @@ extendedPubkey, path: 'm', }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { + for (const i of range$4(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -27708,10 +25552,10 @@ } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$k.concat([head, data.extendedPubkey]); + const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$m.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -27760,7 +25604,7 @@ const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -27781,7 +25625,7 @@ } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -27813,7 +25657,7 @@ } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -27848,7 +25692,7 @@ nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -27891,9 +25735,9 @@ } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$k.concat([head, pSig.pubkey]), + key: Buffer$m.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -27945,10 +25789,10 @@ } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$k.from(data, 'utf8'), + value: Buffer$m.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -27977,8 +25821,8 @@ } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$k.allocUnsafe(4); + const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$m.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -28004,14 +25848,14 @@ Object.defineProperty(varint$1, '__esModule', { value: true }); // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$2 = 9007199254740991; + const MAX_SAFE_INTEGER$4 = 9007199254740991; function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) throw new RangeError('value out of range'); } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -28097,8 +25941,8 @@ tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$k.from([0])); - return Buffer$k.concat(buffers); + buffers.push(Buffer$m.from([0])); + return Buffer$m.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -28106,7 +25950,7 @@ const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$k.allocUnsafe( + const buffer = Buffer$m.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -28170,12 +26014,12 @@ function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -28193,7 +26037,7 @@ var bip32Derivation$1 = {}; Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$2 = n => [...Array(n).keys()]; + const range$3 = n => [...Array(n).keys()]; function makeConverter$2(TYPE_BYTE) { function decode(keyVal) { if (keyVal.key[0] !== TYPE_BYTE) { @@ -28222,7 +26066,7 @@ pubkey, path: 'm', }; - for (const i of range$2(keyVal.value.length / 4 - 1)) { + for (const i of range$3(keyVal.value.length / 4 - 1)) { const val = keyVal.value.readUInt32LE(i * 4 + 4); const isHard = !!(val & 0x80000000); const idx = val & 0x7fffffff; @@ -28231,10 +26075,10 @@ return data; } function encode(data) { - const head = Buffer$k.from([TYPE_BYTE]); - const key = Buffer$k.concat([head, data.pubkey]); + const head = Buffer$m.from([TYPE_BYTE]); + const key = Buffer$m.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$m.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28314,7 +26158,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -28351,7 +26195,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$m.from([TYPE_BYTE]); return { key, value: data, @@ -28560,7 +26404,7 @@ } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$k.from([keyNum]))) { + if (!keyBuf.equals(Buffer$m.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -28779,13 +26623,13 @@ const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$k.from([0])] + ? [Buffer$m.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$k.allocUnsafe(5); + const header = Buffer$m.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$k.concat( + return Buffer$m.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -29079,11 +26923,11 @@ }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -29303,11 +27147,11 @@ dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$m.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$m.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -29478,7 +27322,7 @@ } finalizeAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); return this; } finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { @@ -29545,7 +27389,7 @@ } validateSignaturesOfAllInputs() { utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$1(this.data.inputs.length).map(idx => + const results = range$2(this.data.inputs.length).map(idx => this.validateSignaturesOfInput(idx), ); return results.reduce((final, res) => res === true && final, true); @@ -29591,7 +27435,7 @@ throw new Error('Need HDSigner to sign input'); } const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInputHD(i, hdKeyPair, sighashTypes); results.push(true); @@ -29614,7 +27458,7 @@ } const results = []; const promises = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { promises.push( this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( () => { @@ -29676,7 +27520,7 @@ // as input information is added, then eventually // optimize this method. const results = []; - for (const i of range$1(this.data.inputs.length)) { + for (const i of range$2(this.data.inputs.length)) { try { this.signInput(i, keyPair, sighashTypes); results.push(true); @@ -29831,7 +27675,7 @@ * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -29856,7 +27700,7 @@ } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -30031,7 +27875,7 @@ } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -30395,14 +28239,14 @@ return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$k.allocUnsafe(0); + let buffer = Buffer$m.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); + buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); + buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -30607,7 +28451,7 @@ if (isP2PK(script)) return 'pubkey'; return 'nonstandard'; } - function range$1(n) { + function range$2(n) { return [...Array(n).keys()]; } @@ -30830,7 +28674,7 @@ const bscript$5 = script$1; const p2ms$1 = multisig$1; const p2pk$1 = pubkey; - const p2pkh$2 = pubkeyhash; + const p2pkh$1 = pubkeyhash; const p2wpkho = output$7; const p2wsho = output$6; function check$4(script, allowIncomplete) { @@ -30854,8 +28698,8 @@ } // match types if ( - p2pkh$2.input.check(scriptSigChunks) && - p2pkh$2.output.check(redeemScriptChunks) + p2pkh$1.input.check(scriptSigChunks) && + p2pkh$1.output.check(redeemScriptChunks) ) return true; if ( @@ -30911,7 +28755,7 @@ const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$k.from('aa21a9ed', 'hex'); + const HEADER = Buffer$m.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -30927,7 +28771,7 @@ }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$k.allocUnsafe(36); + const buffer = Buffer$m.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -30982,7 +28826,7 @@ const typeforce$1 = typeforce_1; const p2ms = multisig$1; const p2pk = pubkey; - const p2pkh$1 = pubkeyhash; + const p2pkh = pubkeyhash; function check(chunks, allowIncomplete) { typeforce$1(typeforce$1.Array, chunks); if (chunks.length < 1) return false; @@ -30994,8 +28838,8 @@ const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); // match types if ( - p2pkh$1.input.check(witnessRawScriptSig) && - p2pkh$1.output.check(witnessScriptChunks) + p2pkh.input.check(witnessRawScriptSig) && + p2pkh.output.check(witnessScriptChunks) ) return true; if ( @@ -31203,7 +29047,7 @@ // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -32145,53 +29989,53 @@ }; } - Object.defineProperty(src$1, '__esModule', { value: true }); - const bip32 = src; - src$1.bip32 = bip32; + Object.defineProperty(src$2, '__esModule', { value: true }); + const bip32 = src$1; + src$2.bip32 = bip32; const address = address$1; - src$1.address = address; + src$2.address = address; const crypto = crypto$2; - var crypto_1 = src$1.crypto = crypto; + var crypto_1 = src$2.crypto = crypto; const ECPair = ecpair; - src$1.ECPair = ECPair; + src$2.ECPair = ECPair; const networks = networks$3; - src$1.networks = networks; + src$2.networks = networks; const payments = payments$4; - src$1.payments = payments; + src$2.payments = payments; const script = script$1; - src$1.script = script; + src$2.script = script; var block_1 = block; - src$1.Block = block_1.Block; + src$2.Block = block_1.Block; var psbt_1 = psbt$1; - src$1.Psbt = psbt_1.Psbt; + src$2.Psbt = psbt_1.Psbt; var script_1 = script$1; - src$1.opcodes = script_1.OPS; + src$2.opcodes = script_1.OPS; var transaction_1 = transaction; - src$1.Transaction = transaction_1.Transaction; + src$2.Transaction = transaction_1.Transaction; var transaction_builder_1 = transaction_builder; - src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + src$2.TransactionBuilder = transaction_builder_1.TransactionBuilder; - var re$5 = {exports: {}}; + var re$b = {exports: {}}; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; + const SEMVER_SPEC_VERSION$1 = '2.0.0'; - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + const MAX_LENGTH$5 = 256; + const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; + const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH + var constants$1 = { + SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, + MAX_LENGTH: MAX_LENGTH$5, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, + MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 }; - const debug$3 = ( + const debug$7 = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && @@ -32199,11 +30043,11 @@ ) ? (...args) => console.error('SEMVER', ...args) : () => {}; - var debug_1 = debug$3; + var debug_1$1 = debug$7; (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; + const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; + const debug = debug_1$1; exports = module.exports = {}; // The actual regexps go on exports.re @@ -32384,24 +30228,24 @@ // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + }(re$b, re$b.exports)); // parse out just the options we care about so we always get a consistent // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => + const opts$1 = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$9 = options => !options ? {} : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { + : opts$1.filter(k => options[k]).reduce((options, k) => { options[k] = true; return options }, {}); - var parseOptions_1 = parseOptions$4; + var parseOptions_1$1 = parseOptions$9; - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + const numeric$1 = /^[0-9]+$/; + const compareIdentifiers$3 = (a, b) => { + const anum = numeric$1.test(a); + const bnum = numeric$1.test(b); if (anum && bnum) { a = +a; @@ -32415,24 +30259,24 @@ : 1 }; - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers + var identifiers$1 = { + compareIdentifiers: compareIdentifiers$3, + rcompareIdentifiers: rcompareIdentifiers$1 }; - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; + const debug$6 = debug_1$1; + const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; + const { re: re$a, t: t$9 } = re$b.exports; - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { + const parseOptions$8 = parseOptions_1$1; + const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; + class SemVer$t { constructor (version, options) { - options = parseOptions$3(options); + options = parseOptions$8(options); - if (version instanceof SemVer$e) { + if (version instanceof SemVer$t) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version @@ -32443,20 +30287,20 @@ throw new TypeError(`Invalid Version: ${version}`) } - if (version.length > MAX_LENGTH$1) { + if (version.length > MAX_LENGTH$4) { throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` + `version is longer than ${MAX_LENGTH$4} characters` ) } - debug$2('SemVer', version, options); + debug$6('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); if (!m) { throw new TypeError(`Invalid Version: ${version}`) @@ -32469,15 +30313,15 @@ this.minor = +m[2]; this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { throw new TypeError('Invalid major version') } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { throw new TypeError('Invalid minor version') } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { throw new TypeError('Invalid patch version') } @@ -32488,7 +30332,7 @@ this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { + if (num >= 0 && num < MAX_SAFE_INTEGER$2) { return num } } @@ -32513,12 +30357,12 @@ } compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { + debug$6('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$t)) { if (typeof other === 'string' && other === this.version) { return 0 } - other = new SemVer$e(other, this.options); + other = new SemVer$t(other, this.options); } if (other.version === this.version) { @@ -32529,20 +30373,20 @@ } compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) + compareIdentifiers$2(this.major, other.major) || + compareIdentifiers$2(this.minor, other.minor) || + compareIdentifiers$2(this.patch, other.patch) ) } comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } // NOT having a prerelease is > having one @@ -32558,7 +30402,7 @@ do { const a = this.prerelease[i]; const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -32568,21 +30412,21 @@ } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + if (!(other instanceof SemVer$t)) { + other = new SemVer$t(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; - debug$2('prerelease compare', i, a, b); + debug$6('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { @@ -32592,7 +30436,7 @@ } else if (a === b) { continue } else { - return compareIdentifiers(a, b) + return compareIdentifiers$2(a, b) } } while (++i) } @@ -32708,17 +30552,17 @@ } } - var semver$1 = SemVer$e; + var semver$3 = SemVer$t; - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; + const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; + const { re: re$9, t: t$8 } = re$b.exports; + const SemVer$s = semver$3; - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); + const parseOptions$7 = parseOptions_1$1; + const parse$b = (version, options) => { + options = parseOptions$7(options); - if (version instanceof SemVer$d) { + if (version instanceof SemVer$s) { return version } @@ -32726,73 +30570,73 @@ return null } - if (version.length > MAX_LENGTH) { + if (version.length > MAX_LENGTH$3) { return null } - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; if (!r.test(version)) { return null } try { - return new SemVer$d(version, options) + return new SemVer$s(version, options) } catch (er) { return null } }; - var parse_1 = parse$5; + var parse_1$1 = parse$b; - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); + const parse$a = parse_1$1; + const valid$3 = (version, options) => { + const v = parse$a(version, options); return v ? v.version : null }; - var valid_1 = valid$1; + var valid_1$1 = valid$3; - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + const parse$9 = parse_1$1; + const clean$1 = (version, options) => { + const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); return s ? s.version : null }; - var clean_1 = clean; + var clean_1$1 = clean$1; - const SemVer$c = semver$1; + const SemVer$r = semver$3; - const inc = (version, release, options, identifier) => { + const inc$1 = (version, release, options, identifier) => { if (typeof (options) === 'string') { identifier = options; options = undefined; } try { - return new SemVer$c(version, options).inc(release, identifier).version + return new SemVer$r(version, options).inc(release, identifier).version } catch (er) { return null } }; - var inc_1 = inc; + var inc_1$1 = inc$1; - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + const SemVer$q = semver$3; + const compare$l = (a, b, loose) => + new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - var compare_1 = compare$a; + var compare_1$1 = compare$l; - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; + const compare$k = compare_1$1; + const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; + var eq_1$1 = eq$5; - const parse$2 = parse_1; - const eq$1 = eq_1; + const parse$8 = parse_1$1; + const eq$4 = eq_1$1; - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { + const diff$1 = (version1, version2) => { + if (eq$4(version1, version2)) { return null } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); + const v1 = parse$8(version1); + const v2 = parse$8(version2); const hasPre = v1.prerelease.length || v2.prerelease.length; const prefix = hasPre ? 'pre' : ''; const defaultResult = hasPre ? 'prerelease' : ''; @@ -32806,79 +30650,79 @@ return defaultResult // may be undefined } }; - var diff_1 = diff; + var diff_1$1 = diff$1; - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; + const SemVer$p = semver$3; + const major$1 = (a, loose) => new SemVer$p(a, loose).major; + var major_1$1 = major$1; - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; + const SemVer$o = semver$3; + const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; + var minor_1$1 = minor$1; - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; + const SemVer$n = semver$3; + const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; + var patch_1$1 = patch$1; - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); + const parse$7 = parse_1$1; + const prerelease$1 = (version, options) => { + const parsed = parse$7(version, options); return (parsed && parsed.prerelease.length) ? parsed.prerelease : null }; - var prerelease_1 = prerelease; + var prerelease_1$1 = prerelease$1; - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; + const compare$j = compare_1$1; + const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); + var rcompare_1$1 = rcompare$1; - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; + const compare$i = compare_1$1; + const compareLoose$1 = (a, b) => compare$i(a, b, true); + var compareLoose_1$1 = compareLoose$1; - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); + const SemVer$m = semver$3; + const compareBuild$5 = (a, b, loose) => { + const versionA = new SemVer$m(a, loose); + const versionB = new SemVer$m(b, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB) }; - var compareBuild_1 = compareBuild$2; + var compareBuild_1$1 = compareBuild$5; - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; + const compareBuild$4 = compareBuild_1$1; + const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); + var sort_1$1 = sort$1; - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; + const compareBuild$3 = compareBuild_1$1; + const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); + var rsort_1$1 = rsort$1; - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; + const compare$h = compare_1$1; + const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; + var gt_1$1 = gt$7; - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; + const compare$g = compare_1$1; + const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; + var lt_1$1 = lt$5; - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; + const compare$f = compare_1$1; + const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; + var neq_1$1 = neq$3; - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; + const compare$e = compare_1$1; + const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; + var gte_1$1 = gte$5; - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; + const compare$d = compare_1$1; + const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; + var lte_1$1 = lte$5; - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; + const eq$3 = eq_1$1; + const neq$2 = neq_1$1; + const gt$6 = gt_1$1; + const gte$4 = gte_1$1; + const lt$4 = lt_1$1; + const lte$4 = lte_1$1; - const cmp$1 = (a, op, b, loose) => { + const cmp$3 = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') @@ -32897,35 +30741,35 @@ case '': case '=': case '==': - return eq(a, b, loose) + return eq$3(a, b, loose) case '!=': - return neq(a, b, loose) + return neq$2(a, b, loose) case '>': - return gt$2(a, b, loose) + return gt$6(a, b, loose) case '>=': - return gte$1(a, b, loose) + return gte$4(a, b, loose) case '<': - return lt$1(a, b, loose) + return lt$4(a, b, loose) case '<=': - return lte$1(a, b, loose) + return lte$4(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } }; - var cmp_1 = cmp$1; + var cmp_1$1 = cmp$3; - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; + const SemVer$l = semver$3; + const parse$6 = parse_1$1; + const {re: re$8, t: t$7} = re$b.exports; - const coerce = (version, options) => { - if (version instanceof SemVer$6) { + const coerce$1 = (version, options) => { + if (version instanceof SemVer$l) { return version } @@ -32941,7 +30785,7 @@ let match = null; if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); + match = version.match(re$8[t$7.COERCE]); } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. @@ -32952,25 +30796,25 @@ // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && + while ((next = re$8[t$7.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next; } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; + re$8[t$7.COERCERTL].lastIndex = -1; } if (match === null) return null - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) }; - var coerce_1 = coerce; + var coerce_1$1 = coerce$1; var yallist = Yallist$1; @@ -33732,22 +31576,22 @@ var lruCache = LRUCache; // hoisted class for cyclic dependency - class Range$a { + class Range$l { constructor (range, options) { - options = parseOptions$1(options); + options = parseOptions$6(options); - if (range instanceof Range$a) { + if (range instanceof Range$l) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { - return new Range$a(range.raw, options) + return new Range$l(range.raw, options) } } - if (range instanceof Comparator$3) { + if (range instanceof Comparator$7) { // just put it in the set and return this.raw = range.value; this.set = [[range]]; @@ -33778,13 +31622,13 @@ if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); + this.set = this.set.filter(c => !isNullSet$1(c[0])); if (this.set.length === 0) this.set = [first]; else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { + if (c.length === 1 && isAny$1(c[0])) { this.set = [c]; break } @@ -33816,24 +31660,24 @@ // this is a very hot path, and fully deterministic. const memoOpts = Object.keys(this.options).join(','); const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); + const cached = cache$1.get(memoKey); if (cached) return cached const loose = this.options.loose; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); + const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); + debug$5('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); + debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); // normalize spaces range = range.split(/\s+/).join(' '); @@ -33841,17 +31685,17 @@ // At this point, the range is completely trimmed and // ready to be split into comparators. - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; const rangeList = range .split(' ') - .map(comp => parseComparator(comp, this.options)) + .map(comp => parseComparator$1(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) + .map(comp => replaceGTE0$1(comp, this.options)) // in loose mode, throw out any that are not valid comparators .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); + .map(comp => new Comparator$7(comp, this.options)); // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators @@ -33859,7 +31703,7 @@ rangeList.length; const rangeMap = new Map(); for (const comp of rangeList) { - if (isNullSet(comp)) + if (isNullSet$1(comp)) return [comp] rangeMap.set(comp.value, comp); } @@ -33867,21 +31711,21 @@ rangeMap.delete(''); const result = [...rangeMap.values()]; - cache.set(memoKey, result); + cache$1.set(memoKey, result); return result } intersects (range, options) { - if (!(range instanceof Range$a)) { + if (!(range instanceof Range$l)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( - isSatisfiable(thisComparators, options) && + isSatisfiable$1(thisComparators, options) && range.set.some((rangeComparators) => { return ( - isSatisfiable(rangeComparators, options) && + isSatisfiable$1(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) @@ -33901,43 +31745,43 @@ if (typeof version === 'string') { try { - version = new SemVer$5(version, this.options); + version = new SemVer$k(version, this.options); } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { + if (testSet$1(this.set[i], version, this.options)) { return true } } return false } } - var range = Range$a; + var range$1 = Range$l; - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); + const LRU$1 = lruCache; + const cache$1 = new LRU$1({ max: 1000 }); - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; + const parseOptions$6 = parseOptions_1$1; + const Comparator$7 = comparator$1; + const debug$5 = debug_1$1; + const SemVer$k = semver$3; const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; + re: re$7, + t: t$6, + comparatorTrimReplace: comparatorTrimReplace$1, + tildeTrimReplace: tildeTrimReplace$1, + caretTrimReplace: caretTrimReplace$1 + } = re$b.exports; - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; + const isNullSet$1 = c => c.value === '<0.0.0-0'; + const isAny$1 = c => c.value === ''; // take a set of comparators and determine whether there // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { + const isSatisfiable$1 = (comparators, options) => { let result = true; const remainingComparators = comparators.slice(); let testComparator = remainingComparators.pop(); @@ -33956,20 +31800,20 @@ // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); + const parseComparator$1 = (comp, options) => { + debug$5('comp', comp, options); + comp = replaceCarets$1(comp, options); + debug$5('caret', comp); + comp = replaceTildes$1(comp, options); + debug$5('tildes', comp); + comp = replaceXRanges$1(comp, options); + debug$5('xrange', comp); + comp = replaceStars$1(comp, options); + debug$5('stars', comp); return comp }; - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 @@ -33977,26 +31821,26 @@ // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => + const replaceTildes$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) + return replaceTilde$1(comp, options) }).join(' '); - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + const replaceTilde$1 = (comp, options) => { + const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); + debug$5('tilde', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { - debug$1('replaceTilde pr', pr); + debug$5('replaceTilde pr', pr); ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0`; } else { @@ -34005,7 +31849,7 @@ } <${M}.${+m + 1}.0-0`; } - debug$1('tilde return', ret); + debug$5('tilde return', ret); return ret }) }; @@ -34016,31 +31860,31 @@ // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => + const replaceCarets$1 = (comp, options) => comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) + return replaceCaret$1(comp, options) }).join(' '); - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const replaceCaret$1 = (comp, options) => { + debug$5('caret', comp, options); + const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; const z = options.includePrerelease ? '-0' : ''; return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); + debug$5('caret', comp, _, M, m, p, pr); let ret; - if (isX(M)) { + if (isX$1(M)) { ret = ''; - } else if (isX(m)) { + } else if (isX$1(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { + } else if (isX$1(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } } else if (pr) { - debug$1('replaceCaret pr', pr); + debug$5('replaceCaret pr', pr); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr @@ -34054,7 +31898,7 @@ } <${+M + 1}.0.0-0`; } } else { - debug$1('no pr'); + debug$5('no pr'); if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p @@ -34069,26 +31913,26 @@ } } - debug$1('caret return', ret); + debug$5('caret return', ret); return ret }) }; - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); + const replaceXRanges$1 = (comp, options) => { + debug$5('replaceXRanges', comp, options); return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) + return replaceXRange$1(comp, options) }).join(' ') }; - const replaceXRange = (comp, options) => { + const replaceXRange$1 = (comp, options) => { comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); + debug$5('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX$1(M); + const xm = xM || isX$1(m); + const xp = xm || isX$1(p); const anyX = xp; if (gtlt === '=' && anyX) { @@ -34149,7 +31993,7 @@ } <${M}.${+m + 1}.0-0`; } - debug$1('xRange return', ret); + debug$5('xRange return', ret); return ret }) @@ -34157,16 +32001,16 @@ // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); + const replaceStars$1 = (comp, options) => { + debug$5('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') + return comp.trim().replace(re$7[t$6.STAR], '') }; - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); + const replaceGTE0$1 = (comp, options) => { + debug$5('replaceGTE0', comp, options); return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') }; // This function is passed to string.replace(re[t.HYPHENRANGE]) @@ -34174,14 +32018,14 @@ // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, + const hyphenReplace$1 = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { + if (isX$1(fM)) { from = ''; - } else if (isX(fm)) { + } else if (isX$1(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { + } else if (isX$1(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; } else if (fpr) { from = `>=${from}`; @@ -34189,11 +32033,11 @@ from = `>=${from}${incPr ? '-0' : ''}`; } - if (isX(tM)) { + if (isX$1(tM)) { to = ''; - } else if (isX(tm)) { + } else if (isX$1(tm)) { to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { + } else if (isX$1(tp)) { to = `<${tM}.${+tm + 1}.0-0`; } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}`; @@ -34206,7 +32050,7 @@ return (`${from} ${to}`).trim() }; - const testSet = (set, version, options) => { + const testSet$1 = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false @@ -34220,8 +32064,8 @@ // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { + debug$5(set[i].semver); + if (set[i].semver === Comparator$7.ANY) { continue } @@ -34242,16 +32086,16 @@ return true }; - const ANY$2 = Symbol('SemVer ANY'); + const ANY$5 = Symbol('SemVer ANY'); // hoisted class for cyclic dependency - class Comparator$2 { + class Comparator$6 { static get ANY () { - return ANY$2 + return ANY$5 } constructor (comp, options) { - options = parseOptions(options); + options = parseOptions$5(options); - if (comp instanceof Comparator$2) { + if (comp instanceof Comparator$6) { if (comp.loose === !!options.loose) { return comp } else { @@ -34259,22 +32103,22 @@ } } - debug('comparator', comp, options); + debug$4('comparator', comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); - if (this.semver === ANY$2) { + if (this.semver === ANY$5) { this.value = ''; } else { this.value = this.operator + this.semver.version; } - debug('comp', this); + debug$4('comp', this); } parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; const m = comp.match(r); if (!m) { @@ -34288,9 +32132,9 @@ // if it literally is just '>' or '' then allow anything. if (!m[2]) { - this.semver = ANY$2; + this.semver = ANY$5; } else { - this.semver = new SemVer$4(m[2], this.options.loose); + this.semver = new SemVer$j(m[2], this.options.loose); } } @@ -34299,25 +32143,25 @@ } test (version) { - debug('Comparator.test', version, this.options.loose); + debug$4('Comparator.test', version, this.options.loose); - if (this.semver === ANY$2 || version === ANY$2) { + if (this.semver === ANY$5 || version === ANY$5) { return true } if (typeof version === 'string') { try { - version = new SemVer$4(version, this.options); + version = new SemVer$j(version, this.options); } catch (er) { return false } } - return cmp(version, this.operator, this.semver, this.options) + return cmp$2(version, this.operator, this.semver, this.options) } intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { + if (!(comp instanceof Comparator$6)) { throw new TypeError('a Comparator is required') } @@ -34332,12 +32176,12 @@ if (this.value === '') { return true } - return new Range$9(comp.value, options).test(this.value) + return new Range$k(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } - return new Range$9(this.value, options).test(comp.semver) + return new Range$k(this.value, options).test(comp.semver) } const sameDirectionIncreasing = @@ -34351,11 +32195,11 @@ (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && + cmp$2(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && + cmp$2(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); @@ -34369,44 +32213,44 @@ } } - var comparator = Comparator$2; + var comparator$1 = Comparator$6; - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; + const parseOptions$5 = parseOptions_1$1; + const {re: re$6, t: t$5} = re$b.exports; + const cmp$2 = cmp_1$1; + const debug$4 = debug_1$1; + const SemVer$j = semver$3; + const Range$k = range$1; - const Range$8 = range; - const satisfies$3 = (version, range, options) => { + const Range$j = range$1; + const satisfies$7 = (version, range, options) => { try { - range = new Range$8(range, options); + range = new Range$j(range, options); } catch (er) { return false } return range.test(version) }; - var satisfies_1 = satisfies$3; + var satisfies_1$1 = satisfies$7; - const Range$7 = range; + const Range$i = range$1; // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set + const toComparators$1 = (range, options) => + new Range$i(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - var toComparators_1 = toComparators; + var toComparators_1$1 = toComparators$1; - const SemVer$3 = semver$1; - const Range$6 = range; + const SemVer$i = semver$3; + const Range$h = range$1; - const maxSatisfying = (versions, range, options) => { + const maxSatisfying$1 = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { - rangeObj = new Range$6(range, options); + rangeObj = new Range$h(range, options); } catch (er) { return null } @@ -34416,22 +32260,22 @@ if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v; - maxSV = new SemVer$3(max, options); + maxSV = new SemVer$i(max, options); } } }); return max }; - var maxSatisfying_1 = maxSatisfying; + var maxSatisfying_1$1 = maxSatisfying$1; - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { + const SemVer$h = semver$3; + const Range$g = range$1; + const minSatisfying$1 = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { - rangeObj = new Range$5(range, options); + rangeObj = new Range$g(range, options); } catch (er) { return null } @@ -34441,27 +32285,27 @@ if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v; - minSV = new SemVer$2(min, options); + minSV = new SemVer$h(min, options); } } }); return min }; - var minSatisfying_1 = minSatisfying; + var minSatisfying_1$1 = minSatisfying$1; - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; + const SemVer$g = semver$3; + const Range$f = range$1; + const gt$5 = gt_1$1; - const minVersion = (range, loose) => { - range = new Range$4(range, loose); + const minVersion$1 = (range, loose) => { + range = new Range$f(range, loose); - let minver = new SemVer$1('0.0.0'); + let minver = new SemVer$g('0.0.0'); if (range.test(minver)) { return minver } - minver = new SemVer$1('0.0.0-0'); + minver = new SemVer$g('0.0.0-0'); if (range.test(minver)) { return minver } @@ -34473,7 +32317,7 @@ let setMin = null; comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); + const compver = new SemVer$g(comparator.semver.version); switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { @@ -34485,7 +32329,7 @@ /* fallthrough */ case '': case '>=': - if (!setMin || gt$1(compver, setMin)) { + if (!setMin || gt$5(compver, setMin)) { setMin = compver; } break @@ -34498,7 +32342,7 @@ throw new Error(`Unexpected operation: ${comparator.operator}`) } }); - if (setMin && (!minver || gt$1(minver, setMin))) + if (setMin && (!minver || gt$5(minver, setMin))) minver = setMin; } @@ -34508,47 +32352,47 @@ return null }; - var minVersion_1 = minVersion; + var minVersion_1$1 = minVersion$1; - const Range$3 = range; - const validRange = (range, options) => { + const Range$e = range$1; + const validRange$1 = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' + return new Range$e(range, options).range || '*' } catch (er) { return null } }; - var valid = validRange; + var valid$2 = validRange$1; - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; + const SemVer$f = semver$3; + const Comparator$5 = comparator$1; + const {ANY: ANY$4} = Comparator$5; + const Range$d = range$1; + const satisfies$6 = satisfies_1$1; + const gt$4 = gt_1$1; + const lt$3 = lt_1$1; + const lte$3 = lte_1$1; + const gte$3 = gte_1$1; - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); + const outside$5 = (version, range, hilo, options) => { + version = new SemVer$f(version, options); + range = new Range$d(range, options); let gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; + gtfn = gt$4; + ltefn = lte$3; + ltfn = lt$3; comp = '>'; ecomp = '>='; break case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; + gtfn = lt$3; + ltefn = gte$3; + ltfn = gt$4; comp = '<'; ecomp = '<='; break @@ -34557,7 +32401,7 @@ } // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { + if (satisfies$6(version, range, options)) { return false } @@ -34571,8 +32415,8 @@ let low = null; comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); + if (comparator.semver === ANY$4) { + comparator = new Comparator$5('>=0.0.0'); } high = high || comparator; low = low || comparator; @@ -34601,38 +32445,38 @@ return true }; - var outside_1 = outside$2; + var outside_1$1 = outside$5; // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; + const outside$4 = outside_1$1; + const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); + var gtr_1$1 = gtr$1; - const outside = outside_1; + const outside$3 = outside_1$1; // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; + const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); + var ltr_1$1 = ltr$1; - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); + const Range$c = range$1; + const intersects$1 = (r1, r2, options) => { + r1 = new Range$c(r1, options); + r2 = new Range$c(r2, options); return r1.intersects(r2) }; - var intersects_1 = intersects; + var intersects_1$1 = intersects$1; // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { + const satisfies$5 = satisfies_1$1; + const compare$c = compare_1$1; + var simplify$1 = (versions, range, options) => { const set = []; let min = null; let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); + const v = versions.sort((a, b) => compare$c(a, b, options)); for (const version of v) { - const included = satisfies$1(version, range, options); + const included = satisfies$5(version, range, options); if (included) { prev = version; if (!min) @@ -34666,11 +32510,11 @@ return simplified.length < original.length ? simplified : range }; - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; + const Range$b = range$1; + const Comparator$4 = comparator$1; + const { ANY: ANY$3 } = Comparator$4; + const satisfies$4 = satisfies_1$1; + const compare$b = compare_1$1; // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR @@ -34708,17 +32552,17 @@ // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true - const subset = (sub, dom, options = {}) => { + const subset$1 = (sub, dom, options = {}) => { if (sub === dom) return true - sub = new Range(sub, options); - dom = new Range(dom, options); + sub = new Range$b(sub, options); + dom = new Range$b(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); + const isSub = simpleSubset$1(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) continue OUTER @@ -34733,33 +32577,33 @@ return true }; - const simpleSubset = (sub, dom, options) => { + const simpleSubset$1 = (sub, dom, options) => { if (sub === dom) return true - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) + if (sub.length === 1 && sub[0].semver === ANY$3) { + if (dom.length === 1 && dom[0].semver === ANY$3) return true else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; + sub = [ new Comparator$4('>=0.0.0-0') ]; else - sub = [ new Comparator('>=0.0.0') ]; + sub = [ new Comparator$4('>=0.0.0') ]; } - if (dom.length === 1 && dom[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY$3) { if (options.includePrerelease) return true else - dom = [ new Comparator('>=0.0.0') ]; + dom = [ new Comparator$4('>=0.0.0') ]; } const eqSet = new Set(); let gt, lt; for (const c of sub) { if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); + gt = higherGT$1(gt, c, options); else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); + lt = lowerLT$1(lt, c, options); else eqSet.add(c.semver); } @@ -34769,7 +32613,7 @@ let gtltComp; if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); + gtltComp = compare$b(gt.semver, lt.semver, options); if (gtltComp > 0) return null else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) @@ -34778,753 +32622,1813 @@ // will iterate one or zero times for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) + if (gt && !satisfies$4(eq, String(gt), options)) return null - if (lt && !satisfies(eq, String(lt), options)) - return null + if (lt && !satisfies$4(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies$4(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT$1(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT$1(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT$1 = (a, b, options) => { + if (!a) + return b + const comp = compare$b(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1$1 = subset$1; + + // just pre-load all the stuff that index.js lazily exports + const internalRe$1 = re$b.exports; + var semver$2 = { + re: internalRe$1.re, + src: internalRe$1.src, + tokens: internalRe$1.t, + SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, + SemVer: semver$3, + compareIdentifiers: identifiers$1.compareIdentifiers, + rcompareIdentifiers: identifiers$1.rcompareIdentifiers, + parse: parse_1$1, + valid: valid_1$1, + clean: clean_1$1, + inc: inc_1$1, + diff: diff_1$1, + major: major_1$1, + minor: minor_1$1, + patch: patch_1$1, + prerelease: prerelease_1$1, + compare: compare_1$1, + rcompare: rcompare_1$1, + compareLoose: compareLoose_1$1, + compareBuild: compareBuild_1$1, + sort: sort_1$1, + rsort: rsort_1$1, + gt: gt_1$1, + lt: lt_1$1, + eq: eq_1$1, + neq: neq_1$1, + gte: gte_1$1, + lte: lte_1$1, + cmp: cmp_1$1, + coerce: coerce_1$1, + Comparator: comparator$1, + Range: range$1, + satisfies: satisfies_1$1, + toComparators: toComparators_1$1, + maxSatisfying: maxSatisfying_1$1, + minSatisfying: minSatisfying_1$1, + minVersion: minVersion_1$1, + validRange: valid$2, + outside: outside_1$1, + gtr: gtr_1$1, + ltr: ltr_1$1, + intersects: intersects_1$1, + simplifyRange: simplify$1, + subset: subset_1$1, + }; + + /* + * Bitcoin BIP32 path helpers + * (C) 2016 Alex Beregszaszi + */ + + const HARDENED = 0x80000000; + + var BIPPath = function (path) { + if (!Array.isArray(path)) { + throw new Error('Input must be an Array') + } + if (path.length === 0) { + throw new Error('Path must contain at least one level') + } + for (var i = 0; i < path.length; i++) { + if (typeof path[i] !== 'number') { + throw new Error('Path element is not a number') + } + } + this.path = path; + }; + + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false + } + }; + + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false + } + }; + + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) + }; + + BIPPath.fromString = function (text, reqRoot) { + // skip the root + if (/^m\//i.test(text)) { + text = text.slice(2); + } else if (reqRoot) { + throw new Error('Root element is required') + } + + var path = text.split('/'); + var ret = new Array(path.length); + for (var i = 0; i < path.length; i++) { + var tmp = /(\d+)([hH\']?)/.exec(path[i]); + if (tmp === null) { + throw new Error('Invalid input') + } + ret[i] = parseInt(tmp[1], 10); + + if (ret[i] >= HARDENED) { + throw new Error('Invalid child index') + } + + if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { + ret[i] += HARDENED; + } else if (tmp[2].length != 0) { + throw new Error('Invalid modifier') + } + } + return new BIPPath(ret) + }; + + BIPPath.prototype.toPathArray = function () { + return this.path + }; + + BIPPath.prototype.toString = function (noRoot, oldStyle) { + var ret = new Array(this.path.length); + for (var i = 0; i < this.path.length; i++) { + var tmp = this.path[i]; + if (tmp & HARDENED) { + ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); + } else { + ret[i] = tmp; + } + } + return (noRoot ? '' : 'm/') + ret.join('/') + }; + + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; + + var bip32Path = BIPPath; + + function pathElementsToBuffer(paths) { + var buffer = Buffer$m.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; + } + + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$m.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$m.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$m.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var result = this.buffer.readBigUInt64LE(this.offset); + this.offset += 8; + return result; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); + } - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false + finally { if (e) throw e.error; } } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + return ar; + }; + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; - - var subset_1 = subset; - - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, + return to.concat(ar || Array.prototype.slice.call(from)); }; - - function unsafeTo64bitLE(n) { - // we want to represent the input as a 8-bytes array - if (n > Number.MAX_SAFE_INTEGER) { - throw new Error("Can't convert numbers > MAX_SAFE_INT"); + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$m.concat([Buffer$m.of(1), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$m.of(0), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$m.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); } - var byteArray = Buffer$k.alloc(8, 0); - for (var index = 0; index < byteArray.length; index++) { - var byte = n & 0xff; - byteArray[index] = byte; - n = (n - byte) / 256; + if (isPowerOf2(n)) { + return n / 2; } - return byteArray; + return 1 << Math.floor(Math.log2(n)); } - function unsafeFrom64bitLE(byteArray) { - var value = 0; - if (byteArray.length != 8) { - throw new Error("Expected Bufffer of lenght 8"); + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; } - if (byteArray[7] != 0) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$m.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$m.of(0, 1)); } - if (byteArray[6] > 0x1f) { - throw new Error("Can't encode numbers > MAX_SAFE_INT"); + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.of()); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } } - for (var i = byteArray.length - 1; i >= 0; i--) { - value = value * 256 + byteArray[i]; + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); + tx.writeVarSlice(psbt.getOutputScript(i)); } - return value; + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); } - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; + + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$6 = (undefined && undefined.__assign) || function () { + __assign$6 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$6.apply(this, arguments); + }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$m.of(0x70, 0x73, 0x62, 0x74, 0xff); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$3(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$k.alloc(alloc); - fn(b); - this.bufs.push(b); + return NoSuchEntry; + }(Error)); + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); }; - BufferWriter.prototype.writeUInt64 = function (i) { - var bytes = unsafeTo64bitLE(i); - this.writeSlice(bytes); + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$k.from(slice)); + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); }; - BufferWriter.prototype.buffer = function () { - return Buffer$k.concat(this.bufs); + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); }; - BufferReader.prototype.readUInt64 = function () { - var buf = this.readSlice(8); - var n = unsafeFrom64bitLE(buf); - return n; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); }; - return BufferReader; - }()); - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } - - var __extends$4 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); }; - })(); - var BaseAccount = /** @class */ (function () { - function BaseAccount(psbt, masterFp) { - this.psbt = psbt; - this.masterFp = masterFp; - } - return BaseAccount; - }()); - /** - * Superclass for single signature accounts. This will make sure that the pubkey - * arrays and path arrays in the method arguments contains exactly one element - * and calls an abstract method to do the actual work. - */ - var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); - function SingleKeyAccount() { - return _super !== null && _super.apply(this, arguments) || this; - } - SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); - } - return this.singleKeyCondition(pubkeys[0]); + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); + }; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$m.of(0x70, 0x73, 0x62, 0x74, 0xff)); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); }; - SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); + } + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; } - if (pathElems.length != 1) { - throw new Error("Expected single path, got " + pathElems.length); + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; } - this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); }; - SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { - if (pubkeys.length != 1) { - throw new Error("Expected single key, got " + pubkeys.length); + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; } - if (paths.length != 1) { - throw new Error("Expected single path, got " + paths.length); + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$m.from(k.substring(2), "hex")); + } + }); + return result; + }; + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); + }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$m.of()); + this.globalMap.set(key.toString(), value); + }; + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); + }; + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); + }; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; } - this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + return (maps[index] = new Map()); }; - return SingleKeyAccount; - }(BaseAccount)); - var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); - function p2pkh() { - return _super !== null && _super.apply(this, arguments) || this; - } - p2pkh.prototype.singleKeyCondition = function (pubkey) { + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getOutputOptional = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); - return { scriptPubKey: buf.buffer() }; + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); }; - p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + return { masterFingerprint: masterFingerprint, path: path }; }; - p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); }; - p2pkh.prototype.getDescriptorTemplate = function () { - return "pkh(@0)"; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$6({ hashes: hashes }, deriv); }; - return p2pkh; - }(SingleKeyAccount)); - var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); - function p2tr() { - return _super !== null && _super.apply(this, arguments) || this; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); } - p2tr.prototype.singleKeyCondition = function (pubkey) { - var xonlyPubkey = pubkey.slice(1); // x-only pubkey + // Make sure to return a copy, to protect the underlying data. + return Buffer$m.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { var buf = new BufferWriter(); - var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen - buf.writeSlice(outputKey); - return { scriptPubKey: buf.buffer() }; - }; - p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + this.toBuffer(buf); + return buf.buffer().toString("hex"); }; - p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - var xonly = pubkey.slice(1); - this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); }; - p2tr.prototype.getDescriptorTemplate = function () { - return "tr(@0)"; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); }; - /* - The following two functions are copied from wallet-btc and adapted. - They should be moved to a library to avoid code reuse. - */ - p2tr.prototype.hashTapTweak = function (x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$k.concat([h, h, x])); + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; + } + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); }; - /** - * Calculates a taproot output key from an internal key. This output key will be - * used as witness program in a taproot output. The internal key is tweaked - * according to recommendation in BIP341: - * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 - * - * @param internalPubkey A 32 byte x-only taproot internal key - * @returns The output key - */ - p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer$m.of(); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$m.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + var b = Buffer$m.alloc(8); + b.writeBigUInt64LE(BigInt(n), 0); + return b; + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * + * @param psbt The psbt with all signatures added as partial sigs, either through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$k.concat([ - Buffer$k.from([0x02]), - internalPubkey, - ]); - var tweak = this.hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - }; - return p2tr; - }(SingleKeyAccount)); - var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); - function p2wpkhWrapped() { - return _super !== null && _super.apply(this, arguments) || this; + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); + } + } + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); + } + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); + } + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$m.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$m.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$m.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$m.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$m.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$m.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); } - p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var redeemScript = this.createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; - }; - p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - var userSuppliedRedeemScript = spentOutput.cond.redeemScript; - var expectedRedeemScript = this.createRedeemScript(pubkey); - if (userSuppliedRedeemScript && - !expectedRedeemScript.equals(userSuppliedRedeemScript)) { - // At what point might a user set the redeemScript on its own? - throw new Error("User-supplied redeemScript ".concat(userSuppliedRedeemScript.toString("hex"), " doesn't\n match expected ").concat(expectedRedeemScript.toString("hex"), " for input ").concat(i)); - } - this.psbt.setInputRedeemScript(i, expectedRedeemScript); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputRedeemScript(i, cond.redeemScript); - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkhWrapped.prototype.getDescriptorTemplate = function () { - return "sh(wpkh(@0))"; - }; - p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); - }; - return p2wpkhWrapped; - }(SingleKeyAccount)); - var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); - function p2wpkh() { - return _super !== null && _super.apply(this, arguments) || this; + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$m.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$m.concat([ + inputBuffer, + input.prevout, + Buffer$m.from([0x00]), + input.sequence, + ]) + : Buffer$m.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$m.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$m.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$m.alloc(0), + transaction.extraData || Buffer$m.alloc(0), + ]); } - p2wpkh.prototype.singleKeyCondition = function (pubkey) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); - buf.writeSlice(pubkeyHash); - return { scriptPubKey: buf.buffer() }; - }; - p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { - if (!inputTx) { - throw new Error("Full input base transaction required"); - } - this.psbt.setInputNonWitnessUtxo(i, inputTx); - this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); - this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); - }; - p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { - this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); - }; - p2wpkh.prototype.getDescriptorTemplate = function () { - return "wpkh(@0)"; - }; - return p2wpkh; - }(SingleKeyAccount)); + return Buffer$m.concat([ + transaction.version, + timestamp ? timestamp : Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - finally { if (e) throw e.error; } - } - return ar; + return t; + }; + return __assign$5.apply(this, arguments); }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return to.concat(ar || Array.prototype.slice.call(from)); }; - /** - * This class implements the merkle tree used by Ledger Bitcoin app v2+, - * which is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md - */ - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver$2.major(appAndVersion.version) >= 2); + } + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); }; - Merkle.prototype.size = function () { - return this.leaves.length; + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$e(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$e(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, accountTypeFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); }; - Merkle.prototype.getLeaves = function () { - return this.leaves; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * more than a few hours to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, accountType, display) { + return __awaiter$e(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(accountType, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outptus + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$e(this, void 0, void 0, function () { + var psbt, accountType, masterFp, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + if (arg.inputs.length == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + accountType = accountTypeFromArg(arg); + psbt.setGlobalTxVersion(2); + if (arg.lockTime) { + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(arg.inputs.length); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < arg.inputs.length)) return [3 /*break*/, 7]; + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + psbt.setGlobalOutputCount(outputCount); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.script); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + if (accountType == AccountType.p2pkh) { + psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); + } + else if (accountType == AccountType.p2wpkh) { + psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); + } + else if (accountType == AccountType.p2wpkhWrapped) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + psbt.setOutputRedeemScript(i, changeData.redeemScript); + psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); + } + else if (accountType == AccountType.p2tr) { + psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath); + } + } + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.script.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType, key); + return [4 /*yield*/, this.signPsbt(psbt, p)]; + case 9: return [2 /*return*/, _a.sent()]; + } + }); + }); }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$e(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, script; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } + } + return [4 /*yield*/, this.client.getPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + if (accountType == AccountType.p2tr) { + pubkey = pubkey.slice(1); + } + script = outputScriptOf(pubkey, accountType); + return [2 /*return*/, __assign$5(__assign$5({}, script), { pubkey: pubkey })]; + } + }); + }); }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP) { + return __awaiter$e(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentOutput, expectedRedeemScript, xonly; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2]; + sequence = input[3]; + if (sequence) { + psbt.setInputSequence(i, sequence); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentOutput = inputTx.outputs[spentOutputIndex]; + if (accountType == AccountType.p2pkh) { + psbt.setInputNonWitnessUtxo(i, inputTxBuffer); + psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); + } + else if (accountType == AccountType.p2wpkh) { + psbt.setInputNonWitnessUtxo(i, inputTxBuffer); + psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); + psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); + } + else if (accountType == AccountType.p2wpkhWrapped) { + psbt.setInputNonWitnessUtxo(i, inputTxBuffer); + psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); + if (!redeemScript) { + throw new Error("Missing redeemScript for p2wpkhWrapped input"); + } + expectedRedeemScript = createRedeemScript(pubkey); + if (redeemScript != expectedRedeemScript.toString("hex")) { + throw new Error("Unexpected redeemScript"); + } + psbt.setInputRedeemScript(i, expectedRedeemScript); + psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); + } + else if (accountType == AccountType.p2tr) { + xonly = pubkey.slice(1); + psbt.setInputTapBip32Derivation(i, xonly, [], masterFP, pathElements); + psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); + } + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); + BtcNew.prototype.signPsbt = function (psbt, walletPolicy) { + return __awaiter$e(this, void 0, void 0, function () { + var sigs, serializedTx; + return __generator$e(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0))]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case. + // some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); }; - return Merkle; + return BtcNew; }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$k.from([0]), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$k.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; + var AccountType; + (function (AccountType) { + AccountType["p2pkh"] = "pkh(@0)"; + AccountType["p2wpkh"] = "wpkh(@0)"; + AccountType["p2wpkhWrapped"] = "sh(wpkh(@0))"; + AccountType["p2tr"] = "tr(@0)"; + })(AccountType || (AccountType = {})); + function createRedeemScript(pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); + } + function outputScriptOf(pubkey, accountType) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + var redeemScript; + if (accountType == AccountType.p2pkh) { + buf.writeSlice(Buffer$m.of(OP_DUP, OP_HASH160, HASH_SIZE)); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$m.of(OP_EQUALVERIFY, OP_CHECKSIG)); } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; + else if (accountType == AccountType.p2wpkhWrapped) { + redeemScript = createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$m.of(OP_HASH160, HASH_SIZE)); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + else if (accountType == AccountType.p2wpkh) { + buf.writeSlice(Buffer$m.of(0, HASH_SIZE)); + buf.writeSlice(pubkeyHash); } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + else if (accountType == AccountType.p2tr) { + console.log("Internal key: " + pubkey.toString("hex")); + var outputKey = getTaprootOutputKey(pubkey); + buf.writeSlice(Buffer$m.of(0x51, 32)); // push1, pubkeylen + buf.writeSlice(outputKey); } + return { script: buf.buffer(), redeemScript: redeemScript }; } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; - } - return 1 << Math.floor(Math.log2(n)); + function accountTypeFrom(addressFormat) { + if (addressFormat == "legacy") + return AccountType.p2pkh; + if (addressFormat == "p2sh") + return AccountType.p2wpkhWrapped; + if (addressFormat == "bech32") + return AccountType.p2wpkh; + if (addressFormat == "bech32m") + return AccountType.p2tr; + throw new Error("Unsupported address format " + addressFormat); } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; + function accountTypeFromArg(arg) { + if (arg.additionals.includes("bech32m")) + return AccountType.p2tr; + if (arg.additionals.includes("bech32")) + return AccountType.p2wpkh; + if (arg.segwit) + return AccountType.p2wpkhWrapped; + return AccountType.p2pkh; } - - /** - * The Bitcon hardware app uses a descriptors-like thing to describe - * how to construct output scripts from keys. A "Wallet Policy" consists - * of a "Descriptor Template" and a list of "keys". A key is basically - * a serialized BIP32 extended public key with some added derivation path - * information. This is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md - */ - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; - } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$k.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[".concat(masterFingerprint.toString("hex")).concat(accountPath.substring(1), "]").concat(xpub, "/**"); + /* + The following two functions are copied from wallet-btc and adapte. + They should be moved to a library to avoid code reuse. + */ + function hashTapTweak(x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$m.concat([h, h, x])); + } + function getTaprootOutputKey(internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$m.concat([Buffer$m.of(0x02), internalPubkey]); + var tweak = hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; } + var id$1 = 0; + var subscribers = []; /** - * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However - * the role is partially documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type */ - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$k.from([0, 1])); - } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = function (cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } + catch (e) { + console.error(e); } } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(psbt.getOutputAmount(i)); - tx.writeVarSlice(psbt.getOutputScript(i)); - } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; } - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log, + listen: listen + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -35532,716 +34436,1182 @@ } return t; }; - return __assign$5.apply(this, arguments); + return __assign$4.apply(this, arguments); }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return NoSuchEntry; - }(Error)); + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$d(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + /** - * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as - * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki - * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki - * - * A psbt is a data structure that can carry all relevant information about a - * transaction through all stages of the signing process. From constructing an - * unsigned transaction to extracting the final serialized transaction ready for - * broadcast. + * Use invariant() to assert state which your program assumes to be true. * - * This implementation is limited to what's needed in ledgerjs to carry out its - * duties, which means that support for features like multisig or taproot script - * path spending are not implemented. Specifically, it supports p2pkh, - * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. * - * This class is made purposefully dumb, so it's easy to add support for - * complemantary fields as needed in the future. + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. */ - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { - this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); - }; - PsbtV2.prototype.getInputSighashType = function (inputIndex) { - var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); - if (!result) - return undefined; - return result.readUInt32LE(0); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); - return unsafeFrom64bitLE(buf); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var browser = invariant; + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); - } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; - } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; - } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$k.from(k.substring(2), "hex")); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$c(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$c(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$m.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; } }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$k.from([])); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$c(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$c(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$c(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$m.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$m.from([0x00]) + : Buffer$m.alloc(0); + data = Buffer$m.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$m.concat([ + output.amount, + isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$m.concat(endData); + extraPart = isDecred + ? data + : Buffer$m.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - return { masterFingerprint: masterFingerprint, path: path }; }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$b(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$b(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$m.concat([ + transaction.version, + transaction.timestamp || Buffer$m.alloc(0), + transaction.nVersionGroupId || Buffer$m.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$m.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$m.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$m.from([0x00]); + } + } + data = Buffer$m.concat([ + prefix, + inputValue, + isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$m.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$5({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer$k.from(value); + }); } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); - keyPair.serialize(buf); + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); } - buf.writeUInt8(0); - } - function b() { - return Buffer$k.from([]); + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$m.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$m.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } - function uint32LE(n) { - var b = Buffer$k.alloc(4); - b.writeUInt32LE(n, 0); - return b; + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$m.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([sigHashType]), + ]) + : Buffer$m.concat([ + pathsBuffer, + Buffer$m.from([0x00]), + lockTimeBuffer, + Buffer$m.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$m.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); } - function uint64LE(n) { - return unsafeTo64bitLE(n); + + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$a(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); + + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver$2.gte(version, "1.4.0"); } - /** - * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 - * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However - * the role is documented in BIP174 (PSBTv0 - * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). - * - * Verify that all inputs have a signature, and set inputFinalScriptwitness - * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean - * fields that aren't useful anymore, partial signatures, redeem script and - * derivation paths. - * - * @param psbt The psbt with all signatures added as partial sigs, either - * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input ".concat(i, " present")); + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got ".concat(legacyPubkeys.length)); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$8(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$m.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$m.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$m.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$m.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$m.concat([ + Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$m.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$m.concat([ + Buffer$m.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$m.alloc(1); + keySize = Buffer$m.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$m.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$m.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$m.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$m.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$m.concat([ + Buffer$m.from("02", "hex"), + Buffer$m.from([signatures[i].length]), + signatures[i], + Buffer$m.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$m.concat([witness, tmpScriptData]); + } + result = Buffer$m.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$m.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$m.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$m.alloc(0), + targetTransaction.extraData || Buffer$m.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$m.concat([ + decredWitness_1, + Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0x00, 0x00, 0x00, 0x00]), + Buffer$m.from([0xff, 0xff, 0xff, 0xff]), + Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$m.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - /** - * Deletes fields that are no longer neccesary from the psbt. - * - * Note, the spec doesn't say anything about removing ouput fields - * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them - * without actually knowing why. I think we should remove them too. - */ - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - /** - * Writes a script push operation to buf, which looks different - * depending on the size of the data. See - * https://en.bitcoin.it/wiki/Script#Constants - * - * @param buf the BufferWriter to write to - * @param data the Buffer to be pushed. - */ - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$k.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); - } - - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$k.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer$k.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer$k.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$k.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$k.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$k.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$k.concat([ - inputBuffer, - input.prevout, - Buffer$k.from([0x00]), - input.sequence, - ]) - : Buffer$k.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$k.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$k.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$k.alloc(0), - transaction.extraData || Buffer$k.alloc(0), - ]); - } - return Buffer$k.concat([ - transaction.version, - timestamp ? timestamp : Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -36250,7 +35620,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -36277,459 +35647,285 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver.major(appAndVersion.version) >= 2); - } - /** - * This class implements the same interface as BtcOld (formerly - * named Btc), but interacts with Bitcoin hardware app version 2+ - * which uses a totally new APDU protocol. This new - * protocol is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - * - * Since the interface must remain compatible with BtcOld, the methods - * of this class are quite clunky, because it needs to adapt legacy - * input data into the PSBT process. In the future, a new interface should - * be developed that exposes PSBT to the outer world, which would render - * a much cleaner implementation. - */ - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - /** - * This is a new method that allow users to get an xpub at a standard path. - * Standard paths are described at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description - * - * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): - * M/44'/N'/x'/** - * M/48'/N'/x'/y'/** - * M/49'/N'/x'/** - * M/84'/N'/x'/** - * M/86'/N'/x'/** - * - * The method was added because of added security in the hardware app v2+. The - * new hardware app will allow export of any xpub up to and including the - * deepest hardened key of standard derivation paths, whereas the old app - * would allow export of any key. - * - * This caused an issue for callers of this class, who only had - * getWalletPublicKey() to call which means they have to constuct xpub - * themselves: - * - * Suppose a user of this class wants to create an account xpub on a standard - * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) - * by requesting the parent key M/44'/0'. The new app won't allow that, because - * it only allows exporting deepest level hardened path. So the options are to - * allow requesting M/44'/0' from the app, or to add a new function - * "getWalletXpub". - * - * We opted for adding a new function, which can greatly simplify client code. - */ - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version ".concat(xpubVersion, " doesn't match the xpub version from the device ").concat(xpubComponents.version)); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * This method returns a public key, a bitcoin address, and and a chaincode - * for a specific derivation path. - * - * Limitation: If the path is not a leaf node of a standard path, the address - * will be the empty string "", see this.getWalletAddress() for details. - */ - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * too much time to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * Build and sign a transaction. See Btc.createPaymentTransactionNew for - * details on how to use this method. - * - * This method will convert the legacy arguments, CreateTransactionArg, into - * a psbt which is finally signed and finalized, and the extracted fully signed - * transaction is returned. - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputCount = arg.inputs.length; - if (inputCount == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountType = accountTypeFromArg(arg, psbt, masterFp); - if (arg.lockTime != undefined) { - // The signer will assume locktime 0 if unset - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(inputCount); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - notifyCount = 0; - progress = function () { - if (!arg.onDeviceStreaming) - return; - arg.onDeviceStreaming({ - total: 2 * inputCount, - index: notifyCount, - progress: ++notifyCount / (2 * inputCount) - }); - }; - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < inputCount)) return [3 /*break*/, 7]; - progress(); - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - psbt.setGlobalOutputCount(outputCount); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); - } - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType.getDescriptorTemplate(), key); - // This is cheating, because it's not actually requested on the - // device yet, but it will be, soonish. - if (arg.onDeviceSignatureRequested) - arg.onDeviceSignatureRequested(); - firstSigned = false; - progressCallback = function () { - if (!firstSigned) { - firstSigned = true; - arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); - } - progress(); - }; - return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; - case 9: - _a.sent(); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - /** - * Calculates an output script along with public key and possible redeemScript - * from a path and accountType. The accountPath must be a prefix of path. - * - * @returns an object with output script (property "script"), redeemScript (if - * wrapped p2wpkh), and pubkey at provided path. The values of these three - * properties depend on the accountType used. - */ - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path ".concat(path, " not in account ").concat(pathArrayToString(accountPath))); - } - } - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - cond = accountType.spendingCondition([pubkey]); - return [2 /*return*/, { cond: cond, pubkey: pubkey }]; - } - }); - }); - }; - /** - * Adds relevant data about an input to the psbt. This includes sequence, - * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, - * public key and its derivation path. - */ - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; - sequence = input[3]; - if (sequence != undefined) { - psbt.setInputSequence(i, sequence); - } - if (sigHashType != undefined) { - psbt.setInputSighashType(i, sigHashType); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentTxOutput = inputTx.outputs[spentOutputIndex]; - spendCondition = { - scriptPubKey: spentTxOutput.script, - redeemScript: redeemScript - }; - spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; - accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - /** - * This implements the "Signer" role of the BIP370 transaction signing - * process. - * - * It ssks the hardware device to sign the a psbt using the specified wallet - * policy. This method assumes BIP32 derived keys are used for all inputs, see - * comment in-line. The signatures returned from the hardware device is added - * to the appropriate input fields of the PSBT. - */ - BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case, - // since some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input ".concat(k)); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$7(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$7(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$m.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; } }); - return [2 /*return*/]; - } - }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } }); - }; - return BtcNew; - }()); - function descrTemplFrom(addressFormat) { - if (addressFormat == "legacy") - return "pkh(@0)"; - if (addressFormat == "p2sh") - return "sh(wpkh(@0))"; - if (addressFormat == "bech32") - return "wpkh(@0)"; - if (addressFormat == "bech32m") - return "tr(@0)"; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg, psbt, masterFp) { - if (arg.additionals.includes("bech32m")) - return new p2tr(psbt, masterFp); - if (arg.additionals.includes("bech32")) - return new p2wpkh(psbt, masterFp); - if (arg.segwit) - return new p2wpkhWrapped(psbt, masterFp); - return new p2pkh(psbt, masterFp); + }); } - var id$1 = 0; - var subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch(obj); + return __assign$2.apply(this, arguments); }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = function (cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } - catch (e) { - console.error(e); - } - } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; + nullScript = Buffer$m.alloc(0); + nullPrevout = Buffer$m.alloc(0); + defaultVersion = Buffer$m.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + startTime = Date.now(); + targetTransaction = { + inputs: [], + timestamp: Buffer$m.alloc(0), + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$m.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$m.from(trustedInput, "hex") + : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$m.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$m.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$m.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); } - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log, - listen: listen - }); - - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) @@ -36737,9 +35933,9 @@ } return t; }; - return __assign$4.apply(this, arguments); + return __assign$1.apply(this, arguments); }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -36748,7 +35944,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -36775,125 +35971,365 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$5(this, void 0, void 0, function () { + var res; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$5(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$m.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$m.concat([ + Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$m.concat([ + asBufferUInt32BE(version), + Buffer$m.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$m.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$2 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$2(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); } + return v; }); - }); - } - - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); + var __extends$1 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } - }; - - var browser = invariant; - - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + return ar; }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } + return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$7 = (undefined && undefined.__values) || function(o) { + var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -36904,224 +36340,275 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$k.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$1(YieldCommand, _super); + function YieldCommand(results) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$m.from(request.subarray(1))); + return Buffer$m.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$1(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = request.subarray(1); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$m.from([known_preimage[i]])); + } } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$k.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ - transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$k.from([0x00]) - : Buffer$k.alloc(0); - data = Buffer$k.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$k.concat([ - output.amount, - isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$k.concat(endData); - extraPart = isDecred - ? data - : Buffer$k.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; + return Buffer$m.concat([ + preimage_len_varint, + Buffer$m.from([payload_size]), + known_preimage.subarray(0, payload_size), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = request.subarray(1); + if (req.length != 32 + 4 + 4) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the hash + var hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req.readUInt8(i); + } + var hash_hex = hash.toString("hex"); + var tree_size = req.readUInt32BE(32); + var leaf_index = req.readUInt32BE(32 + 4); + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$m.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$m.from([proof.length]), + Buffer$m.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$1(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = request.subarray(1); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$m.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; } - }); - }); - } + } + return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$1(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$m.concat(__spreadArray$1([ + Buffer$m.from([n_returned_elements]), + Buffer$m.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter() { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } + } + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37130,7 +36617,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37157,7 +36644,7 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var __values$6 = (undefined && undefined.__values) || function(o) { + var __values$2 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -37168,368 +36655,365 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$k.concat([ - transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputValue.length]); + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$4(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); } - else { - prefix = Buffer$k.from([0x02]); + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getPubkey = function (display, pathElements) { + return __awaiter$4(this, void 0, void 0, function () { + var response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputs[i].value.length]); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ + Buffer$m.of(display ? 1 : 0), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$4(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); } - else { - prefix = Buffer$k.from([0x00]); + clientInterpreter = new ClientCommandInterpreter(); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$m.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ + Buffer$m.of(display ? 1 : 0), + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + Buffer$m.of(change), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC) { + return __awaiter$4(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$4(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); } - } - data = Buffer$k.concat([ - prefix, - inputValue, - isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + clientInterpreter = new ClientCommandInterpreter(); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); } - else { - scriptBlocks.push(Buffer$k.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); } - offset += blockSize; + finally { if (e_1) throw e_1.error; } } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$m.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.of())]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$m.alloc(0); + var nExpiryHeight = Buffer$m.alloc(0); + var nVersionGroupId = Buffer$m.alloc(0); + var extraData = Buffer$m.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$m.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$m.alloc(0); + var tree = Buffer$m.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$k.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + else { + locktime = transaction.slice(offset, offset + 4); } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; } - hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$k.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$k.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$k.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([sigHashType]), - ]) - : Buffer$k.concat([ - pathsBuffer, - Buffer$k.from([0x00]), - lockTimeBuffer, - Buffer$k.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$k.concat([buffer, expiryHeight]); + if (hasExtraData) { + extraData = transaction.slice(offset); } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); } - return result; - }); - } - - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; } - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37538,7 +37022,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37561,358 +37045,652 @@ _.trys.pop(); continue; } op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$k.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$k.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$k.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$k.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$k.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$k.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$k.concat([ - Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$k.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$k.concat([ - Buffer$k.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletXpub", + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); + } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; + } + else { + options = opts || {}; + } + return this.getCorrectImpl().then(function (impl) { + return impl.getWalletPublicKey(path, options); + }); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return this.old().signMessageNew(path, messageHex); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "bech32m" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + return this.old().signP2SHTransaction(arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$3(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, new BtcOld(this.transport)]; } else { - signatureSize = Buffer$k.alloc(1); - keySize = Buffer$k.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$k.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); + return [2 /*return*/, new BtcNew(new AppClient(this.transport))]; } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$k.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$k.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$k.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$k.concat([ - Buffer$k.from("02", "hex"), - Buffer$k.from([signatures[i].length]), - signatures[i], - Buffer$k.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$k.concat([witness, tmpScriptData]); + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + return Btc; + }()); + + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); + + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; + }; + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; + }; + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } + } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; } - result = Buffer$k.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$k.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$k.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$k.alloc(0), - targetTransaction.extraData || Buffer$k.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$k.concat([ - decredWitness_1, - Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0xff, 0xff, 0xff, 0xff]), - Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$k.concat([result, decredWitness_1]); } - return [2 /*return*/, result.toString("hex")]; + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } } - }); - }); + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; + } + return new Error(String(object)); + }; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); + } + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; + } + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + if (typeof from.name === "string") { + to.name = from.name; + } + if (typeof from.message === "string") { + to.message = from.message; + } + if (typeof from.stack === "string") { + to.stack = from.stack; + } + return to; + } + + var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); + var AmountRequired = createCustomErrorClass("AmountRequired"); + var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass("NetworkDown"); + var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass("FeeRequired"); + var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); + var SyncError = createCustomErrorClass("SyncError"); + var PairingFailed = createCustomErrorClass("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); + var DBNotReset = createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa + }; + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; + } + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass, + addCustomErrorDeserializer: addCustomErrorDeserializer, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError, + StatusCodes: StatusCodes, + getAltStatusMessage: getAltStatusMessage, + TransportStatusError: TransportStatusError + }); + + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37921,7 +37699,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37948,127 +37726,32 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$k.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + finally { if (e) throw e.error; } + } + return ar; }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } } + return to.concat(ar || Array.prototype.slice.call(from)); }; - var __values$4 = (undefined && undefined.__values) || function(o) { + var __values = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { @@ -38079,2421 +37762,2341 @@ }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion; - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$k.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$k.from(trustedInput, "hex") - : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$k.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !segwit && firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { + var Transport = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$m.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$m.concat([ + Buffer$m.from([cla, ins, p1, p2]), + Buffer$m.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { switch (_a.label) { case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: res = _a.sent(); - this.derivationsCache[path] = res; + if (unresponsiveReached) { + this.emit("responsive"); + } return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; } }); - }); + }); }; + this._appAPIlock = null; + } + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); }; /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); }; /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); + * Enable or not logs of the binary exchange */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); }; /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; }; /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); + TransportFoo.create().then(transport => ...) */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } } - return signP2SHTransaction(this.transport, arg); }; - return BtcOld; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$k.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; + + var hidFraming$1 = {}; + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$m.alloc(2); + b.writeUInt16BE(value, 0); + return b; } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$k.concat([ - Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); + var initialAcc = { + data: Buffer$m.alloc(0), + dataLength: 0, + sequence: 0 + }; + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$m.concat([ + data, + Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$m.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$m.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$m.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; + }; + exports["default"] = createHIDframing; + + }(hidFraming$1)); + + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$3; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$k.concat([ - asBufferUInt32BE(version), - Buffer$k.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - /** - * This implements "Merkelized Maps", documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps - * - * A merkelized map consist of two merkle trees, one for the keys of - * a map and one for the values of the same map, thus the two merkle - * trees have the same shape. The commitment is the number elements - * in the map followed by the keys' merkle root followed by the - * values' merkle root. - */ - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); - } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$k.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - /** - * This class merkelizes a PSBTv2, by merkelizing the different - * maps of the psbt. This is used during the transaction signing process, - * where the hardware app can request specific parts of the psbt from the - * client code and be sure that the response data actually belong to the psbt. - * The reason for this is the limited amount of memory available to the app, - * so it can't always store the full psbt in memory. - * - * The signing process is documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt - */ - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { + return id + }); } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results, progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$k.from(request.subarray(1))); - this.progressCallback(); - return Buffer$k.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - GetPreimageCommand.prototype.execute = function (request) { - var req = Buffer$k.from(request.subarray(1)); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$k.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$k.from([known_preimage[i]])); - } - } - return Buffer$k.concat([ - preimage_len_varint, - Buffer$k.from([payload_size]), - Buffer$k.from(known_preimage.subarray(0, payload_size)), - ]); - } - throw Error("Requested unknown preimage for: ".concat(req_hash_hex)); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; + + if (other.version === this.version) { + return 0 } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = Buffer$k.from(request.subarray(1)); - if (req.length < 32 + 1 + 1) { - throw new Error("Invalid request, expected at least 34 bytes"); - } - var reqBuf = new BufferReader(req); - var hash = reqBuf.readSlice(32); - var hash_hex = hash.toString("hex"); - var tree_size; - var leaf_index; - try { - tree_size = reqBuf.readVarInt(); - leaf_index = reqBuf.readVarInt(); - } - catch (e) { - throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); - } - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: ".concat(hash_hex)); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$k.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$k.from([proof.length]), - Buffer$k.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = Buffer$k.from(request.subarray(1)); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$k.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$k.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: ".concat(root_hash_hex)); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$k.concat(__spreadArray$1([ - Buffer$k.from([n_returned_elements]), - Buffer$k.from([element_len]) - ], __read$1(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - /** - * This class will dispatch a client command coming from the hardware device to - * the appropriate client command implementation. Those client commands - * typically requests data from a merkle tree or merkelized maps. - * - * A ClientCommandInterpreter is prepared by adding the merkle trees and - * merkelized maps it should be able to serve to the hardware device. This class - * doesn't know anything about the semantics of the data it holds, it just - * serves merkle data. It doesn't even know in what context it is being - * executed, ie SignPsbt, getWalletAddress, etc. - * - * If the command yelds results to the client, as signPsbt does, the yielded - * data will be accessible after the command completed by calling getYielded(), - * which will return the yields in the same order as they came in. - */ - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter(progressCallback) { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded, progressCallback), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code ".concat(cmd.code)); - } - this.commands.set(cmd.code, cmd); - } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); - this.addKnownPreimage(preimage); + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); + } else { + this.prerelease = [identifier, 0]; + } } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code ".concat(cmdCode)); + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); + } + } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - /** - * This class encapsulates the APDU protocol documented at - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md - */ - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$k.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), - walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), - Buffer$k.from([change]), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(progressCallback); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; - }); - }); - }; - return AppClient; - }()); + var coerce_1 = coerce; - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput ".concat(i, ":"); - str += " prevout ".concat(prevout.toString("hex")); - str += " script ".concat(script.toString("hex")); - str += " sequence ".concat(sequence.toString("hex")); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput ".concat(i, ":"); - str += " amount ".concat(amount.toString("hex")); - str += " script ".concat(script.toString("hex")); - }); - return str; - } + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$k.alloc(0); - var nExpiryHeight = Buffer$k.alloc(0); - var nVersionGroupId = Buffer$k.alloc(0); - var extraData = Buffer$k.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer$k.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$k.alloc(0); - var tree = Buffer$k.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); + } } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); } - else { - locktime = transaction.slice(offset, offset + 4); + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } - if (hasExtraData) { - extraData = transaction.slice(offset); + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); - return t; + return false + } } + var range = Range$a; - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) }); + + testComparator = remainingComparators.pop(); + } + + return result }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 84' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var _this = this; - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; + + debug$1('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } - return this.getCorrectImpl().then(function (impl) { - /** - * Definition: A "normal path" is a prefix of a standard path where all - * the hardened steps of the standard path are included. For example, the - * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' - * is not. m/'199/1'/17'/0/1 is not a normal path either. - * - * There's a compatiblity issue between old and new app: When exporting - * the key of a non-normal path with verify=false, the new app would - * return an error, whereas the old app would return the key. - * - * See - * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey - * - * If format bech32m is used, we'll not use old, because it doesn't - * support it. - * - * When to use new (given the app supports it) - * * format is bech32m or - * * path is normal or - * * verify is true - * - * Otherwise use old. - */ - if (impl instanceof BtcNew && - options.format != "bech32m" && - (!options.verify || options.verify == false) && - !isPathNormal(path)) { - console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); - return _this.old().getWalletPublicKey(path, options); - } - else { - return impl.getWalletPublicKey(path, options); - } - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, this.old()]; - } - else { - return [2 /*return*/, this["new"]()]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - Btc.prototype["new"] = function () { - return new BtcNew(new AppClient(this.transport)); - }; - return Btc; - }()); - function isPathNormal(path) { - //path is not deepest hardened node of a standard path or deeper, use BtcOld - var h = 0x80000000; - var pathElems = pathStringToArray(path); - var hard = function (n) { return n >= h; }; - var soft = function (n) { return !n || n < h; }; - var change = function (n) { return !n || n == 0 || n == 1; }; - if (pathElems.length >= 3 && - pathElems.length <= 5 && - [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - change(pathElems[3]) && - soft(pathElems[4])) { - return true; + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } } - if (pathElems.length >= 4 && - pathElems.length <= 6 && - 48 + h == pathElems[0] && - [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && - hard(pathElems[2]) && - hard(pathElems[3]) && - change(pathElems[4]) && - soft(pathElems[5])) { - return true; + + debug$1('caret return', ret); + return ret + }) + }; + + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; } - return false; - } - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); + debug$1('xRange return', ret); - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + return ret + }) }; - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } - return error; + } } - return new Error(String(object)); + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } + + debug('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - if (typeof from.name === "string") { - to.name = from.name; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); } - if (typeof from.message === "string") { - to.message = from.message; + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true } - if (typeof from.stack === "string") { - to.stack = from.stack; + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } } - return to; - } - var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); - var AmountRequired = createCustomErrorClass("AmountRequired"); - var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass("NetworkDown"); - var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass("FeeRequired"); - var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); - var SyncError = createCustomErrorClass("SyncError"); - var PairingFailed = createCustomErrorClass("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); - var DBNotReset = createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); + }); + return min + }; + var minSatisfying_1 = minSatisfying; - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass, - addCustomErrorDeserializer: addCustomErrorDeserializer, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError, - StatusCodes: StatusCodes, - getAltStatusMessage: getAltStatusMessage, - TransportStatusError: TransportStatusError - }); + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } + } + return true }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$k.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$k.concat([ - Buffer$k.from([cla, ins, p1, p2]), - Buffer$k.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError(sw); - } - return [2 /*return*/, response]; - } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; - } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } - var hidFraming$1 = {}; + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$k.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$k.alloc(0), - dataLength: 0, - sequence: 0 + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$k.concat([ - data, - Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$k.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$k.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$k.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - exports["default"] = createHIDframing; - }(hidFraming$1)); + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -40929,7 +40532,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$k.from(r.data.buffer); + buffer = Buffer$m.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: From 472b36986e10bbfb30724b4d8592f46633215d00 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Tue, 15 Feb 2022 09:23:31 +1100 Subject: [PATCH 57/78] down to 6.7.0 --- js/ledger.js | 47320 +++++++++++++------------------------------------ 1 file changed, 12093 insertions(+), 35227 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index be5d408b..9c9e4c79 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -19,8 +19,6 @@ return Object.freeze(n); } - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } @@ -999,7 +997,7 @@ var toString = {}.toString; - var isArray$1 = Array.isArray || function (arr) { + var isArray$3 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1029,12 +1027,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$m.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$e.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$m.TYPED_ARRAY_SUPPORT + return Buffer$e.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1043,14 +1041,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$e.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$m(length); + that = new Buffer$e(length); } that.length = length; } @@ -1068,9 +1066,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$m (arg, encodingOrOffset, length) { - if (!Buffer$m.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$m)) { - return new Buffer$m(arg, encodingOrOffset, length) + function Buffer$e (arg, encodingOrOffset, length) { + if (!Buffer$e.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$e)) { + return new Buffer$e(arg, encodingOrOffset, length) } // Common case. @@ -1082,18 +1080,18 @@ } return allocUnsafe(this, arg) } - return from$1(this, arg, encodingOrOffset, length) + return from(this, arg, encodingOrOffset, length) } - Buffer$m.poolSize = 8192; // not used by this implementation + Buffer$e.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$m._augment = function (arr) { - arr.__proto__ = Buffer$m.prototype; + Buffer$e._augment = function (arr) { + arr.__proto__ = Buffer$e.prototype; return arr }; - function from$1 (that, value, encodingOrOffset, length) { + function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1117,13 +1115,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$m.from = function (value, encodingOrOffset, length) { - return from$1(null, value, encodingOrOffset, length) + Buffer$e.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) }; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { - Buffer$m.prototype.__proto__ = Uint8Array.prototype; - Buffer$m.__proto__ = Uint8Array; + if (Buffer$e.TYPED_ARRAY_SUPPORT) { + Buffer$e.prototype.__proto__ = Uint8Array.prototype; + Buffer$e.__proto__ = Uint8Array; } function assertSize (size) { @@ -1154,14 +1152,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$m.alloc = function (size, fill, encoding) { + Buffer$e.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) { + if (!Buffer$e.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1172,13 +1170,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$m.allocUnsafe = function (size) { + Buffer$e.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$m.allocUnsafeSlow = function (size) { + Buffer$e.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1187,7 +1185,7 @@ encoding = 'utf8'; } - if (!Buffer$m.isEncoding(encoding)) { + if (!Buffer$e.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1234,10 +1232,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$m.prototype; + that.__proto__ = Buffer$e.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1267,7 +1265,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$1(obj.data)) { + if (obj.type === 'Buffer' && isArray$3(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1284,12 +1282,12 @@ } return length | 0 } - Buffer$m.isBuffer = isBuffer; + Buffer$e.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$m.compare = function compare (a, b) { + Buffer$e.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1312,7 +1310,7 @@ return 0 }; - Buffer$m.isEncoding = function isEncoding (encoding) { + Buffer$e.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1331,13 +1329,13 @@ } }; - Buffer$m.concat = function concat (list, length) { - if (!isArray$1(list)) { + Buffer$e.concat = function concat (list, length) { + if (!isArray$3(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$m.alloc(0) + return Buffer$e.alloc(0) } var i; @@ -1348,7 +1346,7 @@ } } - var buffer = Buffer$m.allocUnsafe(length); + var buffer = Buffer$e.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1404,7 +1402,7 @@ } } } - Buffer$m.byteLength = byteLength$1; + Buffer$e.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1478,7 +1476,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$m.prototype._isBuffer = true; + Buffer$e.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1486,7 +1484,7 @@ b[m] = i; } - Buffer$m.prototype.swap16 = function swap16 () { + Buffer$e.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1497,7 +1495,7 @@ return this }; - Buffer$m.prototype.swap32 = function swap32 () { + Buffer$e.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1509,7 +1507,7 @@ return this }; - Buffer$m.prototype.swap64 = function swap64 () { + Buffer$e.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1523,20 +1521,20 @@ return this }; - Buffer$m.prototype.toString = function toString () { + Buffer$e.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$m.prototype.equals = function equals (b) { + Buffer$e.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$m.compare(this, b) === 0 + return Buffer$e.compare(this, b) === 0 }; - Buffer$m.prototype.inspect = function inspect () { + Buffer$e.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1546,7 +1544,7 @@ return '' }; - Buffer$m.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$e.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1645,7 +1643,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$m.from(val, encoding); + val = Buffer$e.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1657,7 +1655,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$m.TYPED_ARRAY_SUPPORT && + if (Buffer$e.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1727,15 +1725,15 @@ return -1 } - Buffer$m.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$e.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$m.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$e.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$m.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$e.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1786,7 +1784,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$m.prototype.write = function write (string, offset, length, encoding) { + Buffer$e.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1858,7 +1856,7 @@ } }; - Buffer$m.prototype.toJSON = function toJSON () { + Buffer$e.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -1997,7 +1995,7 @@ var out = ''; for (var i = start; i < end; ++i) { - out += toHex$1(buf[i]); + out += toHex(buf[i]); } return out } @@ -2011,7 +2009,7 @@ return res } - Buffer$m.prototype.slice = function slice (start, end) { + Buffer$e.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2033,12 +2031,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$m.prototype; + newBuf.__proto__ = Buffer$e.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$m(sliceLen, undefined); + newBuf = new Buffer$e(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2055,7 +2053,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$m.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$e.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2070,7 +2068,7 @@ return val }; - Buffer$m.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$e.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2086,22 +2084,22 @@ return val }; - Buffer$m.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$e.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$m.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$e.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$m.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$e.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$m.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$e.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2110,7 +2108,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$m.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$e.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2119,7 +2117,7 @@ this[offset + 3]) }; - Buffer$m.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$e.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2137,7 +2135,7 @@ return val }; - Buffer$m.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$e.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2155,25 +2153,25 @@ return val }; - Buffer$m.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$e.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$m.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$e.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$e.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$m.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$e.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2182,7 +2180,7 @@ (this[offset + 3] << 24) }; - Buffer$m.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$e.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2191,22 +2189,22 @@ (this[offset + 3]) }; - Buffer$m.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$e.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$m.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$e.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$m.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$e.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$m.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$e.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2217,7 +2215,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$m.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$e.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2236,7 +2234,7 @@ return offset + byteLength }; - Buffer$m.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$e.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2255,11 +2253,11 @@ return offset + byteLength }; - Buffer$m.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$e.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$e.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2272,11 +2270,11 @@ } } - Buffer$m.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$e.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2285,11 +2283,11 @@ return offset + 2 }; - Buffer$m.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$e.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2305,11 +2303,11 @@ } } - Buffer$m.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$e.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2320,11 +2318,11 @@ return offset + 4 }; - Buffer$m.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$e.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2335,7 +2333,7 @@ return offset + 4 }; - Buffer$m.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$e.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2358,7 +2356,7 @@ return offset + byteLength }; - Buffer$m.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$e.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2381,21 +2379,21 @@ return offset + byteLength }; - Buffer$m.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$e.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$m.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$e.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$m.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$e.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2404,11 +2402,11 @@ return offset + 2 }; - Buffer$m.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$e.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2417,11 +2415,11 @@ return offset + 2 }; - Buffer$m.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$e.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2432,12 +2430,12 @@ return offset + 4 }; - Buffer$m.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$e.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; - if (Buffer$m.TYPED_ARRAY_SUPPORT) { + if (Buffer$e.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2461,11 +2459,11 @@ return offset + 4 } - Buffer$m.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$e.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$e.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2477,16 +2475,16 @@ return offset + 8 } - Buffer$m.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$e.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$m.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$e.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$m.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$e.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2518,7 +2516,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$m.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$e.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2538,7 +2536,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$m.prototype.fill = function fill (val, start, end, encoding) { + Buffer$e.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2558,7 +2556,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$m.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$e.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2587,7 +2585,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$m(val, encoding).toString()); + : utf8ToBytes(new Buffer$e(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -2619,7 +2617,7 @@ return str.replace(/^\s+|\s+$/g, '') } - function toHex$1 (n) { + function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } @@ -2763,37340 +2761,13927 @@ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } - var src$2 = {}; - - var src$1 = {}; - - var bip32$1 = {}; - - var crypto$5 = {}; + /* + * Bitcoin BIP32 path helpers + * (C) 2016 Alex Beregszaszi + */ - var inherits_browser = {exports: {}}; + const HARDENED = 0x80000000; - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - inherits_browser.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; + var BIPPath = function (path) { + if (!Array.isArray(path)) { + throw new Error('Input must be an Array') + } + if (path.length === 0) { + throw new Error('Path must contain at least one level') + } + for (var i = 0; i < path.length; i++) { + if (typeof path[i] !== 'number') { + throw new Error('Path element is not a number') } - }; - } - - var safeBuffer = {exports: {}}; - - var buffer = {}; - - var base64Js = {}; - - base64Js.byteLength = byteLength; - base64Js.toByteArray = toByteArray; - base64Js.fromByteArray = fromByteArray; - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - - var code$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i$1 = 0, len = code$1.length; i$1 < len; ++i$1) { - lookup[i$1] = code$1[i$1]; - revLookup[code$1.charCodeAt(i$1)] = i$1; - } - - // 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') } + this.path = path; + }; - // 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; + BIPPath.validatePathArray = function (path) { + try { + BIPPath.fromPathArray(path); + return true + } catch (e) { + return false } + }; - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[curByte++] = tmp & 0xFF; + BIPPath.validateString = function (text, reqRoot) { + try { + BIPPath.fromString(text, reqRoot); + return true + } catch (e) { + return false } + }; - 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; + BIPPath.fromPathArray = function (path) { + return new BIPPath(path) + }; + + BIPPath.fromString = function (text, reqRoot) { + // skip the root + if (/^m\//i.test(text)) { + text = text.slice(2); + } else if (reqRoot) { + throw new Error('Root element is required') } - return arr - } + var path = text.split('/'); + var ret = new Array(path.length); + for (var i = 0; i < path.length; i++) { + var tmp = /(\d+)([hH\']?)/.exec(path[i]); + if (tmp === null) { + throw new Error('Invalid input') + } + ret[i] = parseInt(tmp[1], 10); - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } + if (ret[i] >= HARDENED) { + throw new Error('Invalid child index') + } - 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)); + if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { + ret[i] += HARDENED; + } else if (tmp[2].length != 0) { + throw new Error('Invalid modifier') + } } - return output.join('') - } + return new BIPPath(ret) + }; - 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 + BIPPath.prototype.toPathArray = function () { + return this.path + }; - // 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))); + BIPPath.prototype.toString = function (noRoot, oldStyle) { + var ret = new Array(this.path.length); + for (var i = 0; i < this.path.length; i++) { + var tmp = this.path[i]; + if (tmp & HARDENED) { + ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); + } else { + ret[i] = tmp; + } } + return (noRoot ? '' : 'm/') + ret.join('/') + }; - // 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] + - '=' - ); - } + BIPPath.prototype.inspect = function () { + return 'BIPPath <' + this.toString() + '>' + }; - return parts.join('') - } + var bip32Path = BIPPath; - var ieee754 = {}; + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; - /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - - ieee754.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) + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - ieee754.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; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } - - 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; }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - (function (exports) { - - var base64 = base64Js; - var ieee754$1 = ieee754; - var 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; - - var 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 signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$a(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$a(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$e.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$a(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$e.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$e.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); } - function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - var proto = { foo: function () { return 42 } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42 - } catch (e) { - return false - } + function bip32asBuffer(path) { + var paths = !path ? [] : bip32Path.fromString(path).toPathArray(); + var buffer = Buffer$e.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + return buffer; } - 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 - var buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer.prototype); - return buf + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$9(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$9(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); } + var id$1 = 0; + var subscribers = []; /** - * 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. + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type */ - - 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' - ) + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = function (cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } + catch (e) { + console.error(e); + } } - 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' - ) - } - - var valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var 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) - ) + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; } - /** - * 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); + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log, + listen: listen + }); - 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 getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); } - - 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) + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$e.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$e.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$e.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; } - /** - * 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) + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput ".concat(i, ":"); + str += " prevout ".concat(prevout.toString("hex")); + str += " script ".concat(script.toString("hex")); + str += " sequence ".concat(sequence.toString("hex")); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput ".concat(i, ":"); + str += " amount ".concat(amount.toString("hex")); + str += " script ".concat(script.toString("hex")); + }); + return str; } - /** - * 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) - } - - var length = byteLength(string, encoding) | 0; - var buf = createBuffer(length); - - var actual = buf.write(string, encoding); + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$e.alloc(0); + var nExpiryHeight = Buffer$e.alloc(0); + var nVersionGroupId = Buffer$e.alloc(0); + var extraData = Buffer$e.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$e.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$e.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$e.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$e.alloc(0); + var tree = Buffer$e.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree + }); + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; + } + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData + }; + log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); + return t; + } - 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); - } + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - return buf + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } - - function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - var buf = createBuffer(length); - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255; - } - return buf + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } - - function fromArrayView (arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) - } - return fromArrayLike(arrayView) + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; } - function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - var 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); - } + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype); - return buf - } - function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; - if (buf.length === 0) { - return buf + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } + } - obj.copy(buf, 0, 0, len); - return buf - } + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; } - return fromArrayLike(obj) - } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$3 = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } + function noop() {} + + var on = noop; + var addListener = noop; + var once$1 = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); } - 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') + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } } - return length | 0 + return [seconds,nanoseconds] } - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; - } - return Buffer.alloc(+length) + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; } - Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false + var process = { + nextTick: nextTick, + title: title, + browser: browser$3, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once$1, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime }; - 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 - - var x = a.length; - var y = b.length; + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); } } - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } - 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 + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; } }; - 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) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } + var browser$2 = invariant; - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(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); + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - 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 - ) - } - - var len = string.length; - var mustMatch = (arguments.length > 2 && arguments[2] === true); - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var 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 + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer.byteLength = byteLength; - - function slowToString (encoding, start, end) { - var 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) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this - }; - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$8(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$8(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$e.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$e.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$8(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$8(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$8(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$e.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$e.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$e.concat([ + transaction.version, + transaction.timestamp || Buffer$e.alloc(0), + transaction.nVersionGroupId || Buffer$e.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$e.compare(version, Buffer$e.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$e.from([0x00]) + : Buffer$e.alloc(0); + data = Buffer$e.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$e.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$e.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$e.concat([ + output.amount, + isDecred ? Buffer$e.from([0x00, 0x00]) : Buffer$e.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$e.concat(endData); + extraPart = isDecred + ? data + : Buffer$e.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$e.concat([locktime, extraPart || Buffer$e.alloc(0)]))]; + case 20: + res = _c.sent(); + browser$2(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } - Buffer.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var 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 - }; + var sha_js = {exports: {}}; - Buffer.prototype.toString = function toString () { - var length = this.length; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; + var inherits_browser = {exports: {}}; - Buffer.prototype.toLocaleString = Buffer.prototype.toString; + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + inherits_browser.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; + } + }; + } - 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 - }; + var safeBuffer = {exports: {}}; - Buffer.prototype.inspect = function inspect () { - var str = ''; - var 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; + var buffer = {}; + + var base64Js = {}; + + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i$1 = 0, len = code.length; i$1 < len; ++i$1) { + lookup[i$1] = code[i$1]; + revLookup[code.charCodeAt(i$1)] = i$1; } - 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) - ) - } + // 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; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + function getLens (b64) { + var len = b64.length; - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') } - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + // 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; - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4); - if (this === target) return 0 + return [validLen, placeHoldersLen] + } - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + // 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 + } - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } + function toByteArray (b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - // 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 + var curByte = 0; - // 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); - } + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen; - // 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 + 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; } - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[curByte++] = tmp & 0xFF; } - // 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) + 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; } - throw new TypeError('val must be string, number or Buffer') + return arr } - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } - 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 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 read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } + 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))); } - var i; - if (dir) { - var 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--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } + // 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 -1 + return parts.join('') } - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; + var ieee754 = {}; - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; + ieee754.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]; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + i += d; - var strLen = string.length; + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i - } + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } + 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) + }; - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } + ieee754.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; - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } + value = Math.abs(value); - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } + 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; + } - 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'; + 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 { - encoding = length; - length = undefined; + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) } - var 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') - } + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - if (!encoding) encoding = 'utf8'; + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + buffer[offset + i - d] |= s * 128; + }; - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - case 'ascii': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length) + (function (exports) { - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + var base64 = base64Js; + var ieee754$1 = ieee754; + var 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; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - }; + /** + * 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(); - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } + 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 utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) - ? 4 - : (firstByte > 0xDF) - ? 3 - : (firstByte > 0xBF) - ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var 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; + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { foo: function () { return 42 } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42 + } catch (e) { + return false } - - 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 - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer } + }); - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); + Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset } - return res - } - - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + }); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); + function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') } - return ret + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf } - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + /** + * 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. + */ - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + 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 ret + return from(arg, encodingOrOffset, length) } - function hexSlice (buf, start, end) { - var len = buf.length; + Buffer.poolSize = 8192; // not used by this implementation - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - var out = ''; - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) } - return out - } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - for (var i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); + 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) + ) } - return res - } - Buffer.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) } - if (end < start) end = start; + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - var newBuf = this.subarray(start, end); - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(newBuf, Buffer.prototype); + var b = fromObject(value); + if (b) return b - return newBuf - }; + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } - /* - * 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') + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) } - Buffer.prototype.readUintLE = - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val + /** + * 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) }; - Buffer.prototype.readUintBE = - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.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"') } + } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; + 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) + } - return val + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) }; - Buffer.prototype.readUint8 = - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; + function allocUnsafe (size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } - 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) + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) }; - - 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] + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) }; - 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) - }; + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } - Buffer.prototype.readUint32BE = - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + var actual = buf.write(string, encoding); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + 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); } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return buf + } - return val - }; + function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf + } - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) + } - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') } - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } - return val - }; + var 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); + } - 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) - }; + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + return buf + } - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); + if (buf.length === 0) { + return buf + } - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; + obj.copy(buf, 0, 0, len); + return buf + } - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, true, 23, 4) - }; + 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 + } - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, false, 23, 4) - }; + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) + } - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.read(this, offset, true, 52, 8) + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false }; - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.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) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + 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' + ) } - return offset + byteLength - }; + if (a === b) return 0 - Buffer.prototype.writeUintBE = - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + var x = a.length; + var y = b.length; - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } } - return offset + byteLength + if (x < y) return -1 + if (y < x) return 1 + return 0 }; - 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.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.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.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - 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 - }; + if (list.length === 0) { + return Buffer.alloc(0) + } - 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 - }; + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } - 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 + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(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 }; - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); + 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 + ) } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; + var len = string.length; + var mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var 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; } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } + } + Buffer.byteLength = byteLength; - return offset + byteLength - }; + function slowToString (encoding, start, end) { + var loweredCase = false; - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1); + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - checkInt(this, value, offset, byteLength, limit - 1, -limit); + // 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 '' } - var i = byteLength - 1; - var mul = 1; - var 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; + if (end === undefined || end > this.length) { + end = this.length; } - return offset + byteLength - }; + if (end <= 0) { + return '' + } - 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 - }; + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - 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 - }; + if (end <= start) { + return '' + } - 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 - }; + if (!encoding) encoding = 'utf8'; - 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 - }; + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - 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 - }; + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - 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') - } + case 'ascii': + return asciiSlice(this, start, end) - function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - ieee754$1.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; + case 'base64': + return base64Slice(this, start, end) - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } } - ieee754$1.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 + // 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; - // 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') + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') } - - var 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 - ); + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); } - - return len + return this }; - // 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) { - var 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); + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') } - - // 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') + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this + }; - if (end <= start) { - return this + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - - if (!val) val = 0; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding); - var 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]; - } + for (var 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 }; - // HELPER FUNCTIONS - // ================ + Buffer.prototype.toString = function toString () { + var length = this.length; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + Buffer.prototype.toLocaleString = Buffer.prototype.toString; - 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 + 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 () { + var str = ''; + var 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; } - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; + 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) + ) + } - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - // 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 - } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - // valid lead - leadSurrogate = codePoint; + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - continue - } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } + if (this === target) return 0 - // 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); - } + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - leadSurrogate = null; + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - // 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') + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break } } - return bytes - } + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); + // 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); } - return byteArray - } - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + // 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 + } - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); } - return byteArray - } + // 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) + } - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) + throw new TypeError('val must be string, number or Buffer') } - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var 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; + } } - 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 - var hexSliceLookupTable = (function () { - var alphabet = '0123456789abcdef'; - var table = new Array(256); - for (var i = 0; i < 16; ++i) { - var i16 = i * 16; - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) } } - return table - })(); - }(buffer)); - - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - - (function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - var buffer$1 = buffer; - var Buffer = buffer$1.Buffer; - // alternative to using Object.keys for old browsers - function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key]; + var i; + if (dir) { + var 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--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } } - } - if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer$1; - } else { - // Copy properties from require('buffer') - copyProps(buffer$1, exports); - exports.Buffer = SafeBuffer; - } - function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) + return -1 } - 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) + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 }; - 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 + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; - SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } } - return buffer$1.SlowBuffer(size) - }; - }(safeBuffer, safeBuffer.exports)); - var readableBrowser = {exports: {}}; + var strLen = string.length; - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + 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' + ) + } + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); + 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 drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var 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; } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } + } + 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; + } + } + } } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + + 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) } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser$6 = true; - var env = {}; - var argv = []; - var version$1 = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config$1 = {}; - function noop$2() {} + // 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 + var MAX_ARGUMENTS_LENGTH = 0x1000; - var on = noop$2; - var addListener = noop$2; - var once$3 = noop$2; - var off = noop$2; - var removeListener = noop$2; - var removeAllListeners = noop$2; - var emit = noop$2; + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - function binding(name) { - throw new Error('process.binding is not supported'); + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res } - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); } - return [seconds,nanoseconds] + return ret } - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret } - var process = { - nextTick: nextTick, - title: title, - browser: browser$6, - env: env, - argv: argv, - version: version$1, - versions: versions, - on: on, - addListener: addListener, - once: once$3, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config$1, - uptime: uptime - }; + function hexSlice (buf, start, end) { + var len = buf.length; - var events = {exports: {}}; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - 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 out = ''; + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out + } - 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 utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); + } + return res } - function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); - } + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; + 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; + + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); + + return newBuf }; - function EventEmitter() { - EventEmitter.init.call(this); + /* + * 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') } - events.exports = EventEmitter; - events.exports.once = once$2; - // Backwards-compat with node 0.10.x - EventEmitter.EventEmitter = EventEmitter; + Buffer.prototype.readUintLE = + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._eventsCount = 0; - EventEmitter.prototype._maxListeners = undefined; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - // 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; + return val + }; - function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + Buffer.prototype.readUintBE = + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - } - 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; + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - }); - EventEmitter.init = function() { + return val + }; - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } + Buffer.prototype.readUint8 = + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - this._maxListeners = this._maxListeners || undefined; + 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) }; - // 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; + 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] }; - function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; - } + Buffer.prototype.readUint32LE = + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) }; - EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); + Buffer.prototype.readUint32BE = + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; - // 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 + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } + mul *= 0x80; - var handler = events[type]; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if (handler === undefined) - return false; + return val + }; - 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); + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; } + mul *= 0x80; - return true; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val }; - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; + 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) + }; - checkListener(listener); + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - 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); + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - // 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]; - } + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - 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); - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; - // 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); - } - } + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - return target; - } + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, true, 23, 4) }; - EventEmitter.prototype.on = EventEmitter.prototype.addListener; + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, false, 23, 4) + }; - EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, true, 52, 8) + }; - 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); - } - } + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, false, 52, 8) + }; - 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; + 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') } - EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; + Buffer.prototype.writeUintLE = + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - // 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; + return offset + byteLength + }; - checkListener(listener); + Buffer.prototype.writeUintBE = + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - events = this._events; - if (events === undefined) - return this; + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - list = events[type]; - if (list === undefined) - return this; + return offset + byteLength + }; - 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; + 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 + }; - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } + 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 + }; - if (position < 0) - return this; + 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 + }; - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } + 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 + }; - if (list.length === 1) - events[type] = list[0]; + 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 + }; - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - return this; - }; + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + var i = 0; + var mul = 1; + var 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; + } - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; + return offset + byteLength + }; - events = this._events; - if (events === undefined) - return this; + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - // 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; - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - // 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; - } + var i = byteLength - 1; + var mul = 1; + var 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; + } - listeners = events[type]; + return offset + byteLength + }; - 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]); - } - } + 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 + }; - return this; - }; + 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 + }; - function _listeners(target, type, unwrap) { - var events = target._events; + 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 + }; - if (events === undefined) - return []; + 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 + }; - var evlistener = events[type]; - if (evlistener === undefined) - return []; + 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 + }; - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + 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') + } - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + ieee754$1.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 } - EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) }; - EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) }; - EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount$1.call(emitter, type); + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); } - }; + ieee754$1.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } - EventEmitter.prototype.listenerCount = listenerCount$1; - function listenerCount$1(type) { - var events = this._events; + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; - if (events !== undefined) { - var evlistener = events[type]; + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } + // 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; - return 0; - } + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; - }; + // 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') - function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; - } + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); - } + var len = end - start; - function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; + 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 ret; - } - function once$2(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } + return len + }; - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); + // 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; } - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') } - }); - } - - 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); + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) } - } 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); + if (val.length === 1) { + var 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; } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); } - } - - var EventEmitter$1 = events.exports; - - var streamBrowser = events.exports.EventEmitter; - - var _nodeResolve_empty = {}; - - var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': _nodeResolve_empty - }); - - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); - 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } - - function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // 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') + } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + if (end <= start) { + return this + } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - var _require$2 = buffer, - Buffer$l = _require$2.Buffer; + if (!val) val = 0; - var _require2 = require$$3, - inspect$1 = _require2.inspect; + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding); + var 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]; + } + } - var custom = inspect$1 && inspect$1.custom || 'inspect'; + return this + }; - function copyBuffer(src, target, offset) { - Buffer$l.prototype.copy.call(src, target, offset); - } + // HELPER FUNCTIONS + // ================ - var buffer_list = - /*#__PURE__*/ - function () { - function BufferList() { - _classCallCheck(this, BufferList); + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - this.head = null; - this.tail = null; - this.length = 0; + 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 + } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer$l.alloc(0); - var ret = Buffer$l.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - break; + // 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 } - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer$l.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } + // valid lead + leadSurrogate = codePoint; - ++c; + continue } - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect$1(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; - }(); - - function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - nextTick(emitErrorNT, this, err); + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well + // 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); + } - if (this._writableState) { - this._writableState.destroyed = true; - } + leadSurrogate = null; - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - nextTick(emitErrorAndCloseNT, _this, err); - } else { - nextTick(emitCloseNT, _this); - } - } else if (cb) { - nextTick(emitCloseNT, _this); - cb(err); + // 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 { - nextTick(emitCloseNT, _this); + throw new Error('Invalid code point') } - }); - - return this; - } + } - function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); + return bytes } - function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); + function asciiToBytes (str) { + var byteArray = []; + for (var 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 undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - 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; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); } - } - function emitErrorNT(self, err) { - self.emit('error', err); + return byteArray } - function errorOrDestroy$2(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) } - var destroy_1 = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy$2 - }; - - var errorsBrowser = {}; - - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - - var codes = {}; - - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; } + return i + } - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); + // 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 + } - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); + // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; } - } else { - return "of ".concat(thing, " ").concat(String(expected)); } - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - + return table + })(); + }(buffer)); - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer$1 = buffer; + var Buffer = buffer$1.Buffer; - function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; + // 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$1; + } else { + // Copy properties from require('buffer') + copyProps(buffer$1, exports); + exports.Buffer = SafeBuffer; + } - return str.substring(this_len - search.length, this_len) === search; - } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + SafeBuffer.prototype = Object.create(Buffer.prototype); - function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - } - - createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; + return Buffer(arg, encodingOrOffset, length) + }; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); + 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 { - determiner = 'must be'; + buf.fill(0); } + return buf + }; - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) + }; - msg += ". Received type ".concat(typeof actual); - return msg; - }, TypeError); - createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); - createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; - }); - createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); - createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' 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 (arg) { - return 'Unknown encoding: ' + arg; - }, TypeError); - createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - errorsBrowser.codes = codes; + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer$1.SlowBuffer(size) + }; + }(safeBuffer, safeBuffer.exports)); - var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + var Buffer$d = safeBuffer.exports.Buffer; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; } - function getHighWaterMark$2(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - return Math.floor(hwm); - } // Default value + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } + accum += remainder; + offset += remainder; - return state.objectMode ? 16 : 16 * 1024; - } + if ((accum % blockSize) === 0) { + this._update(block); + } + } - var state = { - getHighWaterMark: getHighWaterMark$2 + this._len += length; + return this }; - /** - * Module exports. - */ + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - var browser$5 = deprecate$1; + this._block[rem] = 0x80; - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - function deprecate$1 (fn, msg) { - if (config('noDeprecation')) { - return fn; + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); } - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + var bits = this._len * 8; - return deprecated; - } + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!commonjsGlobal.localStorage) return false; - } catch (_) { - return false; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); } - var val = commonjsGlobal.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; - } - var _stream_writable = Writable$2; - // there will be only 2 of these for each stream - - - function CorkedRequest$1(state) { - var _this = this; + this._update(this._block); + var hash = this._hash(); - this.next = null; - this.entry = null; + return enc ? hash.toString(enc) : hash + }; - this.finish = function () { - onCorkedFinish(_this, state); - }; - } - /* */ + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - /**/ + var hash = Hash$7; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - var Duplex$4; - /**/ + var inherits$c = inherits_browser.exports; + var Hash$6 = hash; + var Buffer$c = safeBuffer.exports.Buffer; - Writable$2.WritableState = WritableState$1; - /**/ + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - var internalUtil = { - deprecate: browser$5 - }; - /**/ + var W$5 = new Array(80); - /**/ + function Sha () { + this.init(); + this._w = W$5; - var Stream$2 = streamBrowser; - /**/ + Hash$6.call(this, 64, 56); + } + inherits$c(Sha, Hash$6); - var Buffer$k = buffer.Buffer; + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + return this + }; - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$k.from(chunk); + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) } - function _isUint8Array$1(obj) { - return Buffer$k.isBuffer(obj) || obj instanceof OurUint8Array$1; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) } - var destroyImpl$1 = destroy_1; - - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; - - var _require$codes$3 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + Sha.prototype._update = function (M) { + var W = this._w; - inherits_browser.exports(Writable$2, Stream$2); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - function nop$1() {} + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - function WritableState$1(options, stream, isDuplex) { - Duplex$4 = Duplex$4 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - this.finalCalled = false; // drain event flag. + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - this.needDrain = false; // at the start of calling end() + return H + }; - this.ending = false; // when end() has been called, and returned + var sha$2 = Sha; - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + var inherits$b = inherits_browser.exports; + var Hash$5 = hash; + var Buffer$b = safeBuffer.exports.Buffer; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + var K$2 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - this.length = 0; // a flag to see when we're in the middle of a write. + var W$4 = new Array(80); - this.writing = false; // when true all writes will be buffered until .uncork() call + function Sha1 () { + this.init(); + this._w = W$4; - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + Hash$5.call(this, 64, 56); + } - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. + inherits$b(Sha1, Hash$5); - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - this.onwrite = function (er) { - onwrite$1(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + return this + }; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - this.writecb = null; // the amount that is being written when _write is called. + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - this.prefinished = false; // True if the error was already emitted and should not be thrown again + Sha1.prototype._update = function (M) { + var W = this._w; - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - this.autoDestroy = !!options.autoDestroy; // count buffered requests + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } - this.corkedRequestsFree = new CorkedRequest$1(this); - } + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - WritableState$1.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - while (current) { - out.push(current); - current = current.next; - } + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - return out; + return H }; - (function () { - try { - Object.defineProperty(WritableState$1.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. + var sha1 = Sha1; + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - var realHasInstance; + var inherits$a = inherits_browser.exports; + var Hash$4 = hash; + var Buffer$a = safeBuffer.exports.Buffer; - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$2, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$2) return false; - return object && object._writableState instanceof WritableState$1; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; - } + var K$1 = [ + 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 Writable$2(options) { - Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$4; - if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); - this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + var W$3 = new Array(64); - this.writable = true; + function Sha256$1 () { + this.init(); - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } + this._w = W$3; // new Array(64) - Stream$2.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. + Hash$4.call(this, 64, 56); + } + inherits$a(Sha256$1, Hash$4); - Writable$2.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - function writeAfterEnd$1(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + return this + }; - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - function validChunk$1(stream, state, chunk, cb) { - var er; + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); - } + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - return true; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) } - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + Sha256$1.prototype._update = function (M) { + var W = this._w; - var isBuf = !state.objectMode && _isUint8Array$1(chunk); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - if (isBuf && !Buffer$k.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop$1; - if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; } - return ret; - }; - Writable$2.prototype.cork = function () { - this._writableState.corked++; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; }; - Writable$2.prototype.uncork = function () { - var state = this._writableState; + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; + return H }; - Object.defineProperty(Writable$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$k.from(chunk, encoding); - } + var sha256 = Sha256$1; - return chunk; - } - - Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk$1(state, chunk, encoding); + var inherits$9 = inherits_browser.exports; + var Sha256 = sha256; + var Hash$3 = hash; + var Buffer$9 = safeBuffer.exports.Buffer; - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } + var W$2 = new Array(64); - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + function Sha224 () { + this.init(); - if (!ret) state.needDrain = true; + this._w = W$2; // new Array(64) - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + Hash$3.call(this, 64, 56); + } - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } + inherits$9(Sha224, Sha256); - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); - } + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - return ret; - } + return this + }; - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error + return H + }; - nextTick(finishMaybe$1, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error + var sha224 = Sha224; - finishMaybe$1(stream, state); - } - } + var inherits$8 = inherits_browser.exports; + var Hash$2 = hash; + var Buffer$8 = safeBuffer.exports.Buffer; - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 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 + ]; - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state) || stream.destroyed; + var W$1 = new Array(160); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + function Sha512 () { + this.init(); + this._w = W$1; - if (sync) { - nextTick(afterWrite$1, stream, state, finished, cb); - } else { - afterWrite$1(stream, state, finished, cb); - } - } + Hash$2.call(this, 128, 112); } - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - + inherits$8(Sha512, Hash$2); - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + return this + }; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - buffer.allBuffers = allBuffers; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - state.pendingcb++; - state.lastBufferedRequest = null; + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest$1(state); - } + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - if (state.writing) { - break; - } - } + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - if (entry === null) state.lastBufferedRequest = null; - } + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - state.bufferedRequest = entry; - state.bufferProcessing = false; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 } - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; + Sha512.prototype._update = function (M) { + var W = this._w; - Writable$2.prototype._writev = null; + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable$1(this, state, cb); - return this; - }; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - Object.defineProperty(Writable$2.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } - }); + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - if (err) { - errorOrDestroy$1(stream, err); - } + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe$1(stream, state); - }); - } + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - function prefinish$2(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } + W[i] = Wih; + W[i + 1] = Wil; } - } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - if (need) { - prefinish$2(stream, state); + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j]; + var Kil = K[j + 1]; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - return need; - } + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; } - state.ended = true; - stream.writable = false; - } - - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; - } - - Object.defineProperty(Writable$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } - }); - Writable$2.prototype.destroy = destroyImpl$1.destroy; - Writable$2.prototype._undestroy = destroyImpl$1.undestroy; + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - Writable$2.prototype._destroy = function (err, cb) { - cb(err); + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; }; - /**/ - - var objectKeys = Object.keys || function (obj) { - var keys = []; + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - for (var key in obj) { - keys.push(key); + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - return keys; - }; - /**/ - + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - var _stream_duplex = Duplex$3; + return H + }; - var Readable$2 = _stream_readable; + var sha512 = Sha512; - var Writable$1 = _stream_writable; + var inherits$7 = inherits_browser.exports; + var SHA512 = sha512; + var Hash$1 = hash; + var Buffer$7 = safeBuffer.exports.Buffer; - inherits_browser.exports(Duplex$3, Readable$2); + var W = new Array(160); - { - // Allow the keys array to be GC'ed. - var keys$1 = objectKeys(Writable$1.prototype); + function Sha384 () { + this.init(); + this._w = W; - for (var v$1 = 0; v$1 < keys$1.length; v$1++) { - var method$1 = keys$1[v$1]; - if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; - } + Hash$1.call(this, 128, 112); } - function Duplex$3(options) { - if (!(this instanceof Duplex$3)) return new Duplex$3(options); - Readable$2.call(this, options); - Writable$1.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + inherits$7(Sha384, SHA512); - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend$1); - } - } - } + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); // the no-half-open enforcer + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; - function onend$1() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + return this + }; - nextTick(onEndNT$1, this); - } + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - function onEndNT$1(self) { - self.end(); - } + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - Object.defineProperty(Duplex$3.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + return H + }; + var sha384 = Sha384; - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - var string_decoder$1 = {}; + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - /**/ + return new Algorithm() + }; - var Buffer$j = safeBuffer.exports.Buffer; - /**/ + exports$1.sha = sha$2; + exports$1.sha1 = sha1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - var isEncoding = Buffer$j.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; - } - }; + var sha$1 = sha_js.exports; - 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; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$e.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$e.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$e.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); } - } - } - // 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$j.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. - string_decoder$1.StringDecoder = StringDecoder$3; - function StringDecoder$3(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$j.allocUnsafe(nb); - } - - StringDecoder$3.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$3.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$3.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$3.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; + return outputBuffer; } - - // 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; + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$e.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$e.concat([ + inputBuffer, + input.prevout, + Buffer$e.from([0x00]), + input.sequence, + ]) + : Buffer$e.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$e.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$e.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$e.alloc(0), + transaction.extraData || Buffer$e.alloc(0), + ]); } - return nb; - } - return 0; + return Buffer$e.concat([ + transaction.version, + timestamp ? timestamp : Buffer$e.alloc(0), + transaction.nVersionGroupId || Buffer$e.alloc(0), + useWitness ? Buffer$e.from("0001", "hex") : Buffer$e.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); } - // 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'; - } + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); } - } - } - - // 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); - 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); - } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); + var hash = sha$1("sha256") + .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$e.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$e.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); } - // 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; - } + var readable = {exports: {}}; - 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); - } + var events = {exports: {}}; - 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; - } + 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); + }; - // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) - function simpleWrite(buf) { - return buf.toString(this.encoding); + 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 simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); } - var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; + }; - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; + function EventEmitter() { + EventEmitter.init.call(this); + } + events.exports = EventEmitter; + events.exports.once = once; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; - callback.apply(this, args); - }; - } + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._eventsCount = 0; + EventEmitter.prototype._maxListeners = undefined; - function noop$1() {} + // 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 isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; + function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } } - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; + 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; + } + }); - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + EventEmitter.init = function() { - var writableEnded = stream._writableState && stream._writableState.finished; + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; + this._maxListeners = this._maxListeners || undefined; + }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; + // 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; + }; - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } - var onerror = function onerror(err) { - callback.call(stream, err); - }; + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; - var onclose = function onclose() { - var err; + EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + // 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 } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + // 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 } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; - } + var handler = events[type]; - var endOfStream = eos$1; + if (handler === undefined) + return false; - var _Object$setPrototypeO; + 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); + } - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + return true; + }; - var finished = endOfStream; + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); + checkListener(listener); - function createIterResult(value, done) { - return { - value: value, - done: done - }; - } - - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' + 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); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + // 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]; } - } - - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } - - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } - - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); + 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); } - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); + // 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); } + } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time + return target; + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; - var lastPromise = this[kLastPromise]; - var promise; + EventEmitter.prototype.on = EventEmitter.prototype.addListener; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + 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); + } + } - promise = new Promise(this[kHandlePromise]); - } + 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; + } - this[kLastPromise] = promise; - return promise; - } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; + }; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } + // 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; - iterator[kError] = err; - return; - } + checkListener(listener); - var resolve = iterator[kLastResolve]; + events = this._events; + if (events === undefined) + return this; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + list = events[type]; + if (list === undefined) + return this; - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; + 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; - var async_iterator = createReadableStreamAsyncIterator$1; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } - var fromBrowser = function () { - throw new Error('Readable.from is not available in the browser') - }; + if (position < 0) + return this; - var _stream_readable = Readable$1; - /**/ + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } - var Duplex$2; - /**/ + if (list.length === 1) + events[type] = list[0]; - Readable$1.ReadableState = ReadableState$1; - /**/ + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } - events.exports.EventEmitter; + return this; + }; - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - /**/ + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + events = this._events; + if (events === undefined) + return this; - var Stream$1 = streamBrowser; - /**/ + // 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; + } - var Buffer$i = buffer.Buffer; + listeners = events[type]; - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + 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]); + } + } - function _uint8ArrayToBuffer(chunk) { - return Buffer$i.from(chunk); - } + return this; + }; - function _isUint8Array(obj) { - return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ + function _listeners(target, type, unwrap) { + var events = target._events; + if (events === undefined) + return []; - var debugUtil = require$$3; + var evlistener = events[type]; + if (evlistener === undefined) + return []; - var debug$9; + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - if (debugUtil && debugUtil.debuglog) { - debug$9 = debugUtil.debuglog('stream'); - } else { - debug$9 = function debug() {}; + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } - /**/ + EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; - var BufferList$1 = buffer_list; + EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; - var destroyImpl = destroy_1; + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; - var _require = state, - getHighWaterMark = _require.getHighWaterMark; + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; - var _require$codes$2 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + if (events !== undefined) { + var evlistener = events[type]; + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } - var StringDecoder$2; - var createReadableStreamAsyncIterator; - var from; + return 0; + } - inherits_browser.exports(Readable$1, Stream$1); - - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - - function prependListener$1(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; } - function ReadableState$1(options, stream, isDuplex) { - Duplex$2 = Duplex$2 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList$1(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } - if (options.encoding) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - this.decoder = new StringDecoder$2(options.encoding); - this.encoding = options.encoding; + 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 Readable$1(options) { - Duplex$2 = Duplex$2 || _stream_duplex; - if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex$2; - this._readableState = new ReadableState$1(options, this, isDuplex); // legacy + function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } - this.readable = true; + 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 }); + } + }); + } - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } - - Stream$1.call(this); } - Object.defineProperty(Readable$1.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; + } 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); } - }); - Readable$1.prototype.destroy = destroyImpl.destroy; - Readable$1.prototype._undestroy = destroyImpl.undestroy; - - Readable$1.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - - - Readable$1.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + } - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + var EventEmitter$1 = events.exports; - if (encoding !== state.encoding) { - chunk = Buffer$i.from(chunk, encoding); - encoding = ''; + var inherits$5; + if (typeof Object.create === 'function'){ + inherits$5 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } + }); + }; + } else { + inherits$5 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$6 = inherits$5; - skipChunkCheck = true; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); } - } else { - skipChunkCheck = true; + return objects.join(' '); } - return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() - - - Readable$1.prototype.unshift = function (chunk) { - return readableAddChunk$1(this, chunk, null, true, false); - }; - - function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$9('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + 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$1(x) || !isObject$1(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined$1(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); - } else { - addChunk(stream, state, chunk, false); - } + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); } - } else if (!addToFront) { - state.reading = false; - maybeReadMore$1(stream, state); + warned = true; } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - + return fn.apply(this, arguments); + } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); + return deprecated; } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable$1(stream); + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined$1(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } } - - maybeReadMore$1(stream, state); + return debugs[set]; } - function chunkInvalid$1(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + /** + * 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$1(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); } - - return er; + // set default options + if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined$1(ctx.depth)) ctx.depth = 2; + if (isUndefined$1(ctx.colors)) ctx.colors = false; + if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } - Readable$1.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. - - - Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$2) StringDecoder$2 = string_decoder$1.StringDecoder; - var decoder = new StringDecoder$2(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); + // 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] + }; - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB + // 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' + }; - var MAX_HWM$1 = 0x40000000; + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - function computeNewHighWaterMark$1(n) { - if (n >= MAX_HWM$1) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM$1; + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + return str; } + } - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + function stylizeNoColor(str, styleType) { + return str; + } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); - if (n <= state.length) return n; // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } + function arrayToHash(array) { + var hash = {}; - return state.length; - } // you can override either this method, or the async _read(n) below. + array.forEach(function(val, idx) { + hash[val] = true; + }); + return hash; + } - Readable$1.prototype.read = function (n) { - debug$9('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$9('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; + 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$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== 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$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; } - n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug$9('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$9('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug$9('reading or ended', doRead); - } else if (doRead) { - debug$9('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - if (state.length === 0) state.needReadable = true; // call internal read method + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - this._read(state.highWaterMark); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError$1(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - if (!state.reading) n = howMuchToRead$1(nOrig, state); + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate$1(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError$1(value)) { + return formatError(value); + } } - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + var base = '', array = false, braces = ['{', '}']; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; + // Make Array say that they are Array + if (isArray$2(value)) { + array = true; + braces = ['[', ']']; } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - if (nOrig !== n && state.ended) endReadable$1(this); + // Make RegExps say that they are RegExps + if (isRegExp$1(value)) { + base = ' ' + RegExp.prototype.toString.call(value); } - if (ret !== null) this.emit('data', ret); - return ret; - }; + // Make dates with properties first say the date + if (isDate$1(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - function onEofChunk$1(stream, state) { - debug$9('onEofChunk'); - if (state.ended) return; + // Make error with message first say the error + if (isError$1(value)) { + base = ' ' + formatError(value); + } - if (state.decoder) { - var chunk = state.decoder.end(); + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + if (recurseTimes < 0) { + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); } } - state.ended = true; + ctx.seen.push(value); - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable$1(stream); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_$1(stream); - } + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + ctx.seen.pop(); - function emitReadable$1(stream) { - var state = stream._readableState; - debug$9('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + return reduceToSingleString(output, base, braces); + } - if (!state.emittedReadable) { - debug$9('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_$1, stream); + + function formatPrimitive(ctx, value) { + if (isUndefined$1(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); } + if (isNumber$1(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean$1(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull$1(value)) + return ctx.stylize('null', 'null'); } - function emitReadable_$1(stream) { - var state = stream._readableState; - debug$9('emitReadable_', state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow$1(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - - - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); + 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 maybeReadMore_$1(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug$9('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - - - Readable$1.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); - }; - - Readable$1.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; + 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'); + } } - - state.pipesCount += 1; - debug$9('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug$9('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull$1(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$1(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'); } } - function onend() { - debug$9('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); - var cleanedUp = false; + return name + ': ' + str; + } - function cleanup() { - debug$9('cleanup'); // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; } - src.on('data', ondata); + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } - function ondata(chunk) { - debug$9('ondata'); - var ret = dest.write(chunk); - debug$9('dest.write', ret); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$9('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$2(ar) { + return Array.isArray(ar); + } - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + function isBoolean$1(arg) { + return typeof arg === 'boolean'; + } + function isNull$1(arg) { + return arg === null; + } - function onerror(er) { - debug$9('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + function isNumber$1(arg) { + return typeof arg === 'number'; + } + function isString$1(arg) { + return typeof arg === 'string'; + } - prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + function isUndefined$1(arg) { + return arg === void 0; + } - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + function isRegExp$1(re) { + return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; + } - dest.once('close', onclose); + function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; + } - function onfinish() { - debug$9('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } + function isDate$1(d) { + return isObject$1(d) && objectToString$1(d) === '[object Date]'; + } - dest.once('finish', onfinish); + function isError$1(e) { + return isObject$1(e) && + (objectToString$1(e) === '[object Error]' || e instanceof Error); + } - function unpipe() { - debug$9('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + function isFunction$1(arg) { + return typeof arg === 'function'; + } + function objectToString$1(o) { + return Object.prototype.toString.call(o); + } - dest.emit('pipe', src); // start the flow if it hasn't been started already. + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$1(add)) return origin; - if (!state.flowing) { - debug$9('pipe resume'); - src.resume(); + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } - - return dest; - }; - - function pipeOnDrain$1(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug$9('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow$1(src); - } - }; + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } - Readable$1.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - if (state.pipesCount === 0) return this; // just one destination. most common case. + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - return this; - } // try to find the right one. + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + var string_decoder = {}; - var index = indexOf$1(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something + var StringDecoder_1; + // 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$6 = buffer.Buffer; - Readable$1.prototype.on = function (ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); - var state = this._readableState; + var isBufferEncoding = Buffer$6.isEncoding + || function(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; + } + }; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug$9('on readable', state.length, state.reading); + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } - if (state.length) { - emitReadable$1(this); - } else if (!state.reading) { - nextTick(nReadingNextTick$1, this); - } - } + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; } - return res; + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$6(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; }; - Readable$1.prototype.addListener = Readable$1.prototype.on; - - Readable$1.prototype.removeListener = function (ev, fn) { - var res = Stream$1.prototype.removeListener.call(this, ev, fn); - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$2.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - return res; - }; + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; - Readable$1.prototype.removeAllListeners = function (ev) { - var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); - return res; - }; + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; } - } - - function nReadingNextTick$1(self) { - debug$9('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - Readable$1.prototype.resume = function () { - var state = this._readableState; + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - if (!state.flowing) { - debug$9('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + charStr += buffer.toString(this.encoding, 0, end); - state.flowing = !state.readableListening; - resume$1(this, state); + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); } - state.paused = false; - return this; + // or just emit the charStr + return charStr; }; - function resume$1(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_$1, stream, state); - } - } + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; - function resume_$1(stream, state) { - debug$9('resume', state.reading); + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; - if (!state.reading) { - stream.read(0); - } + // See http://en.wikipedia.org/wiki/UTF-8#Description - state.resumeScheduled = false; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); - } + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - Readable$1.prototype.pause = function () { - debug$9('call pause flowing=%j', this._readableState.flowing); + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - if (this._readableState.flowing !== false) { - debug$9('pause'); - this._readableState.flowing = false; - this.emit('pause'); + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } } - - this._readableState.paused = true; - return this; + this.charReceived = i; }; - function flow$1(stream) { - var state = stream._readableState; - debug$9('flow', state.flowing); + StringDecoder$2.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - while (state.flowing && stream.read() !== null) { + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - - Readable$1.prototype.wrap = function (stream) { - var _this = this; + return res; + }; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug$9('wrapped end'); + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug$9('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug$9('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; - }; - - if (typeof Symbol === 'function') { - Readable$1.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; - } + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } - return createReadableStreamAsyncIterator(this); - }; + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } - Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable$1.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } - }); // exposed for testing purposes only. + Readable$2.ReadableState = ReadableState$1; - Readable$1._fromList = fromList$1; - Object.defineProperty(Readable$1.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. + var debug$4 = debuglog('stream'); + inherits$6(Readable$2, EventEmitter$1); - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; } - return ret; } - - function endReadable$1(stream) { - var state = stream._readableState; - debug$9('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT$1, state, stream); - } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; } + function ReadableState$1(options, stream) { - function endReadableNT$1(state, stream) { - debug$9('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } + options = options || {}; - if (typeof Symbol === 'function') { - Readable$1.from = function (iterable, opts) { - if (from === undefined) { - from = fromBrowser; - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - return from(Readable$1, iterable, opts); - }; - } + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - return -1; - } + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - var _stream_transform = Transform$4; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - var _require$codes$1 = errorsBrowser.codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var Duplex$1 = _stream_duplex; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - inherits_browser.exports(Transform$4, Duplex$1); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - function afterTransform$1(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; } } + function Readable$2(options) { - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); - Duplex$1.call(this, options); - this._transformState = { - afterTransform: afterTransform$1.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. + if (!(this instanceof Readable$2)) return new Readable$2(options); - this._readableState.sync = false; + this._readableState = new ReadableState$1(options, this); - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. + // legacy + this.readable = true; + if (options && typeof options.read === 'function') this._read = options.read; - this.on('prefinish', prefinish$1); + EventEmitter$1.call(this); } - function prefinish$1() { - var _this = this; + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$2.prototype.push = function (chunk, encoding) { + var state = this._readableState; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done$1(_this, er, data); - }); - } else { - done$1(this, null, null); + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$e.from(chunk, encoding); + encoding = ''; + } } - } - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$1.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. + return readableAddChunk$1(this, state, chunk, encoding, false); + }; + // Unshift should *always* be something directly out of read() + Readable$2.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk$1(this, state, chunk, '', true); + }; - Transform$4.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + Readable$2.prototype.isPaused = function () { + return this._readableState.flowing === false; }; - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid$1(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. + if (!addToFront) state.reading = false; + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + if (state.needReadable) emitReadable$1(stream); + } + } - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + maybeReadMore$1(stream, state); + } + } else if (!addToFront) { + state.reading = false; } - }; - - Transform$4.prototype._destroy = function (err, cb) { - Duplex$1.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); - }; - - function done$1(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); + return needMoreData$1(state); } - var _stream_passthrough = PassThrough$1; - - var Transform$3 = _stream_transform; - - inherits_browser.exports(PassThrough$1, Transform$3); - - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$3.call(this, options); + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData$1(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + // backwards compatibility. + Readable$2.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; }; - var eos; + // Don't raise the hwm > 8MB + var MAX_HWM$1 = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM$1) { + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } - function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; } - var _require$codes = errorsBrowser.codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + // you can override either this method, or the async _read(n) below. + Readable$2.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; - } + if (n !== 0) state.emittedReadable = false; - function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; - } + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = endOfStream; - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; - } + n = howMuchToRead$1(n, state); - function call(fn) { - fn(); - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } - function pipe(from, to) { - return from.pipe(to); - } + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead$1(nOrig, state); } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; } - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - var pipeline_1 = pipeline; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable$1(this); + } - (function (module, exports) { - exports = module.exports = _stream_readable; - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - exports.finished = endOfStream; - exports.pipeline = pipeline_1; - }(readableBrowser, readableBrowser.exports)); + if (ret !== null) this.emit('data', ret); - var Buffer$h = safeBuffer.exports.Buffer; - var Transform$2 = readableBrowser.exports.Transform; - var inherits$i = inherits_browser.exports; + return ret; + }; - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$h.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + function chunkInvalid$1(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } + return er; } - function HashBase$2 (blockSize) { - Transform$2.call(this); + function onEofChunk$1(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - this._block = Buffer$h.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + // emit 'readable' now to make sure it gets picked up. + emitReadable$1(stream); + } - this._finalized = false; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable$1(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); + } } - inherits$i(HashBase$2, Transform$2); + function emitReadable_$1(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow$1(stream); + } - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); } + } - callback(error); - }; - - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; + function maybeReadMore_$1(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } + state.readingMore = false; + } - callback(error); + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$2.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); }; - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$h.isBuffer(data)) data = Buffer$h.from(data, encoding); + Readable$2.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } + var doEnd = (!pipeOpts || pipeOpts.end !== false); - return this - }; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + function onend() { + debug$4('onend'); + dest.end(); + } - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - return digest - }; + cleanedUp = true; - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - var hashBase = HashBase$2; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } - var inherits$h = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$g = safeBuffer.exports.Buffer; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } - var ARRAY16$1 = new Array(16); + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - function MD5$2 () { - HashBase$1.call(this, 64); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - inherits$h(MD5$2, HashBase$1); + // tell the dest that it's being piped to + dest.emit('pipe', src); - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + return dest; + }; - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + function pipeOnDrain$1(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow$1(src); + } + }; + } - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + Readable$2.prototype.unpipe = function (dest) { + var state = this._readableState; - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; + if (!dest) dest = state.pipes; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // slow case. multiple pipe destinations. - // produce result - var buffer = Buffer$g.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer - }; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 - } + // try to find the right one. + var i = indexOf$1(state.pipes, dest); + if (i === -1) return this; - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + dest.emit('unpipe', this); - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 - } + return this; + }; - var md5_js = MD5$2; + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$2.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - var Buffer$f = buffer.Buffer; - var inherits$g = inherits_browser.exports; - var HashBase = hashBase; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable$1(this); + } + } + } - var ARRAY16 = new Array(16); + return res; + }; + Readable$2.prototype.addListener = Readable$2.prototype.on; - var zl = [ - 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 - ]; + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); + } - var zr = [ - 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 - ]; + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$2.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; - var sl = [ - 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 - ]; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } - var sr = [ - 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 - ]; + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); + } - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - function RIPEMD160$3 () { - HashBase.call(this, 64); + Readable$2.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + function flow$1(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } - inherits$g(RIPEMD160$3, HashBase); + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$2.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + self.push(null); + }); - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } + }); - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } } - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$2(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - // produce result - var buffer = Buffer$f.alloc ? Buffer$f.alloc(20) : new Buffer$f(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + return self; }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + // exposed for testing purposes only. + Readable$2._fromList = fromList$1; - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; } - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - var ripemd160$2 = RIPEMD160$3; + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$e.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } - var sha_js = {exports: {}}; + function endReadable$1(stream) { + var state = stream._readableState; - var Buffer$e = safeBuffer.exports.Buffer; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$e.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$e.from(data, enc); + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); } + } - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; - } - - accum += remainder; - offset += remainder; + function forEach$2(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - if ((accum % blockSize) === 0) { - this._update(block); - } + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } + return -1; + } - this._len += length; - return this - }; + // A bit simpler than readable streams. + Writable$2.WritableState = WritableState$1; + inherits$6(Writable$2, events.exports.EventEmitter); - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + function nop() {} - this._block[rem] = 0x80; + function WriteReq$1(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + function WritableState$1(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - var bits = this._len * 8; + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); - } + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - this._update(this._block); - var hash = this._hash(); + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - return enc ? hash.toString(enc) : hash - }; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - var hash$3 = Hash$7; + // a flag to see when we're in the middle of a write. + this.writing = false; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + // when true all writes will be buffered until .uncork() call + this.corked = 0; - var inherits$f = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$d = safeBuffer.exports.Buffer; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var W$5 = new Array(80); + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite$1(stream, er); + }; - function Sha () { - this.init(); - this._w = W$5; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - Hash$6.call(this, 64, 56); - } + // the amount that is being written when _write is called. + this.writelen = 0; - inherits$f(Sha, Hash$6); + this.bufferedRequest = null; + this.lastBufferedRequest = null; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - return this + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; }; + function Writable$2(options) { - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); + + this._writableState = new WritableState$1(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + events.exports.EventEmitter.call(this); } - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) + // Otherwise people can pipe Writable streams, which is just wrong. + Writable$2.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd$1(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); } - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk$1(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; } - Sha.prototype._update = function (M) { - var W = this._w; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + if (typeof cb !== 'function') cb = nop; - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; + if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, chunk, encoding, cb); } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + return ret; }; - Sha.prototype._hash = function () { - var H = Buffer$d.allocUnsafe(20); - - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + Writable$2.prototype.cork = function () { + var state = this._writableState; - return H + state.corked++; }; - var sha$4 = Sha; + Writable$2.prototype.uncork = function () { + var state = this._writableState; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + if (state.corked) { + state.corked--; - var inherits$e = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - var W$4 = new Array(80); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; + } - function Sha1 () { - this.init(); - this._w = W$4; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer$1(stream, state, chunk, encoding, cb) { + chunk = decodeChunk$1(state, chunk, encoding); - Hash$5.call(this, 64, 56); - } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - inherits$e(Sha1, Hash$5); + state.length += len; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - return this - }; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); + } - function rotl1 (num) { - return (num << 1) | (num >>> 31) + return ret; } - function rotl5 (num) { - return (num << 5) | (num >>> 27) + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - function rotl30 (num) { - return (num << 30) | (num >>> 2) + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - Sha1.prototype._update = function (M) { - var W = this._w; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + onwriteStateUpdate$1(state); - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state); - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + if (sync) { + /**/ + nextTick(afterWrite$1, stream, state, finished, cb); + /**/ + } else { + afterWrite$1(stream, state, finished, cb); + } } + } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } - Sha1.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // if there's something in the buffer waiting, then process it + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - return H - }; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - var sha1$1 = Sha1; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); - var inherits$d = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - var K$2 = [ - 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 - ]; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - var W$3 = new Array(64); + if (entry === null) state.lastBufferedRequest = null; + } - function Sha256$1 () { - this.init(); + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - this._w = W$3; // new Array(64) + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - Hash$4.call(this, 64, 56); - } + Writable$2.prototype._writev = null; - inherits$d(Sha256$1, Hash$4); + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - return this - }; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - function ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable$1(this, state, cb); + }; - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; } - Sha256$1.prototype._update = function (M) { - var W = this._w; + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + this.next = null; + this.entry = null; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + inherits$6(Duplex$2, Readable$2); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; - } + var keys = Object.keys(Writable$2.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; + } + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; + Readable$2.call(this, options); + Writable$2.call(this, options); - Sha256$1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(32); + if (options && options.readable === false) this.readable = false; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + if (options && options.writable === false) this.writable = false; - return H - }; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - var sha256$2 = Sha256$1; + this.once('end', onend$1); + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + // the no-half-open enforcer + function onend$1() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - var inherits$c = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } - var W$2 = new Array(64); + function onEndNT(self) { + self.end(); + } - function Sha224 () { - this.init(); + // a transform stream is a readable/writable stream where you do + inherits$6(Transform$4, Duplex$2); - this._w = W$2; // new Array(64) + function TransformState$1(stream) { + this.afterTransform = function (er, data) { + return afterTransform$1(stream, er, data); + }; - Hash$3.call(this, 64, 56); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; } - inherits$c(Sha224, Sha256); + function afterTransform$1(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + var cb = ts.writecb; - return this - }; + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - Sha224.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(28); + ts.writechunk = null; + ts.writecb = null; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + if (data !== null && data !== undefined) stream.push(data); - return H - }; + cb(er); - var sha224 = Sha224; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); - var inherits$b = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + Duplex$2.call(this, options); - var K$1 = [ - 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 - ]; + this._transformState = new TransformState$1(this); - var W$1 = new Array(160); + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function Sha512 () { - this.init(); - this._w = W$1; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - Hash$2.call(this, 128, 112); - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - inherits$b(Sha512, Hash$2); + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + if (typeof options.flush === 'function') this._flush = options.flush; + } - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done$1(stream, er); + });else done$1(stream); + }); + } - return this + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$2.prototype.push.call(this, chunk, encoding); }; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$4.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + function done$1(stream, er) { + if (er) return stream.emit('error', er); - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); } - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + inherits$6(PassThrough$1, Transform$4); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + + Transform$4.call(this, options); } - Sha512.prototype._update = function (M) { - var W = this._w; + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + inherits$6(Stream$2, EventEmitter$1); + Stream$2.Readable = Readable$2; + Stream$2.Writable = Writable$2; + Stream$2.Duplex = Duplex$2; + Stream$2.Transform = Transform$4; + Stream$2.PassThrough = PassThrough$1; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + // Backwards-compat with node 0.4.x + Stream$2.Stream = Stream$2; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + function Stream$2() { + EventEmitter$1.call(this); + } - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + Stream$2.prototype.pipe = function(dest, options) { + var source = this; - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + source.on('data', ondata); - W[i] = Wih; - W[i + 1] = Wil; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + dest.on('drain', ondrain); - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + dest.end(); + } - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + if (typeof dest.destroy === 'function') dest.destroy(); + } - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } } - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + source.on('error', onerror); + dest.on('error', onerror); - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - Sha512.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(64); + source.removeListener('end', onend); + source.removeListener('close', onclose); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - return H - }; + dest.removeListener('close', cleanup); + } - var sha512 = Sha512; + source.on('end', cleanup); + source.on('close', cleanup); - var inherits$a = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + dest.on('close', cleanup); - var W = new Array(160); + dest.emit('pipe', source); - function Sha384 () { - this.init(); - this._w = W; + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; - Hash$1.call(this, 128, 112); - } + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream$2, + Readable: Readable$2, + Writable: Writable$2, + Duplex: Duplex$2, + Transform: Transform$4, + PassThrough: PassThrough$1, + Stream: Stream$2 + }); - inherits$a(Sha384, SHA512$2); + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + var isarray = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; + }; - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + var util$5 = {}; - return this - }; + // 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. - Sha384.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(48); + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + function isArray$1(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; + } + util$5.isArray = isArray$1; - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + util$5.isBoolean = isBoolean; - return H - }; + function isNull(arg) { + return arg === null; + } + util$5.isNull = isNull; - var sha384 = Sha384; + function isNullOrUndefined(arg) { + return arg == null; + } + util$5.isNullOrUndefined = isNullOrUndefined; - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + function isNumber(arg) { + return typeof arg === 'number'; + } + util$5.isNumber = isNumber; - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + function isString(arg) { + return typeof arg === 'string'; + } + util$5.isString = isString; - return new Algorithm() - }; + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + util$5.isSymbol = isSymbol; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + function isUndefined(arg) { + return arg === void 0; + } + util$5.isUndefined = isUndefined; - var sha$3 = sha_js.exports; + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + util$5.isRegExp = isRegExp; - var inherits$8; - if (typeof Object.create === 'function'){ - inherits$8 = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$8 = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + function isObject(arg) { + return typeof arg === 'object' && arg !== null; } - var inherits$9 = inherits$8; - - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + util$5.isObject = isObject; - 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; + function isDate(d) { + return objectToString(d) === '[object Date]'; } + util$5.isDate = isDate; - // 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + util$5.isError = isError; - return deprecated; + function isFunction(arg) { + return typeof arg === 'function'; } + util$5.isFunction = isFunction; - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; } + util$5.isPrimitive = isPrimitive; - /** - * 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 - _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); + util$5.isBuffer = buffer.Buffer.isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); } - // 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] - }; + // 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. - // 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' - }; + var _stream_readable = Readable$1; + /**/ + var isArray = isarray; + /**/ - 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; - } - } + /**/ + var Buffer$5 = buffer.Buffer; + /**/ + Readable$1.ReadableState = ReadableState; - function stylizeNoColor(str, styleType) { - return str; - } + var EE = events.exports.EventEmitter; + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - function arrayToHash(array) { - var hash = {}; + var Stream$1 = require$$1; - array.forEach(function(val, idx) { - hash[val] = true; - }); + /**/ + var util$4 = util$5; + util$4.inherits = inherits_browser.exports; + /**/ - return hash; - } + var StringDecoder$1; + util$4.inherits(Readable$1, Stream$1); - 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 !== 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; - } + function ReadableState(options, stream) { + options = options || {}; - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; - // 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); - } + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; - // 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 = ['[', ']']; - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; - // 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); - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - ctx.seen.push(value); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - 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); - }); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); } + function Readable$1(options) { + if (!(this instanceof Readable$1)) + return new Readable$1(options); - 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'); - } + this._readableState = new ReadableState(options, this); + // legacy + this.readable = true; - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + Stream$1.call(this); } + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$1.prototype.push = function(chunk, encoding) { + var state = this._readableState; - 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(''); + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer$5(chunk, encoding); + encoding = ''; } } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } + return readableAddChunk(this, state, chunk, encoding, false); + }; - 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'); + // Unshift should *always* be something directly out of read() + Readable$1.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); } 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); + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); } 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'); - } + state.reading = false; + state.buffer.push(chunk); } - } 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'); + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); } + } else if (!addToFront) { + state.reading = false; } - return name + ': ' + str; + return needMoreData(state); } - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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]; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); } + // backwards compatibility. + Readable$1.prototype.setEncoding = function(enc) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this._readableState.decoder = new StringDecoder$1(enc); + this._readableState.encoding = enc; + }; - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; + // Don't raise the hwm > 128MB + var MAX_HWM = 0x800000; + function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; } - function isNull(arg) { - return arg === null; - } + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; - function isNumber(arg) { - return typeof arg === 'number'; - } + if (state.objectMode) + return n === 0 ? 0 : 1; - function isString(arg) { - return typeof arg === 'string'; - } + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } - function isUndefined(arg) { - return arg === void 0; - } + if (n <= 0) + return 0; - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + return n; } - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } + // you can override either this method, or the async _read(n) below. + Readable$1.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; - function isFunction(arg) { - return typeof arg === 'function'; - } + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - function objectToString(o) { - return Object.prototype.toString.call(o); - } + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + n = howMuchToRead(n, state); - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; } - return origin; - } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + return ret; }; - var string_decoder = {}; + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer$5.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } - var StringDecoder_1; - // 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$7 = buffer.Buffer; + function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); + } - var isBufferEncoding = Buffer$7.isEncoding - || function(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; - } - }; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + state.emittedReadable = true; + if (state.sync) + nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); + function emitReadable_(stream) { + stream.emit('readable'); + } + + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(function() { + maybeReadMore_(stream, state); + }); } } - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$1 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. break; - default: - this.write = passThroughWrite; - return; + else + len = state.length; } + state.readingMore = false; + } - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$7(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$1.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); }; + Readable$1.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$1.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + nextTick(endFn); + else + src.once('end', endFn); - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + function onend() { + dest.end(); + } - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); } - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - charStr += buffer.toString(this.encoding, 0, end); - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); } + dest.once('finish', onfinish); - // or just emit the charStr - return charStr; - }; + function unpipe() { + src.unpipe(dest); + } - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$1.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + // tell the dest that it's being piped to + dest.emit('pipe', src); - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); - // See http://en.wikipedia.org/wiki/UTF-8#Description + state.flowing = true; + nextTick(function() { + flow(src); + }); + } - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + return dest; + }; - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; + } - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; + function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; } } - this.charReceived = i; - }; - StringDecoder$1.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + while (state.pipesCount && null !== (chunk = src.read())) { - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); + if (state.pipesCount === 1) + write(state.pipes); + else + forEach$1(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; } - return res; - }; + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; } - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; + function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } } - Readable.ReadableState = ReadableState; - var debug$8 = debuglog('stream'); - inherits$9(Readable, EventEmitter$1); + Readable$1.prototype.unpipe = function(dest) { + var state = this._readableState; - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; - } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState(options, stream) { + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; - options = options || {}; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + if (!dest) + dest = state.pipes; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + // slow case. multiple pipe destinations. - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + dest.emit('unpipe', this); - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + return this; + }; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$1.prototype.on = function(ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this); + } + } } - } - function Readable(options) { - if (!(this instanceof Readable)) return new Readable(options); + return res; + }; + Readable$1.prototype.addListener = Readable$1.prototype.on; + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$1.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); + }; - this._readableState = new ReadableState(options, this); + Readable$1.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); + }; - // legacy - this.readable = true; + function emitDataEvents(stream, startPaused) { + var state = stream._readableState; - if (options && typeof options.read === 'function') this._read = options.read; + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } - EventEmitter$1.call(this); + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream$1.prototype.pipe; + stream.on = stream.addListener = Stream$1.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable.prototype.push = function (chunk, encoding) { + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$1.prototype.wrap = function(stream) { var state = this._readableState; + var paused = false; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$m.from(chunk, encoding); - encoding = ''; + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); } } - return readableAddChunk(this, state, chunk, encoding, false); - }; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$1(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; + return self; }; - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); + + + // exposed for testing purposes only. + Readable$1._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer$5.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer$5(n); - if (!addToFront) state.reading = false; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); - if (state.needReadable) emitReadable(stream); - } - } + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); - maybeReadMore(stream, state); + c += cpy; + } } - } else if (!addToFront) { - state.reading = false; } - return needMoreData(state); + return ret; } - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } + function endReadable(stream) { + var state = stream._readableState; - // backwards compatibility. - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; - }; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); - // Don't raise the hwm > 8MB - var MAX_HWM = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + if (!state.endEmitted && state.calledRead) { + state.ended = true; + nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); } - return n; } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; + function forEach$1 (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - return state.length; } - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function (n) { - debug$8('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$8('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } + return -1; + } - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } + // 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. - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$8('need readable', doRead); + var _stream_duplex = Duplex$1; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$8('length less than watermark', doRead); - } + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; + /**/ - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$8('reading or ended', doRead); - } else if (doRead) { - debug$8('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + /**/ + var util$3 = util$5; + util$3.inherits = inherits_browser.exports; + /**/ - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + var Readable = _stream_readable; + var Writable$1 = _stream_writable; - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + util$3.inherits(Duplex$1, Readable); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + forEach(objectKeys(Writable$1.prototype), function(method) { + if (!Duplex$1.prototype[method]) + Duplex$1.prototype[method] = Writable$1.prototype[method]; + }); - if (ret !== null) this.emit('data', ret); + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) + return new Duplex$1(options); - return ret; - }; + Readable.call(this, options); + Writable$1.call(this, options); - function chunkInvalid(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } + if (options && options.readable === false) + this.readable = false; - function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + if (options && options.writable === false) + this.writable = false; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$8('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); - } + this.once('end', onend); } - function emitReadable_(stream) { - debug$8('emit readable'); - stream.emit('readable'); - flow(stream); - } + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_, stream, state); - } + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(this.end.bind(this)); } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$8('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - state.readingMore = false; } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; + // 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. - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug$8('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var _stream_writable = Writable; - var doEnd = (!pipeOpts || pipeOpts.end !== false); + /**/ + var Buffer$4 = buffer.Buffer; + /**/ - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + Writable.WritableState = WritableState; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$8('onunpipe'); - if (readable === src) { - cleanup(); - } - } - function onend() { - debug$8('onend'); - dest.end(); - } + /**/ + var util$2 = util$5; + util$2.inherits = inherits_browser.exports; + /**/ - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + var Stream = require$$1; - var cleanedUp = false; - function cleanup() { - debug$8('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + util$2.inherits(Writable, Stream); - cleanedUp = true; + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + function WritableState(options, stream) { + options = options || {}; - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$8('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug$8('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$8('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$8('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - function unpipe() { - debug$8('unpipe'); - src.unpipe(dest); - } + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // tell the dest that it's being piped to - dest.emit('pipe', src); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$8('pipe resume'); - src.resume(); - } + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - return dest; - }; + // a flag to see when we're in the middle of a write. + this.writing = false; - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug$8('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - if (!dest) dest = state.pipes; + // the amount that is being written when _write is called. + this.writelen = 0; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } + this.buffer = []; - // slow case. multiple pipe destinations. + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + } - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + function Writable(options) { + var Duplex = _stream_duplex; - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) return this; + this._writableState = new WritableState(options, this); - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + // legacy. + this.writable = true; - dest.emit('unpipe', this); + Stream.call(this); + } - return this; + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; - }; - Readable.prototype.addListener = Readable.prototype.on; - function nReadingNextTick(self) { - debug$8('readable nexttick read 0'); - self.read(0); + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(function() { + cb(er); + }); } - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$8('resume'); - state.flowing = true; - resume(this, state); - } - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer$4.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + valid = false; } + return valid; } - function resume_(stream, state) { - if (!state.reading) { - debug$8('resume read 0'); - stream.read(0); + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } + if (Buffer$4.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; - Readable.prototype.pause = function () { - debug$8('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$8('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; }; - function flow(stream) { - var state = stream._readableState; - debug$8('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer$4(chunk, encoding); + } + return chunk; } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer$4.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - var self = this; - stream.on('end', function () { - debug$8('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + state.length += len; - self.push(null); - }); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; - stream.on('data', function (chunk) { - debug$8('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + return ret; + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + function onwriteError(stream, state, sync, er, cb) { + if (sync) + nextTick(function() { + cb(er); + }); + else + cb(er); - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$8('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - return self; - }; + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - // exposed for testing purposes only. - Readable._fromList = fromList; + onwriteStateUpdate(state); - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); - return ret; + if (sync) { + nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } } - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } - list.length -= c; - return ret; } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$m.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; break; } - ++c; } - list.length -= c; - return ret; + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; } - function endReadable(stream) { - var state = stream._readableState; + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - } - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; + + + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); } + return need; } - function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + nextTick(cb); + else + stream.once('finish', cb); } - return -1; + state.ended = true; } - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$9(Writable, events.exports.EventEmitter); + // 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. - function nop() {} - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; + var _stream_transform = Transform$3; - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var Duplex = _stream_duplex; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + /**/ + var util$1 = util$5; + util$1.inherits = inherits_browser.exports; + /**/ - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + util$1.inherits(Transform$3, Duplex); - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + var cb = ts.writecb; - // a flag to see when we're in the middle of a write. - this.writing = false; + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); - // when true all writes will be buffered until .uncork() call - this.corked = 0; + ts.writechunk = null; + ts.writecb = null; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + if (data !== null && data !== undefined) + stream.push(data); - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + if (cb) + cb(er); - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - // the amount that is being written when _write is called. - this.writelen = 0; + function Transform$3(options) { + if (!(this instanceof Transform$3)) + return new Transform$3(options); - this.bufferedRequest = null; - this.lastBufferedRequest = null; + Duplex.call(this, options); - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + this._transformState = new TransformState(options, this); - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + // when the writable side finishes, then flush out anything remaining. + var stream = this; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - // count buffered requests - this.bufferedRequestCount = 0; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + Transform$3.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$3.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); + }; + + Transform$3.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); } - return out; }; - function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$3.prototype._read = function(n) { + var ts = this._transformState; - this._writableState = new WritableState(options, this); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; - // legacy. - this.writable = true; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + function done(stream, er) { + if (er) + return stream.emit('error', er); - if (typeof options.writev === 'function') this._writev = options.writev; - } + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + stream._readableState; + var ts = stream._transformState; - events.exports.EventEmitter.call(this); - } + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + if (ts.transforming) + throw new Error('calling transform done when still transforming'); - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); + return stream.push(null); } - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; - } + // 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. - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + var _stream_passthrough = PassThrough; - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + var Transform$2 = _stream_transform; - if (typeof cb !== 'function') cb = nop; + /**/ + var util = util$5; + util.inherits = inherits_browser.exports; + /**/ - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } + util.inherits(PassThrough, Transform$2); - return ret; - }; + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); - Writable.prototype.cork = function () { - var state = this._writableState; + Transform$2.call(this, options); + } - state.corked++; + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; - Writable.prototype.uncork = function () { - var state = this._writableState; + (function (module, exports) { + var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify + exports = module.exports = _stream_readable; + exports.Stream = Stream; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + }(readable, readable.exports)); - if (state.corked) { - state.corked--; + var Buffer$3 = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$4 = inherits_browser.exports; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$3.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } - }; + } - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; + function HashBase$2 (blockSize) { + Transform$1.call(this); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); - } - return chunk; - } - - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + this._block = Buffer$3.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - state.length += len; + this._finalized = false; + } - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + inherits$4(HashBase$2, Transform$1); - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - return ret; - } + callback(error); + }; - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + callback(error); + }; - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$3.isBuffer(data)) data = Buffer$3.from(data, encoding); - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; + } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } - onwriteStateUpdate(state); + return this + }; - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - if (sync) { - /**/ - nextTick(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } + return digest + }; - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + var hashBase = HashBase$2; - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + var Buffer$2 = buffer.Buffer; + var inherits$3 = inherits_browser.exports; + var HashBase$1 = hashBase; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + var ARRAY16$1 = new Array(16); - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + var zl = [ + 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 + ]; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + var zr = [ + 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 + ]; - if (entry === null) state.lastBufferedRequest = null; - } + var sl = [ + 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 + ]; - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } + var sr = [ + 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 + ]; - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - Writable.prototype._writev = null; + function RIPEMD160$1 () { + HashBase$1.call(this, 64); - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + inherits$3(RIPEMD160$1, HashBase$1); - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + RIPEMD160$1.prototype._update = function () { + var words = ARRAY16$1; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); } - } - return need; - } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + al = el; + el = dl; + dl = rotl$1(cl, 10); + cl = bl; + bl = tl; + + ar = er; + er = dr; + dr = rotl$1(cr, 10); + cr = br; + br = tr; } - state.ended = true; - stream.writable = false; - } - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - this.next = null; - this.entry = null; + RIPEMD160$1.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - inherits$9(Duplex, Readable); + // produce result + var buffer = Buffer$2.alloc ? Buffer$2.alloc(20) : new Buffer$2(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; - var keys = Object.keys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend); + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } - function onEndNT(self) { - self.end(); + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } - // a transform stream is a readable/writable stream where you do - inherits$9(Transform$1, Duplex); - - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) stream.push(data); - - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - function Transform$1(options) { - if (!(this instanceof Transform$1)) return new Transform$1(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } + var ripemd160 = RIPEMD160$1; - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); + function hashPublicKey(buffer) { + return new ripemd160().update(sha$1("sha256").update(buffer).digest()).digest(); } - Transform$1.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$1.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; - - Transform$1.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$1.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - function done(stream, er) { - if (er) return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); } - - inherits$9(PassThrough, Transform$1); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform$1.call(this, options); + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$7(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$7(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$e.concat([ + transaction.version, + transaction.timestamp || Buffer$e.alloc(0), + transaction.nVersionGroupId || Buffer$e.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$4(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$e.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$e.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$e.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$e.from([0x00]); + } + } + data = Buffer$e.concat([ + prefix, + inputValue, + isDecred ? Buffer$e.from([0x00]) : Buffer$e.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$e.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); } - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - inherits$9(Stream, EventEmitter$1); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform$1; - Stream.PassThrough = PassThrough; - - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; - - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - - function Stream() { - EventEmitter$1.call(this); + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$e.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$e.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } - Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$e.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$e.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$e.from([0x00, 0x00, 0x00, 0x00]), + Buffer$e.from([sigHashType]), + ]) + : Buffer$e.concat([ + pathsBuffer, + Buffer$e.from([0x00]), + lockTimeBuffer, + Buffer$e.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$e.concat([buffer, expiryHeight]); } - } - - source.on('data', ondata); + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } - function ondrain() { - if (source.readable && source.resume) { - source.resume(); + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$6(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$5(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser$2(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + var re$5 = {exports: {}}; - if (typeof dest.destroy === 'function') dest.destroy(); - } + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; - source.on('error', onerror); - dest.on('error', onerror); + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; - source.removeListener('end', onend); - source.removeListener('close', onclose); + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + var debug_1 = debug$3; - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; - dest.removeListener('close', cleanup); - } + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; - source.on('end', cleanup); - source.on('close', cleanup); + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; - dest.on('close', cleanup); + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. - dest.emit('pipe', source); + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream, - Readable: Readable, - Writable: Writable, - Duplex: Duplex, - Transform: Transform$1, - PassThrough: PassThrough, - Stream: Stream - }); + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - var Buffer$6 = safeBuffer.exports.Buffer; - var Transform = require$$1.Transform; - var StringDecoder = string_decoder.StringDecoder; - var inherits$7 = inherits_browser.exports; + // ## Main Version + // Three dot-separated numeric identifiers. - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; - } - inherits$7(CipherBase, Transform); + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer$6.from(data, inputEnc); - } + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - var outData = this._update(data); - if (this.hashMode) return this + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); - return outData - }; + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); - } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer$6.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; - - var cipherBase = CipherBase; + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. - var inherits$6 = inherits_browser.exports; - var MD5$1 = md5_js; - var RIPEMD160$2 = ripemd160$2; - var sha$2 = sha_js.exports; - var Base$5 = cipherBase; + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - function Hash (hash) { - Base$5.call(this, 'digest'); + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. - this._hash = hash; - } + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - inherits$6(Hash, Base$5); + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. - Hash.prototype._update = function (data) { - this._hash.update(data); - }; + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. - Hash.prototype._final = function () { - return this._hash.digest() - }; + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); - var browser$3 = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5$1() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() + createToken('FULL', `^${src[t.FULLPLAIN]}$`); - return new Hash(sha$2(alg)) - }; + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); - var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser$3 - }, [browser$3])); + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - var inherits$5 = inherits_browser.exports; - var Buffer$5 = safeBuffer.exports.Buffer; + createToken('GTLT', '((?:<|>)?=?)'); - var Base$4 = cipherBase; + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - var ZEROS$1 = Buffer$5.alloc(128); - var blocksize = 64; + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); - function Hmac$2 (alg, key) { - Base$4.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$5.from(key); - } + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); - this._alg = alg; - this._key = key; + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - if (key.length > blocksize) { - key = alg(key); - } else if (key.length < blocksize) { - key = Buffer$5.concat([key, ZEROS$1], blocksize); - } + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); - var ipad = this._ipad = Buffer$5.allocUnsafe(blocksize); - var opad = this._opad = Buffer$5.allocUnsafe(blocksize); + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; - } + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; - this._hash = [ipad]; - } + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - inherits$5(Hmac$2, Base$4); + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); - Hmac$2.prototype._update = function (data) { - this._hash.push(data); - }; + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; - Hmac$2.prototype._final = function () { - var h = this._alg(Buffer$5.concat(this._hash)); - return this._alg(Buffer$5.concat([this._opad, h])) - }; - var legacy = Hmac$2; + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - var MD5 = md5_js; + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - var md5$1 = function (buffer) { - return new MD5().update(buffer).digest() - }; + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; - var inherits$4 = inherits_browser.exports; - var Legacy = legacy; - var Base$3 = cipherBase; - var Buffer$4 = safeBuffer.exports.Buffer; - var md5 = md5$1; - var RIPEMD160$1 = ripemd160$2; + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); - var sha$1 = sha_js.exports; + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); - var ZEROS = Buffer$4.alloc(128); + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); - function Hmac$1 (alg, key) { - Base$3.call(this, 'digest'); - if (typeof key === 'string') { - key = Buffer$4.from(key); - } + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); - this._alg = alg; - this._key = key; - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - key = hash.update(key).digest(); - } else if (key.length < blocksize) { - key = Buffer$4.concat([key, ZEROS], blocksize); + if (anum && bnum) { + a = +a; + b = +b; } - var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); - var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36; - opad[i] = key[i] ^ 0x5C; - } - this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); - this._hash.update(ipad); - } + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; - inherits$4(Hmac$1, Base$3); + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - Hmac$1.prototype._update = function (data) { - this._hash.update(data); + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers }; - Hmac$1.prototype._final = function () { - var h = this._hash.digest(); - var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); - return hash.update(this._opad).update(h).digest() - }; + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; - var browser$2 = function createHmac (alg, key) { - alg = alg.toLowerCase(); - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac$1('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac$1(alg, key) - }; + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); - Object.defineProperty(crypto$5, "__esModule", { value: true }); - const createHash$2 = browser$3; - const createHmac$1 = browser$2; - function hash160$2(buffer) { - const sha256Hash = createHash$2('sha256') - .update(buffer) - .digest(); - try { - return createHash$2('rmd160') - .update(sha256Hash) - .digest(); - } - catch (err) { - return createHash$2('ripemd160') - .update(sha256Hash) - .digest(); - } - } - crypto$5.hash160 = hash160$2; - function hmacSHA512(key, data) { - return createHmac$1('sha512', key) - .update(data) - .digest(); - } - crypto$5.hmacSHA512 = hmacSHA512; - - // base-x encoding / decoding - // Copyright (c) 2018 base-x contributors - // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) - // Distributed under the MIT software license, see the accompanying - // file LICENSE or http://www.opensource.org/licenses/mit-license.php. - // @ts-ignore - var _Buffer$1 = safeBuffer.exports.Buffer; - function base$2 (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256); - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255; - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i; - } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up - function encode (source) { - if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } - if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } - if (source.length === 0) { return '' } - // Skip & count leading zeroes. - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++; - zeroes++; - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; - var b58 = new Uint8Array(size); - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin]; - // Apply "b58 = b58 * 256 + ch". - var i = 0; - for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { - carry += (256 * b58[it1]) >>> 0; - b58[it1] = (carry % BASE) >>> 0; - carry = (carry / BASE) >>> 0; - } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - pbegin++; - } - // Skip leading zeroes in base58 result. - var it2 = size - length; - while (it2 !== size && b58[it2] === 0) { - it2++; - } - // Translate the result into a string. - var str = LEADER.repeat(zeroes); - for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } - return str - } - function decodeUnsafe (source) { - if (typeof source !== 'string') { throw new TypeError('Expected String') } - if (source.length === 0) { return _Buffer$1.alloc(0) } - var psz = 0; - // Skip and count leading '1's. - var zeroes = 0; - var length = 0; - while (source[psz] === LEADER) { - zeroes++; - psz++; - } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size); - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)]; - // Invalid character - if (carry === 255) { return } - var i = 0; - for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { - carry += (BASE * b256[it3]) >>> 0; - b256[it3] = (carry % 256) >>> 0; - carry = (carry / 256) >>> 0; + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; } - if (carry !== 0) { throw new Error('Non-zero carry') } - length = i; - psz++; - } - // Skip leading zeroes in b256. - var it4 = size - length; - while (it4 !== size && b256[it4] === 0) { - it4++; - } - var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); - vch.fill(0x00, 0, zeroes); - var j = zeroes; - while (it4 !== size) { - vch[j++] = b256[it4++]; + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string); - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } - } - var src = base$2; - - var basex = src; - var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - - var bs58 = basex(ALPHABET$1); - var base58 = bs58; - var Buffer$3 = safeBuffer.exports.Buffer; + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } - var base$1 = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload); + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; - return base58.encode(Buffer$3.concat([ - payload, - checksum - ], payload.length + 4)) - } + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4); - var checksum = buffer.slice(-4); - var newChecksum = checksumFn(payload); + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return + this.raw = version; - return payload - } + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string); - if (!buffer) return + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } - return decodeRaw(buffer) - } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } - function decode (string) { - var buffer = base58.decode(string); - var payload = decodeRaw(buffer); - if (!payload) throw new Error('Invalid checksum') - return payload - } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } - }; - - var createHash$1 = browser$3; - var bs58checkBase = base$1; - - // SHA256(SHA256(buffer)) - function sha256x2 (buffer) { - var tmp = createHash$1('sha256').update(buffer).digest(); - return createHash$1('sha256').update(tmp).digest() - } - - var bs58check$5 = bs58checkBase(sha256x2); - - var bn = {exports: {}}; - - (function (module) { - (function (module, exports) { - - // 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; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); } - 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.build = m[5] ? m[5].split('.') : []; + this.format(); + } - this._init(number || 0, base || 10, endian || 'be'); + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; + return this.version } - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require('buffer').Buffer; - } - } catch (e) { + toString () { + return this.version } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); } - 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; - }; + if (other.version === this.version) { + return 0 + } - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + return this.compareMain(other) || this.comparePre(other) + } - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } - if (base === 'hex') { - base = 16; + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - assert(base === (base | 0) && base >= 2 && base <= 36); - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } + return compareIdentifiers(a, b) } - } - }; + } while (++i) + } - 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; + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); } - 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; - } + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } - 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; - } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break - 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++; + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; } - } - } 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++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - } - } - return this.strip(); - }; + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break - 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; + default: + throw new Error(`invalid increment argument: ${release}`) } + this.format(); + this.raw = this.version; + return this } + } - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } + var semver$1 = SemVer$e; - 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; - } + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; - // 24-bits chunks - var off = 0; - var j = 0; + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); - 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; + if (version instanceof SemVer$d) { + return version + } - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + if (typeof version !== 'string') { + return null + } - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + if (version.length > MAX_LENGTH) { + return null + } - // '0' - '9' - } else { - r += c; - } - } - return r; + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + var parse_1 = parse$5; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + const SemVer$c = semver$1; - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } - for (i = 0; i < mod; i++) { - pow *= base; - } + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - this.strip(); - }; + var compare_1 = compare$a; - 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; - }; + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; + const parse$2 = parse_1; + const eq$1 = eq_1; - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } } - return this; - }; + return defaultResult // may be undefined + } + }; + var diff_1 = diff; - // 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(); - }; + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; - /* + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; - var zeros = []; - var groupSizes = []; - var groupBases = []; + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; - 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; - } + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; - */ + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; - 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; - } + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; - assert(false, 'Base should be between 2 and 36'); - }; + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; - 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; - }; + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; - 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; - } + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b - res[i] = b; - } + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b - for (; i < reqLength; i++) { - res[i] = 0; - } - } + case '': + case '=': + case '==': + return eq(a, b, loose) - return res; - }; + case '!=': + return neq(a, b, loose) - 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; - }; - } + case '>': + return gt$2(a, b, loose) - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + case '>=': + return gte$1(a, b, loose) - 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; - }; + case '<': + return lt$1(a, b, loose) - // 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; - }; + case '<=': + return lte$1(a, b, loose) - function toBitArray (num) { - var w = new Array(num.bitLength()); + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } - return w; + if (typeof version === 'number') { + version = String(version); } - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + if (typeof version !== 'string') { + return null + } - 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; - }; + options = options || {}; - 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); + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; } - return this.clone(); - }; + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + if (match === null) + return null - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + var yallist = Yallist$1; - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } + Yallist$1.Node = Node; + Yallist$1.create = Yallist$1; - return this; - }; + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } + self.tail = null; + self.head = null; + self.length = 0; - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); } + } - return this.strip(); - }; + return self + } - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } - // 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); - }; + var next = node.next; + var prev = node.prev; - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; + if (next) { + next.prev = prev; + } - // 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; - } + if (prev) { + prev.next = next; + } - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } - this.length = b.length; + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; - return this.strip(); - }; + return next + }; - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } - // 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); - }; + if (node.list) { + node.list.removeNode(node); + } - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } - // 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; - } + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + if (node.list) { + node.list.removeNode(node); + } - this.length = a.length; + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } - return this.strip(); - }; + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; - // 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); - }; + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; - if (bitsLeft > 0) { - bytesNeeded--; - } + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; - // And remove leading zeroes - return this.strip(); - }; + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; - var off = (bit / 26) | 0; - var wbit = bit % 26; + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } - this._expand(off + 1); + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } + return acc + }; - 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; - }; + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } - // 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; - } + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } - if (this.length > num.length) return this.clone().iadd(num); + return acc + }; - return num.clone().iadd(this); - }; + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; - // 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; - } + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; - 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; - } + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } - this.length = Math.max(this.length, i); + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } - if (a !== this) { - this.negative = 1; - } + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } - return this.strip(); - }; + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; - 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; - }; + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; - // 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--; - } + function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self); - return out.strip(); + if (inserted.next === null) { + self.tail = inserted; } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); + if (inserted.prev === null) { + self.head = inserted; } - 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); - } + self.length++; - return res; - }; + return inserted + } - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion + function push (self, item) { + self.tail = new Node(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } - function FFTM (x, y) { - this.x = x; - this.y = y; + function unshift (self, item) { + self.head = new Node(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; } + self.length++; + } - 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); - } + function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } - return t; - }; + this.list = list; + this.value = value; - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } - return rb; - }; + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} - // 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]]; - } - }; + // A linked list to keep track of recently-used-ness + const Yallist = yallist; - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; + const naiveLength = () => 1; - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; + if (!options) + options = {}; - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } - var rx = rtwdf_ * ro - itwdf_ * io; + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } - 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; + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } - t = iws[i]; + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); } - }; - - 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; + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } - ws[i] = w & 0x3ffffff; + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; } + } - 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; + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; } + } - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); } - return ph; - }; + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } - var rbt = this.makeRBT(N); + dumpLru () { + return this[LRU_LIST] + } - var _ = this.stub(N); + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); - var rmws = out.words; - rmws.length = N; + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); + const node = this[CACHE].get(key); + const item = node.value; - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } - 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; + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true } - 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); + const hit = new Entry(key, value, len, now, maxAge); - // 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; - } + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); - if (carry !== 0) { - this.words[i] = carry; - this.length++; + return false } - 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[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); + get (key) { + return get(this, key, true) + } - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } + peek (key) { + return get(this, key, false) + } - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null - res = res.mul(q); - } - } + del(this, node); + return node.value + } - return res; - }; + del (key) { + del(this, this[CACHE].get(key)); + } - // 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); - } + load (arr) { + // reset the cache + this.reset(); - if (carry) { - this.words[i] = carry; - this.length++; + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } } } + } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)); + } + } - for (i = 0; i < s; i++) { - this.words[i] = 0; + const get = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); } - - this.length += s; } + return hit.value + } + }; - return this.strip(); - }; + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; - // 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; + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; } + } + }; - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); - h -= s; - h = Math.max(0, h); + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } - if (s === 0) ; 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; + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; - assert(this.negative === 0, 'imaskn works only with positive numbers'); + var lruCache = LRUCache; - if (this.length <= s) { - return this; - } + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); - if (r !== 0) { - s++; + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } } - this.length = Math.min(s, this.length); - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this } - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; - // 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; - } + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - // 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]++; + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } } } - 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.format(); + } - this.words[0] -= num; + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } - 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; - } - } + toString () { + return this.range + } - return this.strip(); - }; + parseRange (range) { + range = range.trim(); - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - BN.prototype.iabs = function iabs () { - this.negative = 0; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - return this; - }; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; + // normalize spaces + range = range.split(/\s+/).join(' '); - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; + // At this point, the range is completely trimmed and + // ready to be split into comparators. - this._expand(len); + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); - 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 any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); - if (carry === 0) return this.strip(); + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } - // 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; + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') } - 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; + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } - // 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; + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } - // 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; + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false } } - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } } + return false + } + } + var range = Range$a; - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; - 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(); + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); - return { - div: q || null, - mod: a - }; - }; + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); - // 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) - }; - } + testComparator = remainingComparators.pop(); + } - 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 result + }; - return this.strip(); - }; + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp + }; - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); - var x = this; - var y = p.clone(); + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; - if (x.negative !== 0) { - x = x.umod(p); + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } else { - x = x.clone(); + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; } - // 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; - } + debug$1('tilde return', ret); + return ret + }) + }; - var yp = y.clone(); - var xp = x.clone(); + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); - 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); - } + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; - A.iushrn(1); - B.iushrn(1); - } + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; } - - 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); + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } } else { - y.isub(x); - C.isub(A); - D.isub(B); + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; } } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; + debug$1('caret return', ret); + return ret + }) + }; - // 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()); + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; - var a = this; - var b = p.clone(); + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + if (gtlt === '=' && anyX) { + gtlt = ''; } - 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); - } + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; - x1.iushrn(1); - } + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; } - - 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); - } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; } + p = 0; - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } } - } - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } + if (gtlt === '<') + pr = '-0'; - if (res.cmpn(0) < 0) { - res.iadd(p); + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; } - return res; - }; + debug$1('xRange return', ret); - 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); - }; + return ret + }) + }; - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } - // 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; - } + return (`${from} ${to}`).trim() + }; - // 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++; + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false } - 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; + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue } - 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; + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } } - 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(); + // Version has a -pre, but it's not one of the ones we like. + return false } - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; + return true + }; - 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; + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); - 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(); + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp } else { - // r is BN v5 instance - r._strip(); + comp = comp.value; } } - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + debug('comp', this); } - inherits(K256, MPrime); - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - output.length = outLen; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; } - // 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; + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; } 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--; - } + this.semver = new SemVer$4(m[2], this.options.loose); } - 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'); + toString () { + return this.value } - 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; + test (version) { + debug('Comparator.test', version, this.options.loose); - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; + if (this.semver === ANY$2 || version === ANY$2) { + return true } - 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); + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } } - 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; - } + return cmp(version, this.operator, this.semver, this.options) } - 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(); + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') } - 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); + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; } - 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); + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) } - 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; - }; + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } + } - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + var comparator = Comparator$2; - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; + const Range$7 = range; - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + var toComparators_1 = toComparators; - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } + const SemVer$3 = semver$1; + const Range$6 = range; - // 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(); + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); } - 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 max + }; + var maxSatisfying_1 = maxSatisfying; - 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); + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); + }); + return min + }; + var minSatisfying_1 = minSatisfying; - 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); - } + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } + const minVersion = (range, loose) => { + range = new Range$4(range, loose); - 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); - } + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) } - 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; - }; + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } - // - // Montgomery method engine - // + if (minver && range.test(minver)) { + return minver + } - BN.mont = function mont (num) { - return new Mont(num); - }; + return null + }; + var minVersion_1 = minVersion; - function Mont (m) { - Red.call(this, m); + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); - 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); + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') } - inherits(Mont, Red); - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; - 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); - }; + let high = null; + let low = null; - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); - 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); + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - 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); - }; - })(module, commonjsGlobal); - }(bn)); - - var elliptic = {}; - - var name = "elliptic"; - var version = "6.5.4"; - var description = "EC cryptography"; - var main = "lib/elliptic.js"; - var files = [ - "lib" - ]; - var scripts = { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/" - }; - var repository = { - type: "git", - url: "git@github.com:indutny/elliptic" - }; - var keywords = [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ]; - var author = "Fedor Indutny "; - var license = "MIT"; - var bugs = { - url: "https://github.com/indutny/elliptic/issues" - }; - var homepage = "https://github.com/indutny/elliptic"; - var devDependencies = { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1" - }; - var dependencies = { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }; - var require$$0$1 = { - name: name, - version: version, - description: description, - main: main, - files: files, - scripts: scripts, - repository: repository, - keywords: keywords, - author: author, - license: license, - bugs: bugs, - homepage: homepage, - devDependencies: devDependencies, - dependencies: dependencies - }; - - var utils$n = {}; - - var minimalisticAssert = assert$f; - - function assert$f(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); - } - - assert$f.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); - }; - - var utils$m = {}; - - (function (exports) { - - 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); + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } } - return res; - } - utils.toArray = toArray; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils.zero2 = zero2; + return true + }; - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils.toHex = toHex; + var outside_1 = outside$2; - utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; - }; - }(utils$m)); + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; - (function (exports) { + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; - var utils = exports; - var BN = bn.exports; - var minAssert = minimalisticAssert; - var minUtils = utils$m; - - 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); + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; - var u2; - if ((m24 & 1) === 0) { - u2 = 0; + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; } else { - m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; } - 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); } + if (min) + set.push([min, null]); - 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; - }(utils$n)); - - var brorand = {exports: {}}; - - var r$1; - - brorand.exports = function rand(len) { - if (!r$1) - r$1 = new Rand(null); - - return r$1.generate(len); + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range }; - function Rand(rand) { - this.rand = rand; - } - brorand.exports.Rand = Rand; + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; - Rand.prototype.generate = function generate(len) { - return this._rand(len); - }; + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true - // Emulate crypto API using randy - Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true }; - 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; - }; + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; } - } else { - // Node.js or Web worker with no crypto support - try { - var crypto$4 = require('crypto'); - if (typeof crypto$4.randomBytes !== 'function') - throw new Error('Not supported'); - Rand.prototype._rand = function _rand(n) { - return crypto$4.randomBytes(n); - }; - } catch (e) { + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; } - } - - var curve = {}; - var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; - - function BaseCurve(type, conf) { - this.type = type; - this.p = new BN$8(conf.p, 16); + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + if (eqSet.size > 1) + return null - // Useful for many curves - this.zero = new BN$8(0).toRed(this.red); - this.one = new BN$8(1).toRed(this.red); - this.two = new BN$8(2).toRed(this.red); + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } - // Curve configuration, optional - this.n = conf.n && new BN$8(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); + if (lt && !satisfies(eq, String(lt), options)) + return null - this._bitLength = this.n ? this.n.bitLength() : 0; + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } - // 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); + return true } - } - var base = 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$e(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$e(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()); - } + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; } - 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; + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } } - if (!zero) - break; - k++; - i--; + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (j = 0; j < len; j++) { - var z = tmp[j]; - 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); + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false } - // 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert$e(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); - }; + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false - BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); + return true }; - BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a }; - 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; + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a }; - BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; + var subset_1 = subset; - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, }; - BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } - 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, - }; + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); }; - - 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, - }; + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - BasePoint.prototype._getBeta = function _getBeta() { - return null; + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; - - BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; + var __values$3 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - - var utils$k = utils$n; - var BN$7 = bn.exports; - var inherits$3 = inherits_browser.exports; - var Base$2 = base; - - var assert$d = utils$k.assert; - - function ShortCurve(conf) { - Base$2.call(this, 'short', conf); - - this.a = new BN$7(conf.a, 16).toRed(this.red); - this.b = new BN$7(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$3(ShortCurve, Base$2); - var short = 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$7(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$7(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$d(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$7(vec.a, 16), - b: new BN$7(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$7.mont(num); - var tinv = new BN$7(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN$7(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$7(1); - var y1 = new BN$7(0); - var x2 = new BN$7(0); - var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { - Base$2.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); - - ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point$2(this, x, y, isRed); - }; - - ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point$2.fromJSON(this, obj, red); - }; - - Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$2.prototype.isInfinity = function isInfinity() { - return this.inf; - }; - - Point$2.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$2.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$2.prototype.getX = function getX() { - return this.x.fromRed(); - }; - - Point$2.prototype.getY = function getY() { - return this.y.fromRed(); - }; - - Point$2.prototype.mul = function mul(k) { - k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); - } else { - this.x = new BN$7(x, 16); - this.y = new BN$7(y, 16); - this.z = new BN$7(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$3(JPoint, Base$2.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$7(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; - }; - - var BN$6 = bn.exports; - var inherits$2 = inherits_browser.exports; - var Base$1 = base; - - var utils$j = utils$n; - - function MontCurve(conf) { - Base$1.call(this, 'mont', conf); - - this.a = new BN$6(conf.a, 16).toRed(this.red); - this.b = new BN$6(conf.b, 16).toRed(this.red); - this.i4 = new BN$6(4).toRed(this.red).redInvm(); - this.two = new BN$6(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); - } - inherits$2(MontCurve, Base$1); - var mont = 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$1(curve, x, z) { - Base$1.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$6(x, 16); - this.z = new BN$6(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$2(Point$1, Base$1.BasePoint); - - MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); - }; - - MontCurve.prototype.point = function point(x, z) { - return new Point$1(this, x, z); - }; - - MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point$1.fromJSON(this, obj); - }; - - Point$1.prototype.precompute = function precompute() { - // No-op - }; - - Point$1.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); - }; - - Point$1.fromJSON = function fromJSON(curve, obj) { - return new Point$1(curve, obj[0], obj[1] || curve.one); - }; - - Point$1.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; - }; - - Point$1.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; - }; - - Point$1.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$1.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); - }; - - Point$1.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; - }; - - Point$1.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } }; + function createTransaction(transport, arg) { + return __awaiter$4(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$4(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$e.alloc(0); + nullPrevout = Buffer$e.alloc(0); + defaultVersion = Buffer$e.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$e.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$e.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$e.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$e.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$e.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$e.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$e.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$e.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$e.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$e.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$e.concat([ + Buffer$e.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$e.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$e.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$e.concat([ + Buffer$e.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$e.alloc(1); + keySize = Buffer$e.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$e.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$e.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$e.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$e.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$e.concat([ + Buffer$e.from("02", "hex"), + Buffer$e.from([signatures[i].length]), + signatures[i], + Buffer$e.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$e.concat([witness, tmpScriptData]); + } + result = Buffer$e.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$e.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$e.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$e.alloc(0), + targetTransaction.extraData || Buffer$e.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$e.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$e.concat([ + decredWitness_1, + Buffer$e.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$e.from([0x00, 0x00, 0x00, 0x00]), + Buffer$e.from([0xff, 0xff, 0xff, 0xff]), + Buffer$e.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$e.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } - Point$1.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); - }; - - var utils$i = utils$n; - var BN$5 = bn.exports; - var inherits$1 = inherits_browser.exports; - var Base = base; - - var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN$5(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN$5(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; - } - inherits$1(EdwardsCurve, Base); - var edwards = 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$5(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$5(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$5(x, 16); - this.y = new BN$5(y, 16); - this.z = z ? new BN$5(z, 16) : this.curve.one; - this.t = t && new BN$5(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$1(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; - - (function (exports) { - - var curve = exports; - - curve.base = base; - curve.short = short; - curve.mont = mont; - curve.edwards = edwards; - }(curve)); - - var curves$2 = {}; - - var hash$2 = {}; - - var utils$h = {}; - - var assert$b = minimalisticAssert; - var inherits = inherits_browser.exports; - - utils$h.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; - } - utils$h.toArray = toArray; - - function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; - } - utils$h.toHex = toHex; - - function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; - } - utils$h.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; - } - utils$h.toHex32 = toHex32; - - function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; - } - utils$h.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; - } - utils$h.zero8 = zero8; - - function join32(msg, start, end, endian) { - var len = end - start; - assert$b(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; - } - utils$h.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; - } - utils$h.split32 = split32; - - function rotr32$1(w, b) { - return (w >>> b) | (w << (32 - b)); - } - utils$h.rotr32 = rotr32$1; - - function rotl32$2(w, b) { - return (w << b) | (w >>> (32 - b)); - } - utils$h.rotl32 = rotl32$2; - - function sum32$3(a, b) { - return (a + b) >>> 0; - } - utils$h.sum32 = sum32$3; - - function sum32_3$1(a, b, c) { - return (a + b + c) >>> 0; - } - utils$h.sum32_3 = sum32_3$1; - - function sum32_4$2(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - utils$h.sum32_4 = sum32_4$2; - - function sum32_5$2(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - utils$h.sum32_5 = sum32_5$2; - - function sum64$1(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; - } - utils$h.sum64 = sum64$1; - - function sum64_hi$1(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - utils$h.sum64_hi = sum64_hi$1; - - function sum64_lo$1(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - utils$h.sum64_lo = sum64_lo$1; - - function sum64_4_hi$1(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; - } - utils$h.sum64_4_hi = sum64_4_hi$1; - - function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - utils$h.sum64_4_lo = sum64_4_lo$1; - - function sum64_5_hi$1(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; - } - utils$h.sum64_5_hi = sum64_5_hi$1; - - function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; - } - utils$h.sum64_5_lo = sum64_5_lo$1; - - function rotr64_hi$1(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - utils$h.rotr64_hi = rotr64_hi$1; - - function rotr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.rotr64_lo = rotr64_lo$1; - - function shr64_hi$1(ah, al, num) { - return ah >>> num; - } - utils$h.shr64_hi = shr64_hi$1; - - function shr64_lo$1(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - utils$h.shr64_lo = shr64_lo$1; - - var common$5 = {}; - - var utils$g = utils$h; - var assert$a = minimalisticAssert; - - function BlockHash$4() { - 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; - } - common$5.BlockHash = BlockHash$4; - - BlockHash$4.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert$a(this.pending === null); - - return this._digest(enc); - }; - - BlockHash$4.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; - }; - - var sha = {}; - - var common$4 = {}; - - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; - - function ft_1$1(s, x, y, z) { - if (s === 0) - return ch32$1(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32$1(x, y, z); - } - common$4.ft_1 = ft_1$1; - - function ch32$1(x, y, z) { - return (x & y) ^ ((~x) & z); - } - common$4.ch32 = ch32$1; - - function maj32$1(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - common$4.maj32 = maj32$1; - - function p32(x, y, z) { - return x ^ y ^ z; - } - common$4.p32 = p32; - - function s0_256$1(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - common$4.s0_256 = s0_256$1; - - function s1_256$1(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - common$4.s1_256 = s1_256$1; - - function g0_256$1(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - common$4.g0_256 = g0_256$1; - - function g1_256$1(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - common$4.g1_256 = g1_256$1; - - var utils$e = utils$h; - var common$3 = common$5; - var shaCommon$1 = common$4; - - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; - var ft_1 = shaCommon$1.ft_1; - var BlockHash$3 = common$3.BlockHash; - - var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 - ]; - - function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash$3.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); - } - - utils$e.inherits(SHA1, BlockHash$3); - var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); - }; - - SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); - else - return utils$e.split32(this.h, 'big'); - }; - - var utils$d = utils$h; - var common$2 = common$5; - var shaCommon = common$4; - var assert$9 = minimalisticAssert; - - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.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$2 = common$2.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$1() { - if (!(this instanceof SHA256$1)) - return new SHA256$1(); - - BlockHash$2.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); - } - utils$d.inherits(SHA256$1, BlockHash$2); - var _256 = SHA256$1; - - SHA256$1.blockSize = 512; - SHA256$1.outSize = 256; - SHA256$1.hmacStrength = 192; - SHA256$1.padLength = 64; - - SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32$1(d, T1); - d = c; - c = b; - b = a; - a = sum32$1(T1, T2); - } - - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); - this.h[5] = sum32$1(this.h[5], f); - this.h[6] = sum32$1(this.h[6], g); - this.h[7] = sum32$1(this.h[7], h); - }; - - SHA256$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); - else - return utils$d.split32(this.h, 'big'); - }; - - var utils$c = utils$h; - var SHA256 = _256; - - function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; - } - utils$c.inherits(SHA224, SHA256); - var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); - else - return utils$c.split32(this.h.slice(0, 7), 'big'); - }; - - var utils$b = utils$h; - var common$1 = common$5; - var assert$8 = minimalisticAssert; - - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; - - var BlockHash$1 = common$1.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$1() { - if (!(this instanceof SHA512$1)) - return new SHA512$1(); - - BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); - var _512 = SHA512$1; - - SHA512$1.blockSize = 1024; - SHA512$1.outSize = 512; - SHA512$1.hmacStrength = 192; - SHA512$1.padLength = 128; - - SHA512$1.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$1.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$8(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); - 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); - 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$1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); - else - return utils$b.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; - } - - var utils$a = utils$h; - - var SHA512 = _512; - - 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$a.inherits(SHA384, SHA512); - var _384 = SHA384; - - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; - - SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); - else - return utils$a.split32(this.h.slice(0, 12), 'big'); - }; - - sha.sha1 = _1; - sha.sha224 = _224; - sha.sha256 = _256; - sha.sha384 = _384; - sha.sha512 = _512; - - var ripemd = {}; - - var utils$9 = utils$h; - var common = common$5; - - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.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$9.inherits(RIPEMD160, BlockHash); - ripemd.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$9.toHex32(this.h, 'little'); - else - return utils$9.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 - ]; - - var utils$8 = utils$h; - var assert$7 = minimalisticAssert; - - 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$8.toArray(key, enc)); - } - var hmac = Hmac; - - Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert$7(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); - }; - - (function (exports) { - var hash = exports; - - hash.utils = utils$h; - hash.common = common$5; - hash.sha = sha; - hash.ripemd = ripemd; - hash.hmac = hmac; - - // 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; - }(hash$2)); - - (function (exports) { - - var curves = exports; - - var hash = hash$2; - var curve$1 = curve; - var utils = utils$n; - - var assert = utils.assert; - - function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve$1.short(options); - else if (options.type === 'edwards') - this.curve = new curve$1.edwards(options); - else - this.curve = new curve$1.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 = require('./precomputed/secp256k1'); - } 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, - ], - }); - }(curves$2)); - - var hash$1 = hash$2; - var utils$7 = utils$m; - var assert$6 = minimalisticAssert; - - function HmacDRBG$1(options) { - if (!(this instanceof HmacDRBG$1)) - return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); - } - var hmacDrbg = HmacDRBG$1; - - HmacDRBG$1.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$1.prototype._hmac = function hmac() { - return new hash$1.hmac(this.hash, this.K); - }; - - HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); - - assert$6(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; - }; - - HmacDRBG$1.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$7.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$7.encode(res, enc); - }; - - var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; - - function KeyPair$4(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); - } - var key$1 = KeyPair$4; - - KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair$4) - return pub; - - return new KeyPair$4(ec, { - pub: pub, - pubEnc: enc, - }); - }; - - KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair$4) - return priv; - - return new KeyPair$4(ec, { - priv: priv, - privEnc: enc, - }); - }; - - KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; - }; - - KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert$5(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$4.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert$5(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); - }; - - // ECDSA - KeyPair$4.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); - }; - - KeyPair$4.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); - }; - - KeyPair$4.prototype.inspect = function inspect() { - return ''; - }; - - var BN$3 = bn.exports; - - var utils$5 = utils$n; - var assert$4 = utils$5.assert; - - function Signature$3(options, enc) { - if (options instanceof Signature$3) - return options; - - if (this._importDER(options, enc)) - return; - - assert$4(options.r && options.s, 'Signature without r or s'); - this.r = new BN$3(options.r, 16); - this.s = new BN$3(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; - } - var signature$1 = Signature$3; - - 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$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.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$3(r); - this.s = new BN$3(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$3.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$5.encode(res, enc); - }; - - var BN$2 = bn.exports; - var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; - var curves$1 = curves$2; - var rand = brorand.exports; - var assert$3 = utils$4.assert; - - var KeyPair$3 = key$1; - var Signature$2 = signature$1; - - function EC$1(options) { - if (!(this instanceof EC$1)) - return new EC$1(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), - 'Unknown curve ' + options); - - options = curves$1[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves$1.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; - } - var ec = EC$1; - - EC$1.prototype.keyPair = function keyPair(options) { - return new KeyPair$3(this, options); - }; - - EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair$3.fromPrivate(this, priv, enc); - }; - - EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair$3.fromPublic(this, pub, enc); - }; - - EC$1.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(2)); - for (;;) { - var priv = new BN$2(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } - }; - - EC$1.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$1.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$2(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$2(1)); - - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); - } - }; - - EC$1.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN$2(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert$3((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature$2(signature, enc); - - var n = this.n; - var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature$2(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'); - }; - - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.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$2(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes$2(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes$2(params.pub); - } - - KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair$2) - return pub; - return new KeyPair$2(eddsa, { pub: pub }); - }; - - KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair$2) - return secret; - return new KeyPair$2(eddsa, { secret: secret }); - }; - - KeyPair$2.prototype.secret = function secret() { - return this._secret; - }; - - cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); - }); - - cachedProperty$1(KeyPair$2, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); - }); - - cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); - }); - - cachedProperty$1(KeyPair$2, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); - }); - - cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); - }); - - KeyPair$2.prototype.sign = function sign(message) { - assert$2(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); - }; - - KeyPair$2.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); - }; - - KeyPair$2.prototype.getSecret = function getSecret(enc) { - assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); - }; - - KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); - }; - - var key = KeyPair$2; - - var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.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$1(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes$1(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; - } - - assert$1(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN$1) - 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$1, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); - }); - - cachedProperty(Signature$1, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); - }); - - cachedProperty(Signature$1, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); - }); - - cachedProperty(Signature$1, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); - }); - - Signature$1.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); - }; - - Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); - }; - - var signature = Signature$1; - - var hash = hash$2; - var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; - var KeyPair$1 = key; - var Signature = signature; - - 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; - } - - var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); - }; - - EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair$1.fromPublic(this, pub); - }; - - EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); - }; - - EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; - }; - - (function (exports) { - - var elliptic = exports; - - elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; - elliptic.rand = brorand.exports; - elliptic.curve = curve; - elliptic.curves = curves$2; - - // Protocols - elliptic.ec = ec; - elliptic.eddsa = eddsa; - }(elliptic)); - - const createHmac = browser$2; - - const ONE1 = Buffer$m.alloc(1, 1); - const ZERO1 = Buffer$m.alloc(1, 0); - - // https://tools.ietf.org/html/rfc6979#section-3.2 - function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { - // Step A, ignored as hash already provided - // Step B - // Step C - let k = Buffer$m.alloc(32, 0); - let v = Buffer$m.alloc(32, 1); - - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step E - v = createHmac('sha256', k).update(v).digest(); - - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE1) - .update(x) - .update(hash) - .update(extraEntropy || '') - .digest(); - - // Step G - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest(); - - let T = v; - - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (!isPrivate(T) || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO1) - .digest(); - - v = createHmac('sha256', k).update(v).digest(); - - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest(); - T = v; - } - - return T - } - - var rfc6979 = deterministicGenerateK$1; - - const BN = bn.exports; - const EC = elliptic.ec; - const secp256k1 = new EC('secp256k1'); - const deterministicGenerateK = rfc6979; - - const ZERO32 = Buffer$m.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$m.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$m.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); - - const n = secp256k1.curve.n; - const nDiv2 = n.shrn(1); - const G = secp256k1.curve.g; - - const THROW_BAD_PRIVATE = 'Expected Private'; - const THROW_BAD_POINT = 'Expected Point'; - const THROW_BAD_TWEAK = 'Expected Tweak'; - const THROW_BAD_HASH = 'Expected Hash'; - const THROW_BAD_SIGNATURE = 'Expected Signature'; - const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; - - function isScalar (x) { - return isBuffer(x) && x.length === 32 - } - - function isOrderScalar (x) { - if (!isScalar(x)) return false - return x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isPoint (p) { - if (!isBuffer(p)) return false - if (p.length < 33) return false - - const t = p[0]; - const x = p.slice(1, 33); - if (x.compare(ZERO32) === 0) return false - if (x.compare(EC_P) >= 0) return false - if ((t === 0x02 || t === 0x03) && p.length === 33) { - try { decodeFrom(p); } catch (e) { return false } // TODO: temporary - return true - } - - const y = p.slice(33); - if (y.compare(ZERO32) === 0) return false - if (y.compare(EC_P) >= 0) return false - if (t === 0x04 && p.length === 65) return true - return false - } - - function __isPointCompressed (p) { - return p[0] !== 0x04 - } - - function isPointCompressed (p) { - if (!isPoint(p)) return false - return __isPointCompressed(p) - } - - function isPrivate (x) { - if (!isScalar(x)) return false - return x.compare(ZERO32) > 0 && // > 0 - x.compare(EC_GROUP_ORDER) < 0 // < G - } - - function isSignature (value) { - const r = value.slice(0, 32); - const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && - r.compare(EC_GROUP_ORDER) < 0 && - s.compare(EC_GROUP_ORDER) < 0 - } - - function assumeCompression (value, pubkey) { - if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) - if (value === undefined) return true - return value - } - - function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$m, 'be', 32) } - function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$m.from(P._encode(compressed)) } - - function pointAdd (pA, pB, __compressed) { - if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) - if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) - - const a = decodeFrom(pA); - const b = decodeFrom(pB); - const pp = a.add(b); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed, pA); - return getEncoded(pp, compressed) - } - - function pointAddScalar (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) - - const tt = fromBuffer$1(tweak); - const qq = G.mul(tt); - const uu = pp.add(qq); - if (uu.isInfinity()) return null - - return getEncoded(uu, compressed) - } - - function pointCompress (p, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - - const pp = decodeFrom(p); - if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) - - const compressed = assumeCompression(__compressed, p); - - return getEncoded(pp, compressed) - } - - function pointFromScalar (d, __compressed) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - - const dd = fromBuffer$1(d); - const pp = G.mul(dd); - if (pp.isInfinity()) return null - - const compressed = assumeCompression(__compressed); - return getEncoded(pp, compressed) - } - - function pointMultiply (p, tweak, __compressed) { - if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const compressed = assumeCompression(__compressed, p); - const pp = decodeFrom(p); - const tt = fromBuffer$1(tweak); - const qq = pp.mul(tt); - if (qq.isInfinity()) return null - - return getEncoded(qq, compressed) - } - - function privateAdd (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.add(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function privateSub (d, tweak) { - if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) - if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) - - const dd = fromBuffer$1(d); - const tt = fromBuffer$1(tweak); - const dt = toBuffer$1(dd.sub(tt).umod(n)); - if (!isPrivate(dt)) return null - - return dt - } - - function sign (hash, x) { - return __sign(hash, x) - } - - function signWithEntropy (hash, x, addData) { - return __sign(hash, x, addData) - } - - function __sign (hash, x, addData) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) - if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) - - const d = fromBuffer$1(x); - const e = fromBuffer$1(hash); - - let r, s; - const checkSig = function (k) { - const kI = fromBuffer$1(k); - const Q = G.mul(kI); - - if (Q.isInfinity()) return false - - r = Q.x.umod(n); - if (r.isZero() === 0) return false - - s = kI - .invm(n) - .mul(e.add(d.mul(r))) - .umod(n); - if (s.isZero() === 0) return false - - return true - }; - - deterministicGenerateK(hash, x, checkSig, isPrivate, addData); - - // enforce low S values, see bip62: 'low s values in signatures' - if (s.cmp(nDiv2) > 0) { - s = n.sub(s); - } - - const buffer = Buffer$m.allocUnsafe(64); - toBuffer$1(r).copy(buffer, 0); - toBuffer$1(s).copy(buffer, 32); - return buffer - } - - function verify (hash, q, signature, strict) { - if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) - if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') - if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) - - const Q = decodeFrom(q); - const r = fromBuffer$1(signature.slice(0, 32)); - const s = fromBuffer$1(signature.slice(32, 64)); - - if (strict && s.cmp(nDiv2) > 0) { - return false - } - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') - if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false - if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false - - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - const e = fromBuffer$1(hash); - - // Compute s^-1 - const sInv = s.invm(n); - - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - const u1 = e.mul(sInv).umod(n); - const u2 = r.mul(sInv).umod(n); - - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - const R = G.mulAdd(u1, Q, u2); - - // 1.4.5 (cont.) Enforce R is not at infinity - if (R.isInfinity()) return false - - // 1.4.6 Convert the field element R.x to an integer - const xR = R.x; - - // 1.4.7 Set v = xR mod n - const v = xR.umod(n); - - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.eq(r) - } - - var js = { - isPoint, - isPointCompressed, - isPrivate, - pointAdd, - pointAddScalar, - pointCompress, - pointFromScalar, - pointMultiply, - privateAdd, - privateSub, - sign, - signWithEntropy, - verify - }; - - var types$c = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } - }; - - // TODO: deprecate - types$c.Null = types$c.Nil; - - for (var typeName$2 in types$c) { - types$c[typeName$2].toJSON = function (t) { - return t - }.bind(null, typeName$2); - } - - var native$1 = types$c; - - var native = native$1; - - function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] - } - - function getValueTypeName$1 (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) - } - - function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value - } - - function captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t); - } - } - - function tfJSON$1 (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' - - return type !== undefined ? type : '' - } - - function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value); - - return 'Expected ' + tfJSON$1(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') - } - - function TfTypeError$1 (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfErrorString(type, value, valueTypeName); - - captureStackTrace(this, TfTypeError$1); - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfTypeError$1.prototype = Object.create(Error.prototype); - TfTypeError$1.prototype.constructor = TfTypeError$1; - - function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type '; - if (label === 'key') description = '" with key type '; - - return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) - } - - function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName$1(value); - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); - } else { - this.message = 'Unexpected property "' + property + '"'; - } - - captureStackTrace(this, TfTypeError$1); - this.__label = label; - this.__property = property; - this.__type = type; - this.__value = value; - this.__valueTypeName = valueTypeName; - } - - TfPropertyTypeError$1.prototype = Object.create(Error.prototype); - TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; - - function tfCustomError (expected, actual) { - return new TfTypeError$1(expected, {}, actual) - } - - function tfSubError$1 (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError$1) { - property = property + '.' + e.__property; - - e = new TfPropertyTypeError$1( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ); - - // child? - } else if (e instanceof TfTypeError$1) { - e = new TfPropertyTypeError$1( - e.__type, property, label, e.__value, e.__valueTypeName - ); - } - - captureStackTrace(e); - return e - } - - var errors = { - TfTypeError: TfTypeError$1, - TfPropertyTypeError: TfPropertyTypeError$1, - tfCustomError: tfCustomError, - tfSubError: tfSubError$1, - tfJSON: tfJSON$1, - getValueTypeName: getValueTypeName$1 - }; - - var NATIVE$1 = native$1; - var ERRORS$1 = errors; - - function _Buffer (value) { - return isBuffer(value) - } - - function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) - } - - function _LengthN (type, length) { - var name = type.toJSON(); - - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true - - throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name }; - - return Length - } - - var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); - var _BufferN = _LengthN.bind(null, _Buffer); - var _HexN = _LengthN.bind(null, Hex); - var _StringN = _LengthN.bind(null, NATIVE$1.String); - - function Range$m (a, b, f) { - f = f || NATIVE$1.Number; - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) - } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - }; - return _range - } - - var INT53_MAX = Math.pow(2, 53) - 1; - - function Finite (value) { - return typeof value === 'number' && isFinite(value) - } - function Int8 (value) { return ((value << 24) >> 24) === value } - function Int16 (value) { return ((value << 16) >> 16) === value } - function Int32 (value) { return (value | 0) === value } - function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value - } - function UInt8 (value) { return (value & 0xff) === value } - function UInt16 (value) { return (value & 0xffff) === value } - function UInt32 (value) { return (value >>> 0) === value } - function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value - } - - var types$b = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range$m, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 - }; - - for (var typeName$1 in types$b) { - types$b[typeName$1].toJSON = function (t) { - return t - }.bind(null, typeName$1); - } - - var extra = types$b; - - var ERRORS = errors; - var NATIVE = native$1; - - // short-hand - var tfJSON = ERRORS.tfJSON; - var TfTypeError = ERRORS.TfTypeError; - var TfPropertyTypeError = ERRORS.TfPropertyTypeError; - var tfSubError = ERRORS.tfSubError; - var getValueTypeName = ERRORS.getValueTypeName; - - var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type); - options = options || {}; - - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false - - return array.every(function (value, i) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']'; - if (options.length !== undefined) { - str += '{' + options.length + '}'; - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; - } - return str - }; - - return _arrayOf - }, - - maybe: function maybe (type) { - type = compile(type); - - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) }; - - return _maybe - }, - - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType); - if (propertyKeyType) propertyKeyType = compile(propertyKeyType); - - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce$b(propertyKeyType, propertyName, strict); - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } - - try { - var propertyValue = value[propertyName]; - typeforce$b(propertyType, propertyValue, strict); - } catch (e) { - throw tfSubError(e, propertyName) - } - } - - return true - } - - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - }; - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; - } - - return _map - }, - - object: function object (uncompiled) { - var type = {}; - - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]); - } - - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - var propertyName; - - try { - for (propertyName in type) { - var propertyType = type[propertyName]; - var propertyValue = value[propertyName]; - - typeforce$b(propertyType, propertyValue, strict); - } - } catch (e) { - throw tfSubError(e, propertyName) - } - - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue - - throw new TfPropertyTypeError(undefined, propertyName) - } - } - - return true - } - _object.toJSON = function () { return tfJSON(type) }; - - return _object - }, - - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile); - - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; - - return _anyOf - }, - - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile); - - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce$b(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; - - return _allOf - }, - - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type }; - - return _quacksLike - }, - - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile); - - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false - - return types.every(function (type, i) { - try { - return typeforce$b(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; - - return _tuple - }, - - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected }; - - return _value - } - }; - - // TODO: deprecate - TYPES.oneOf = TYPES.anyOf; - - function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) - - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } - - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } - - return TYPES.value(type) - } - - function typeforce$b (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true - - throw new TfTypeError(surrogate || type, value) - } - - // JIT - return typeforce$b(compile(type), value, strict) - } - - // assign types to typeforce function - for (var typeName in NATIVE) { - typeforce$b[typeName] = NATIVE[typeName]; - } - - for (typeName in TYPES) { - typeforce$b[typeName] = TYPES[typeName]; - } - - var EXTRA = extra; - for (typeName in EXTRA) { - typeforce$b[typeName] = EXTRA[typeName]; - } - - typeforce$b.compile = compile; - typeforce$b.TfTypeError = TfTypeError; - typeforce$b.TfPropertyTypeError = TfPropertyTypeError; - - var typeforce_1 = typeforce$b; - - var bs58check$4 = bs58check$5; - - function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') - - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false - } - } - - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') - - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') - - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } - } - - function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$m(compressed ? 34 : 33); - - result.writeUInt8(version, 0); - privateKey.copy(result, 1); - - if (compressed) { - result[33] = 0x01; - } - - return result - } - - function decode$g (string, version) { - return decodeRaw(bs58check$4.decode(string), version) - } - - function encode$h (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) - - return bs58check$4.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) - } - - var wif$2 = { - decode: decode$g, - decodeRaw: decodeRaw, - encode: encode$h, - encodeRaw: encodeRaw - }; - - Object.defineProperty(bip32$1, "__esModule", { value: true }); - const crypto$3 = crypto$5; - const bs58check$3 = bs58check$5; - const ecc$6 = js; - const typeforce$a = typeforce_1; - const wif$1 = wif$2; - const UINT256_TYPE = typeforce$a.BufferN(32); - const NETWORK_TYPE = typeforce$a.compile({ - wif: typeforce$a.UInt8, - bip32: { - public: typeforce$a.UInt32, - private: typeforce$a.UInt32, - }, - }); - const BITCOIN = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - const HIGHEST_BIT = 0x80000000; - const UINT31_MAX$1 = Math.pow(2, 31) - 1; - function BIP32Path$1(value) { - return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); - } - function UInt31$1(value) { - return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; - } - class BIP32 { - constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { - this.__D = __D; - this.__Q = __Q; - this.chainCode = chainCode; - this.network = network; - this.__DEPTH = __DEPTH; - this.__INDEX = __INDEX; - this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; - typeforce$a(NETWORK_TYPE, network); - this.lowR = false; - } - get depth() { - return this.__DEPTH; - } - get index() { - return this.__INDEX; - } - get parentFingerprint() { - return this.__PARENT_FINGERPRINT; - } - get publicKey() { - if (this.__Q === undefined) - this.__Q = ecc$6.pointFromScalar(this.__D, true); - return this.__Q; - } - get privateKey() { - return this.__D; - } - get identifier() { - return crypto$3.hash160(this.publicKey); - } - get fingerprint() { - return this.identifier.slice(0, 4); - } - get compressed() { - return true; - } - // Private === not neutered - // Public === neutered - isNeutered() { - return this.__D === undefined; - } - neutered() { - return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); - } - toBase58() { - const network = this.network; - const version = !this.isNeutered() - ? network.bip32.private - : network.bip32.public; - const buffer = Buffer$m.allocUnsafe(78); - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4); - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5); - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9); - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13); - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45); - this.privateKey.copy(buffer, 46); - // 33 bytes: the public key - } - else { - // X9.62 encoding for public keys - this.publicKey.copy(buffer, 45); - } - return bs58check$3.encode(buffer); - } - toWIF() { - if (!this.privateKey) - throw new TypeError('Missing private key'); - return wif$1.encode(this.network.wif, this.privateKey, true); - } - // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions - derive(index) { - typeforce$a(typeforce$a.UInt32, index); - const isHardened = index >= HIGHEST_BIT; - const data = Buffer$m.allocUnsafe(37); - // Hardened child - if (isHardened) { - if (this.isNeutered()) - throw new TypeError('Missing private key for hardened child key'); - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00; - this.privateKey.copy(data, 1); - data.writeUInt32BE(index, 33); - // Normal child - } - else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.publicKey.copy(data, 0); - data.writeUInt32BE(index, 33); - } - const I = crypto$3.hmacSHA512(this.chainCode, data); - const IL = I.slice(0, 32); - const IR = I.slice(32); - // if parse256(IL) >= n, proceed with the next value for i - if (!ecc$6.isPrivate(IL)) - return this.derive(index + 1); - // Private parent key -> private child key - let hd; - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - const ki = ecc$6.privateAdd(this.privateKey, IL); - // In case ki == 0, proceed with the next value for i - if (ki == null) - return this.derive(index + 1); - hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - // Public parent key -> public child key - } - else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); - // In case Ki is the point at infinity, proceed with the next value for i - if (Ki === null) - return this.derive(index + 1); - hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); - } - return hd; - } - deriveHardened(index) { - typeforce$a(UInt31$1, index); - // Only derives hardened private keys by default - return this.derive(index + HIGHEST_BIT); - } - derivePath(path) { - typeforce$a(BIP32Path$1, path); - let splitPath = path.split('/'); - if (splitPath[0] === 'm') { - if (this.parentFingerprint) - throw new TypeError('Expected master, got child'); - splitPath = splitPath.slice(1); - } - return splitPath.reduce((prevHd, indexStr) => { - let index; - if (indexStr.slice(-1) === `'`) { - index = parseInt(indexStr.slice(0, -1), 10); - return prevHd.deriveHardened(index); - } - else { - index = parseInt(indexStr, 10); - return prevHd.derive(index); - } - }, this); - } - sign(hash, lowR) { - if (!this.privateKey) - throw new Error('Missing private key'); - if (lowR === undefined) - lowR = this.lowR; - if (lowR === false) { - return ecc$6.sign(hash, this.privateKey); - } - else { - let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc$6.verify(hash, this.publicKey, signature); - } - } - function fromBase58(inString, network) { - const buffer = bs58check$3.decode(inString); - if (buffer.length !== 78) - throw new TypeError('Invalid buffer length'); - network = network || BITCOIN; - // 4 bytes: version bytes - const version = buffer.readUInt32BE(0); - if (version !== network.bip32.private && version !== network.bip32.public) - throw new TypeError('Invalid network version'); - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - const depth = buffer[4]; - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - const parentFingerprint = buffer.readUInt32BE(5); - if (depth === 0) { - if (parentFingerprint !== 0x00000000) - throw new TypeError('Invalid parent fingerprint'); - } - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - const index = buffer.readUInt32BE(9); - if (depth === 0 && index !== 0) - throw new TypeError('Invalid index'); - // 32 bytes: the chain code - const chainCode = buffer.slice(13, 45); - let hd; - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) - throw new TypeError('Invalid private key'); - const k = buffer.slice(46, 78); - hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } - else { - const X = buffer.slice(45, 78); - hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); - } - return hd; - } - bip32$1.fromBase58 = fromBase58; - function fromPrivateKey$1(privateKey, chainCode, network) { - return fromPrivateKeyLocal(privateKey, chainCode, network); - } - bip32$1.fromPrivateKey = fromPrivateKey$1; - function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - privateKey: UINT256_TYPE, - chainCode: UINT256_TYPE, - }, { privateKey, chainCode }); - network = network || BITCOIN; - if (!ecc$6.isPrivate(privateKey)) - throw new TypeError('Private key not in range [1, n)'); - return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); - } - function fromPublicKey$1(publicKey, chainCode, network) { - return fromPublicKeyLocal(publicKey, chainCode, network); - } - bip32$1.fromPublicKey = fromPublicKey$1; - function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { - typeforce$a({ - publicKey: typeforce$a.BufferN(33), - chainCode: UINT256_TYPE, - }, { publicKey, chainCode }); - network = network || BITCOIN; - // verify the X coordinate is a point on the curve - if (!ecc$6.isPoint(publicKey)) - throw new TypeError('Point is not on the curve'); - return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); - } - function fromSeed(seed, network) { - typeforce$a(typeforce$a.Buffer, seed); - if (seed.length < 16) - throw new TypeError('Seed should be at least 128 bits'); - if (seed.length > 64) - throw new TypeError('Seed should be at most 512 bits'); - network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$m.from('Bitcoin seed', 'utf8'), seed); - const IL = I.slice(0, 32); - const IR = I.slice(32); - return fromPrivateKey$1(IL, IR, network); - } - bip32$1.fromSeed = fromSeed; - - Object.defineProperty(src$1, "__esModule", { value: true }); - var bip32_1 = bip32$1; - src$1.fromSeed = bip32_1.fromSeed; - src$1.fromBase58 = bip32_1.fromBase58; - src$1.fromPublicKey = bip32_1.fromPublicKey; - src$1.fromPrivateKey = bip32_1.fromPrivateKey; - - var address$1 = {}; - - var networks$3 = {}; - - Object.defineProperty(networks$3, '__esModule', { value: true }); - networks$3.bitcoin = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4, - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80, - }; - networks$3.regtest = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bcrt', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - networks$3.testnet = { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394, - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef, - }; - - var payments$4 = {}; - - var embed = {}; - - var script$1 = {}; - - var script_number = {}; - - Object.defineProperty(script_number, '__esModule', { value: true }); - function decode$f(buffer, maxLength, minimal) { - maxLength = maxLength || 4; - minimal = minimal === undefined ? true : minimal; - const length = buffer.length; - if (length === 0) return 0; - if (length > maxLength) throw new TypeError('Script number overflow'); - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) - throw new Error('Non-minimally encoded script number'); - } - } - // 40-bit - if (length === 5) { - const a = buffer.readUInt32LE(0); - const b = buffer.readUInt8(4); - if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); - return b * 0x100000000 + a; - } - // 32-bit / 24-bit / 16-bit / 8-bit - let result = 0; - for (let i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i); - } - if (buffer[length - 1] & 0x80) - return -(result & ~(0x80 << (8 * (length - 1)))); - return result; - } - script_number.decode = decode$f; - function scriptNumSize(i) { - return i > 0x7fffffff - ? 5 - : i > 0x7fffff - ? 4 - : i > 0x7fff - ? 3 - : i > 0x7f - ? 2 - : i > 0x00 - ? 1 - : 0; - } - function encode$g(_number) { - let value = Math.abs(_number); - const size = scriptNumSize(value); - const buffer = Buffer$m.allocUnsafe(size); - const negative = _number < 0; - for (let i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i); - value >>= 8; - } - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); - } else if (negative) { - buffer[size - 1] |= 0x80; - } - return buffer; - } - script_number.encode = encode$g; - - var script_signature = {}; - - var types$a = {}; - - Object.defineProperty(types$a, '__esModule', { value: true }); - const typeforce$9 = typeforce_1; - const UINT31_MAX = Math.pow(2, 31) - 1; - function UInt31(value) { - return typeforce$9.UInt32(value) && value <= UINT31_MAX; - } - types$a.UInt31 = UInt31; - function BIP32Path(value) { - return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); - } - types$a.BIP32Path = BIP32Path; - BIP32Path.toJSON = () => { - return 'BIP32 derivation path'; - }; - function Signer(obj) { - return ( - (typeforce$9.Buffer(obj.publicKey) || - typeof obj.getPublicKey === 'function') && - typeof obj.sign === 'function' - ); - } - types$a.Signer = Signer; - const SATOSHI_MAX = 21 * 1e14; - function Satoshi(value) { - return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; - } - types$a.Satoshi = Satoshi; - // external dependent types - types$a.ECPoint = typeforce$9.quacksLike('Point'); - // exposed, external API - types$a.Network = typeforce$9.compile({ - messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), - bip32: { - public: typeforce$9.UInt32, - private: typeforce$9.UInt32, - }, - pubKeyHash: typeforce$9.UInt8, - scriptHash: typeforce$9.UInt8, - wif: typeforce$9.UInt8, - }); - types$a.Buffer256bit = typeforce$9.BufferN(32); - types$a.Hash160bit = typeforce$9.BufferN(20); - types$a.Hash256bit = typeforce$9.BufferN(32); - types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name - types$a.Array = typeforce$9.Array; - types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name - types$a.String = typeforce$9.String; // tslint:disable-line variable-name - types$a.Buffer = typeforce$9.Buffer; - types$a.Hex = typeforce$9.Hex; - types$a.maybe = typeforce$9.maybe; - types$a.tuple = typeforce$9.tuple; - types$a.UInt8 = typeforce$9.UInt8; - types$a.UInt32 = typeforce$9.UInt32; - types$a.Function = typeforce$9.Function; - types$a.BufferN = typeforce$9.BufferN; - types$a.Null = typeforce$9.Null; - types$a.oneOf = typeforce$9.oneOf; - - // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki - // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - // NOTE: SIGHASH byte ignored AND restricted, truncate before use - - var Buffer$2 = safeBuffer.exports.Buffer; - - function check$m (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false - - var lenR = buffer[3]; - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false - - var lenS = buffer[5 + lenR]; - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false - - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true - } - - function decode$e (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - - var lenR = buffer[3]; - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - - var lenS = buffer[5 + lenR]; - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } - } - - /* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 - */ - function encode$f (r, s) { - var lenR = r.length; - var lenS = s.length; - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30; - signature[1] = signature.length - 2; - signature[2] = 0x02; - signature[3] = r.length; - r.copy(signature, 4); - signature[4 + lenR] = 0x02; - signature[5 + lenR] = s.length; - s.copy(signature, 6 + lenR); - - return signature - } - - var bip66$1 = { - check: check$m, - decode: decode$e, - encode: encode$f - }; - - Object.defineProperty(script_signature, '__esModule', { value: true }); - const types$9 = types$a; - const bip66 = bip66$1; - const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$m.alloc(1, 0); - function toDER(x) { - let i = 0; - while (x[i] === 0) ++i; - if (i === x.length) return ZERO$1; - x = x.slice(i); - if (x[0] & 0x80) return Buffer$m.concat([ZERO$1, x], 1 + x.length); - return x; - } - function fromDER(x) { - if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$m.alloc(32, 0); - const bstart = Math.max(0, 32 - x.length); - x.copy(buffer, bstart); - return buffer; - } - // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) - function decode$d(buffer) { - const hashType = buffer.readUInt8(buffer.length - 1); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const decoded = bip66.decode(buffer.slice(0, -1)); - const r = fromDER(decoded.r); - const s = fromDER(decoded.s); - const signature = Buffer$m.concat([r, s], 64); - return { signature, hashType }; - } - script_signature.decode = decode$d; - function encode$e(signature, hashType) { - typeforce$8( - { - signature: types$9.BufferN(64), - hashType: types$9.UInt8, - }, - { signature, hashType }, - ); - const hashTypeMod = hashType & ~0x80; - if (hashTypeMod <= 0 || hashTypeMod >= 4) - throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$m.allocUnsafe(1); - hashTypeBuffer.writeUInt8(hashType, 0); - const r = toDER(signature.slice(0, 32)); - const s = toDER(signature.slice(32, 64)); - return Buffer$m.concat([bip66.encode(r, s), hashTypeBuffer]); - } - script_signature.encode = encode$e; - - var OP_FALSE = 0; - var OP_0 = 0; - var OP_PUSHDATA1 = 76; - var OP_PUSHDATA2 = 77; - var OP_PUSHDATA4 = 78; - var OP_1NEGATE = 79; - var OP_RESERVED = 80; - var OP_TRUE = 81; - var OP_1 = 81; - var OP_2 = 82; - var OP_3 = 83; - var OP_4 = 84; - var OP_5 = 85; - var OP_6 = 86; - var OP_7 = 87; - var OP_8 = 88; - var OP_9 = 89; - var OP_10 = 90; - var OP_11 = 91; - var OP_12 = 92; - var OP_13 = 93; - var OP_14 = 94; - var OP_15 = 95; - var OP_16 = 96; - var OP_NOP = 97; - var OP_VER = 98; - var OP_IF = 99; - var OP_NOTIF = 100; - var OP_VERIF = 101; - var OP_VERNOTIF = 102; - var OP_ELSE = 103; - var OP_ENDIF = 104; - var OP_VERIFY = 105; - var OP_RETURN = 106; - var OP_TOALTSTACK = 107; - var OP_FROMALTSTACK = 108; - var OP_2DROP = 109; - var OP_2DUP = 110; - var OP_3DUP = 111; - var OP_2OVER = 112; - var OP_2ROT = 113; - var OP_2SWAP = 114; - var OP_IFDUP = 115; - var OP_DEPTH = 116; - var OP_DROP = 117; - var OP_DUP$1 = 118; - var OP_NIP = 119; - var OP_OVER = 120; - var OP_PICK = 121; - var OP_ROLL = 122; - var OP_ROT = 123; - var OP_SWAP = 124; - var OP_TUCK = 125; - var OP_CAT = 126; - var OP_SUBSTR = 127; - var OP_LEFT = 128; - var OP_RIGHT = 129; - var OP_SIZE = 130; - var OP_INVERT = 131; - var OP_AND = 132; - var OP_OR = 133; - var OP_XOR = 134; - var OP_EQUAL$1 = 135; - var OP_EQUALVERIFY$1 = 136; - var OP_RESERVED1 = 137; - var OP_RESERVED2 = 138; - var OP_1ADD = 139; - var OP_1SUB = 140; - var OP_2MUL = 141; - var OP_2DIV = 142; - var OP_NEGATE = 143; - var OP_ABS = 144; - var OP_NOT = 145; - var OP_0NOTEQUAL = 146; - var OP_ADD = 147; - var OP_SUB = 148; - var OP_MUL = 149; - var OP_DIV = 150; - var OP_MOD = 151; - var OP_LSHIFT = 152; - var OP_RSHIFT = 153; - var OP_BOOLAND = 154; - var OP_BOOLOR = 155; - var OP_NUMEQUAL = 156; - var OP_NUMEQUALVERIFY = 157; - var OP_NUMNOTEQUAL = 158; - var OP_LESSTHAN = 159; - var OP_GREATERTHAN = 160; - var OP_LESSTHANOREQUAL = 161; - var OP_GREATERTHANOREQUAL = 162; - var OP_MIN = 163; - var OP_MAX = 164; - var OP_WITHIN = 165; - var OP_RIPEMD160 = 166; - var OP_SHA1 = 167; - var OP_SHA256 = 168; - var OP_HASH160$1 = 169; - var OP_HASH256 = 170; - var OP_CODESEPARATOR = 171; - var OP_CHECKSIG$1 = 172; - var OP_CHECKSIGVERIFY = 173; - var OP_CHECKMULTISIG = 174; - var OP_CHECKMULTISIGVERIFY = 175; - var OP_NOP1 = 176; - var OP_NOP2 = 177; - var OP_CHECKLOCKTIMEVERIFY = 177; - var OP_NOP3 = 178; - var OP_CHECKSEQUENCEVERIFY = 178; - var OP_NOP4 = 179; - var OP_NOP5 = 180; - var OP_NOP6 = 181; - var OP_NOP7 = 182; - var OP_NOP8 = 183; - var OP_NOP9 = 184; - var OP_NOP10 = 185; - var OP_PUBKEYHASH = 253; - var OP_PUBKEY = 254; - var OP_INVALIDOPCODE = 255; - var require$$7 = { - OP_FALSE: OP_FALSE, - OP_0: OP_0, - OP_PUSHDATA1: OP_PUSHDATA1, - OP_PUSHDATA2: OP_PUSHDATA2, - OP_PUSHDATA4: OP_PUSHDATA4, - OP_1NEGATE: OP_1NEGATE, - OP_RESERVED: OP_RESERVED, - OP_TRUE: OP_TRUE, - OP_1: OP_1, - OP_2: OP_2, - OP_3: OP_3, - OP_4: OP_4, - OP_5: OP_5, - OP_6: OP_6, - OP_7: OP_7, - OP_8: OP_8, - OP_9: OP_9, - OP_10: OP_10, - OP_11: OP_11, - OP_12: OP_12, - OP_13: OP_13, - OP_14: OP_14, - OP_15: OP_15, - OP_16: OP_16, - OP_NOP: OP_NOP, - OP_VER: OP_VER, - OP_IF: OP_IF, - OP_NOTIF: OP_NOTIF, - OP_VERIF: OP_VERIF, - OP_VERNOTIF: OP_VERNOTIF, - OP_ELSE: OP_ELSE, - OP_ENDIF: OP_ENDIF, - OP_VERIFY: OP_VERIFY, - OP_RETURN: OP_RETURN, - OP_TOALTSTACK: OP_TOALTSTACK, - OP_FROMALTSTACK: OP_FROMALTSTACK, - OP_2DROP: OP_2DROP, - OP_2DUP: OP_2DUP, - OP_3DUP: OP_3DUP, - OP_2OVER: OP_2OVER, - OP_2ROT: OP_2ROT, - OP_2SWAP: OP_2SWAP, - OP_IFDUP: OP_IFDUP, - OP_DEPTH: OP_DEPTH, - OP_DROP: OP_DROP, - OP_DUP: OP_DUP$1, - OP_NIP: OP_NIP, - OP_OVER: OP_OVER, - OP_PICK: OP_PICK, - OP_ROLL: OP_ROLL, - OP_ROT: OP_ROT, - OP_SWAP: OP_SWAP, - OP_TUCK: OP_TUCK, - OP_CAT: OP_CAT, - OP_SUBSTR: OP_SUBSTR, - OP_LEFT: OP_LEFT, - OP_RIGHT: OP_RIGHT, - OP_SIZE: OP_SIZE, - OP_INVERT: OP_INVERT, - OP_AND: OP_AND, - OP_OR: OP_OR, - OP_XOR: OP_XOR, - OP_EQUAL: OP_EQUAL$1, - OP_EQUALVERIFY: OP_EQUALVERIFY$1, - OP_RESERVED1: OP_RESERVED1, - OP_RESERVED2: OP_RESERVED2, - OP_1ADD: OP_1ADD, - OP_1SUB: OP_1SUB, - OP_2MUL: OP_2MUL, - OP_2DIV: OP_2DIV, - OP_NEGATE: OP_NEGATE, - OP_ABS: OP_ABS, - OP_NOT: OP_NOT, - OP_0NOTEQUAL: OP_0NOTEQUAL, - OP_ADD: OP_ADD, - OP_SUB: OP_SUB, - OP_MUL: OP_MUL, - OP_DIV: OP_DIV, - OP_MOD: OP_MOD, - OP_LSHIFT: OP_LSHIFT, - OP_RSHIFT: OP_RSHIFT, - OP_BOOLAND: OP_BOOLAND, - OP_BOOLOR: OP_BOOLOR, - OP_NUMEQUAL: OP_NUMEQUAL, - OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, - OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, - OP_LESSTHAN: OP_LESSTHAN, - OP_GREATERTHAN: OP_GREATERTHAN, - OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, - OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, - OP_MIN: OP_MIN, - OP_MAX: OP_MAX, - OP_WITHIN: OP_WITHIN, - OP_RIPEMD160: OP_RIPEMD160, - OP_SHA1: OP_SHA1, - OP_SHA256: OP_SHA256, - OP_HASH160: OP_HASH160$1, - OP_HASH256: OP_HASH256, - OP_CODESEPARATOR: OP_CODESEPARATOR, - OP_CHECKSIG: OP_CHECKSIG$1, - OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, - OP_CHECKMULTISIG: OP_CHECKMULTISIG, - OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, - OP_NOP1: OP_NOP1, - OP_NOP2: OP_NOP2, - OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, - OP_NOP3: OP_NOP3, - OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, - OP_NOP4: OP_NOP4, - OP_NOP5: OP_NOP5, - OP_NOP6: OP_NOP6, - OP_NOP7: OP_NOP7, - OP_NOP8: OP_NOP8, - OP_NOP9: OP_NOP9, - OP_NOP10: OP_NOP10, - OP_PUBKEYHASH: OP_PUBKEYHASH, - OP_PUBKEY: OP_PUBKEY, - OP_INVALIDOPCODE: OP_INVALIDOPCODE - }; - - var OPS$9 = require$$7; - - function encodingLength$2 (i) { - return i < OPS$9.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 - } - - function encode$d (buffer, number, offset) { - var size = encodingLength$2(number); - - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset); - - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); - buffer.writeUInt8(number, offset + 1); - - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); - buffer.writeUInt16LE(number, offset + 1); - - // 32 bit - } else { - buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); - buffer.writeUInt32LE(number, offset + 1); - } - - return size - } - - function decode$c (buffer, offset) { - var opcode = buffer.readUInt8(offset); - var number, size; - - // ~6 bit - if (opcode < OPS$9.OP_PUSHDATA1) { - number = opcode; - size = 1; - - // 8 bit - } else if (opcode === OPS$9.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1); - size = 2; - - // 16 bit - } else if (opcode === OPS$9.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1); - size = 3; - - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') - - number = buffer.readUInt32LE(offset + 1); - size = 5; - } - - return { - opcode: opcode, - number: number, - size: size - } - } - - var pushdataBitcoin = { - encodingLength: encodingLength$2, - encode: encode$d, - decode: decode$c - }; - - var OPS$8 = require$$7; - - var map = {}; - for (var op in OPS$8) { - var code = OPS$8[op]; - map[code] = op; - } - - var map_1 = map; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const scriptNumber = script_number; - const scriptSignature = script_signature; - const types = types$a; - const bip66 = bip66$1; - const ecc = js; - const pushdata = pushdataBitcoin; - const typeforce = typeforce_1; - exports.OPS = require$$7; - const REVERSE_OPS = map_1; - const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 - function isOPInt(value) { - return ( - types.Number(value) && - (value === exports.OPS.OP_0 || - (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || - value === exports.OPS.OP_1NEGATE) - ); - } - function isPushOnlyChunk(value) { - return types.Buffer(value) || isOPInt(value); - } - function isPushOnly(value) { - return types.Array(value) && value.every(isPushOnlyChunk); - } - exports.isPushOnly = isPushOnly; - function asMinimalOP(buffer) { - if (buffer.length === 0) return exports.OPS.OP_0; - if (buffer.length !== 1) return; - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; - if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; - } - function chunksIsBuffer(buf) { - return isBuffer(buf); - } - function chunksIsArray(buf) { - return types.Array(buf); - } - function singleChunkIsBuffer(buf) { - return isBuffer(buf); - } - function compile(chunks) { - // TODO: remove me - if (chunksIsBuffer(chunks)) return chunks; - typeforce(types.Array, chunks); - const bufferSize = chunks.reduce((accum, chunk) => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1; - } - return accum + pushdata.encodingLength(chunk.length) + chunk.length; - } - // opcode - return accum + 1; - }, 0.0); - const buffer = Buffer$m.allocUnsafe(bufferSize); - let offset = 0; - chunks.forEach(chunk => { - // data chunk - if (singleChunkIsBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - const opcode = asMinimalOP(chunk); - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset); - offset += 1; - return; - } - offset += pushdata.encode(buffer, chunk.length, offset); - chunk.copy(buffer, offset); - offset += chunk.length; - // opcode - } else { - buffer.writeUInt8(chunk, offset); - offset += 1; - } - }); - if (offset !== buffer.length) throw new Error('Could not decode chunks'); - return buffer; - } - exports.compile = compile; - function decompile(buffer) { - // TODO: remove me - if (chunksIsArray(buffer)) return buffer; - typeforce(types.Buffer, buffer); - const chunks = []; - let i = 0; - while (i < buffer.length) { - const opcode = buffer[i]; - // data chunk - if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { - const d = pushdata.decode(buffer, i); - // did reading a pushDataInt fail? - if (d === null) return null; - i += d.size; - // attempt to read too much data? - if (i + d.number > buffer.length) return null; - const data = buffer.slice(i, i + d.number); - i += d.number; - // decompile minimally - const op = asMinimalOP(data); - if (op !== undefined) { - chunks.push(op); - } else { - chunks.push(data); - } - // opcode - } else { - chunks.push(opcode); - i += 1; - } - } - return chunks; - } - exports.decompile = decompile; - function toASM(chunks) { - if (chunksIsBuffer(chunks)) { - chunks = decompile(chunks); - } - return chunks - .map(chunk => { - // data? - if (singleChunkIsBuffer(chunk)) { - const op = asMinimalOP(chunk); - if (op === undefined) return chunk.toString('hex'); - chunk = op; - } - // opcode! - return REVERSE_OPS[chunk]; - }) - .join(' '); - } - exports.toASM = toASM; - function fromASM(asm) { - typeforce(types.String, asm); - return compile( - asm.split(' ').map(chunkStr => { - // opcode? - if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; - typeforce(types.Hex, chunkStr); - // data! - return Buffer$m.from(chunkStr, 'hex'); - }), - ); - } - exports.fromASM = fromASM; - function toStack(chunks) { - chunks = decompile(chunks); - typeforce(isPushOnly, chunks); - return chunks.map(op => { - if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$m.allocUnsafe(0); - return scriptNumber.encode(op - OP_INT_BASE); - }); - } - exports.toStack = toStack; - function isCanonicalPubKey(buffer) { - return ecc.isPoint(buffer); - } - exports.isCanonicalPubKey = isCanonicalPubKey; - function isDefinedHashType(hashType) { - const hashTypeMod = hashType & ~0x80; - // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04; - } - exports.isDefinedHashType = isDefinedHashType; - function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; - if (!isDefinedHashType(buffer[buffer.length - 1])) return false; - return bip66.check(buffer.slice(0, -1)); - } - exports.isCanonicalScriptSignature = isCanonicalScriptSignature; - // tslint:disable-next-line variable-name - exports.number = scriptNumber; - exports.signature = scriptSignature; - }(script$1)); - - var lazy$7 = {}; - - Object.defineProperty(lazy$7, '__esModule', { value: true }); - function prop(object, name, f) { - Object.defineProperty(object, name, { - configurable: true, - enumerable: true, - get() { - const _value = f.call(this); - this[name] = _value; - return _value; - }, - set(_value) { - Object.defineProperty(this, name, { - configurable: true, - enumerable: true, - value: _value, - writable: true, - }); - }, - }); - } - lazy$7.prop = prop; - function value(f) { - let _value; - return () => { - if (_value !== undefined) return _value; - _value = f(); - return _value; - }; - } - lazy$7.value = value; - - Object.defineProperty(embed, '__esModule', { value: true }); - const networks_1$7 = networks$3; - const bscript$o = script$1; - const lazy$6 = lazy$7; - const typef$6 = typeforce_1; - const OPS$7 = bscript$o.OPS; - function stacksEqual$3(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // output: OP_RETURN ... - function p2data(a, opts) { - if (!a.data && !a.output) throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$6( - { - network: typef$6.maybe(typef$6.Object), - output: typef$6.maybe(typef$6.Buffer), - data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), - }, - a, - ); - const network = a.network || networks_1$7.bitcoin; - const o = { name: 'embed', network }; - lazy$6.prop(o, 'output', () => { - if (!a.data) return; - return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); - }); - lazy$6.prop(o, 'data', () => { - if (!a.output) return; - return bscript$o.decompile(a.output).slice(1); - }); - // extended validation - if (opts.validate) { - if (a.output) { - const chunks = bscript$o.decompile(a.output); - if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); - if (!chunks.slice(1).every(typef$6.Buffer)) - throw new TypeError('Output is invalid'); - if (a.data && !stacksEqual$3(a.data, o.data)) - throw new TypeError('Data mismatch'); - } - } - return Object.assign(o, a); - } - embed.p2data = p2data; - - var p2ms$3 = {}; - - Object.defineProperty(p2ms$3, '__esModule', { value: true }); - const networks_1$6 = networks$3; - const bscript$n = script$1; - const lazy$5 = lazy$7; - const OPS$6 = bscript$n.OPS; - const typef$5 = typeforce_1; - const ecc$5 = js; - const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 - function stacksEqual$2(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: OP_0 [signatures ...] - // output: m [pubKeys ...] n OP_CHECKMULTISIG - function p2ms$2(a, opts) { - if ( - !a.input && - !a.output && - !(a.pubkeys && a.m !== undefined) && - !a.signatures - ) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - function isAcceptableSignature(x) { - return ( - bscript$n.isCanonicalScriptSignature(x) || - (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined - ); - } - typef$5( - { - network: typef$5.maybe(typef$5.Object), - m: typef$5.maybe(typef$5.Number), - n: typef$5.maybe(typef$5.Number), - output: typef$5.maybe(typef$5.Buffer), - pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), - signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), - input: typef$5.maybe(typef$5.Buffer), - }, - a, - ); - const network = a.network || networks_1$6.bitcoin; - const o = { network }; - let chunks = []; - let decoded = false; - function decode(output) { - if (decoded) return; - decoded = true; - chunks = bscript$n.decompile(output); - o.m = chunks[0] - OP_INT_BASE$1; - o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; - o.pubkeys = chunks.slice(1, -2); - } - lazy$5.prop(o, 'output', () => { - if (!a.m) return; - if (!o.n) return; - if (!a.pubkeys) return; - return bscript$n.compile( - [].concat( - OP_INT_BASE$1 + a.m, - a.pubkeys, - OP_INT_BASE$1 + o.n, - OPS$6.OP_CHECKMULTISIG, - ), - ); - }); - lazy$5.prop(o, 'm', () => { - if (!o.output) return; - decode(o.output); - return o.m; - }); - lazy$5.prop(o, 'n', () => { - if (!o.pubkeys) return; - return o.pubkeys.length; - }); - lazy$5.prop(o, 'pubkeys', () => { - if (!a.output) return; - decode(a.output); - return o.pubkeys; - }); - lazy$5.prop(o, 'signatures', () => { - if (!a.input) return; - return bscript$n.decompile(a.input).slice(1); - }); - lazy$5.prop(o, 'input', () => { - if (!a.signatures) return; - return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); - }); - lazy$5.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - lazy$5.prop(o, 'name', () => { - if (!o.m || !o.n) return; - return `p2ms(${o.m} of ${o.n})`; - }); - // extended validation - if (opts.validate) { - if (a.output) { - decode(a.output); - if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); - if (!typef$5.Number(chunks[chunks.length - 2])) - throw new TypeError('Output is invalid'); - if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) - throw new TypeError('Output is invalid'); - if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) - throw new TypeError('Output is invalid'); - if (!o.pubkeys.every(x => ecc$5.isPoint(x))) - throw new TypeError('Output is invalid'); - if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); - if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); - if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) - throw new TypeError('Pubkeys mismatch'); - } - if (a.pubkeys) { - if (a.n !== undefined && a.n !== a.pubkeys.length) - throw new TypeError('Pubkey count mismatch'); - o.n = a.pubkeys.length; - if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); - } - if (a.signatures) { - if (a.signatures.length < o.m) - throw new TypeError('Not enough signatures provided'); - if (a.signatures.length > o.m) - throw new TypeError('Too many signatures provided'); - } - if (a.input) { - if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); - if ( - o.signatures.length === 0 || - !o.signatures.every(isAcceptableSignature) - ) - throw new TypeError('Input has invalid signature(s)'); - if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) - throw new TypeError('Signature mismatch'); - if (a.m !== undefined && a.m !== a.signatures.length) - throw new TypeError('Signature count mismatch'); - } - } - return Object.assign(o, a); - } - p2ms$3.p2ms = p2ms$2; - - var p2pk$3 = {}; - - Object.defineProperty(p2pk$3, '__esModule', { value: true }); - const networks_1$5 = networks$3; - const bscript$m = script$1; - const lazy$4 = lazy$7; - const typef$4 = typeforce_1; - const OPS$5 = bscript$m.OPS; - const ecc$4 = js; - // input: {signature} - // output: {pubKey} OP_CHECKSIG - function p2pk$2(a, opts) { - if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$4( - { - network: typef$4.maybe(typef$4.Object), - output: typef$4.maybe(typef$4.Buffer), - pubkey: typef$4.maybe(ecc$4.isPoint), - signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), - input: typef$4.maybe(typef$4.Buffer), - }, - a, - ); - const _chunks = lazy$4.value(() => { - return bscript$m.decompile(a.input); - }); - const network = a.network || networks_1$5.bitcoin; - const o = { name: 'p2pk', network }; - lazy$4.prop(o, 'output', () => { - if (!a.pubkey) return; - return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); - }); - lazy$4.prop(o, 'pubkey', () => { - if (!a.output) return; - return a.output.slice(1, -1); - }); - lazy$4.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$4.prop(o, 'input', () => { - if (!a.signature) return; - return bscript$m.compile([a.signature]); - }); - lazy$4.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - if (a.output) { - if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) - throw new TypeError('Output is invalid'); - if (!ecc$4.isPoint(o.pubkey)) - throw new TypeError('Output pubkey is invalid'); - if (a.pubkey && !a.pubkey.equals(o.pubkey)) - throw new TypeError('Pubkey mismatch'); - } - if (a.signature) { - if (a.input && !a.input.equals(o.input)) - throw new TypeError('Signature mismatch'); - } - if (a.input) { - if (_chunks().length !== 1) throw new TypeError('Input is invalid'); - if (!bscript$m.isCanonicalScriptSignature(o.signature)) - throw new TypeError('Input has invalid signature'); - } - } - return Object.assign(o, a); - } - p2pk$3.p2pk = p2pk$2; - - var p2pkh$3 = {}; - - var crypto$2 = {}; - - Object.defineProperty(crypto$2, '__esModule', { value: true }); - const createHash = browser$3; - function ripemd160$1(buffer) { - try { - return createHash('rmd160') - .update(buffer) - .digest(); - } catch (err) { - return createHash('ripemd160') - .update(buffer) - .digest(); - } - } - crypto$2.ripemd160 = ripemd160$1; - function sha1(buffer) { - return createHash('sha1') - .update(buffer) - .digest(); - } - crypto$2.sha1 = sha1; - function sha256$1(buffer) { - return createHash('sha256') - .update(buffer) - .digest(); - } - crypto$2.sha256 = sha256$1; - function hash160$1(buffer) { - return ripemd160$1(sha256$1(buffer)); - } - crypto$2.hash160 = hash160$1; - function hash256$1(buffer) { - return sha256$1(sha256$1(buffer)); - } - crypto$2.hash256 = hash256$1; - - Object.defineProperty(p2pkh$3, '__esModule', { value: true }); - const bcrypto$6 = crypto$2; - const networks_1$4 = networks$3; - const bscript$l = script$1; - const lazy$3 = lazy$7; - const typef$3 = typeforce_1; - const OPS$4 = bscript$l.OPS; - const ecc$3 = js; - const bs58check$2 = bs58check$5; - // input: {signature} {pubkey} - // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG - function p2pkh$2(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$3( - { - network: typef$3.maybe(typef$3.Object), - address: typef$3.maybe(typef$3.String), - hash: typef$3.maybe(typef$3.BufferN(20)), - output: typef$3.maybe(typef$3.BufferN(25)), - pubkey: typef$3.maybe(ecc$3.isPoint), - signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), - input: typef$3.maybe(typef$3.Buffer), - }, - a, - ); - const _address = lazy$3.value(() => { - const payload = bs58check$2.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$3.value(() => { - return bscript$l.decompile(a.input); - }); - const network = a.network || networks_1$4.bitcoin; - const o = { name: 'p2pkh', network }; - lazy$3.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(network.pubKeyHash, 0); - o.hash.copy(payload, 1); - return bs58check$2.encode(payload); - }); - lazy$3.prop(o, 'hash', () => { - if (a.output) return a.output.slice(3, 23); - if (a.address) return _address().hash; - if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); - }); - lazy$3.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$l.compile([ - OPS$4.OP_DUP, - OPS$4.OP_HASH160, - o.hash, - OPS$4.OP_EQUALVERIFY, - OPS$4.OP_CHECKSIG, - ]); - }); - lazy$3.prop(o, 'pubkey', () => { - if (!a.input) return; - return _chunks()[1]; - }); - lazy$3.prop(o, 'signature', () => { - if (!a.input) return; - return _chunks()[0]; - }); - lazy$3.prop(o, 'input', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return bscript$l.compile([a.signature, a.pubkey]); - }); - lazy$3.prop(o, 'witness', () => { - if (!o.input) return; - return []; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.pubKeyHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 25 || - a.output[0] !== OPS$4.OP_DUP || - a.output[1] !== OPS$4.OP_HASH160 || - a.output[2] !== 0x14 || - a.output[23] !== OPS$4.OP_EQUALVERIFY || - a.output[24] !== OPS$4.OP_CHECKSIG - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(3, 23); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.pubkey) { - const pkh = bcrypto$6.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - } - if (a.input) { - const chunks = _chunks(); - if (chunks.length !== 2) throw new TypeError('Input is invalid'); - if (!bscript$l.isCanonicalScriptSignature(chunks[0])) - throw new TypeError('Input has invalid signature'); - if (!ecc$3.isPoint(chunks[1])) - throw new TypeError('Input has invalid pubkey'); - if (a.signature && !a.signature.equals(chunks[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(chunks[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$6.hash160(chunks[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2pkh$3.p2pkh = p2pkh$2; - - var p2sh$1 = {}; - - Object.defineProperty(p2sh$1, '__esModule', { value: true }); - const bcrypto$5 = crypto$2; - const networks_1$3 = networks$3; - const bscript$k = script$1; - const lazy$2 = lazy$7; - const typef$2 = typeforce_1; - const OPS$3 = bscript$k.OPS; - const bs58check$1 = bs58check$5; - function stacksEqual$1(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - // input: [redeemScriptSig ...] {redeemScript} - // witness: - // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL - function p2sh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$2( - { - network: typef$2.maybe(typef$2.Object), - address: typef$2.maybe(typef$2.String), - hash: typef$2.maybe(typef$2.BufferN(20)), - output: typef$2.maybe(typef$2.BufferN(23)), - redeem: typef$2.maybe({ - network: typef$2.maybe(typef$2.Object), - output: typef$2.maybe(typef$2.Buffer), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }), - input: typef$2.maybe(typef$2.Buffer), - witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), - }, - a, - ); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; - } - const o = { network }; - const _address = lazy$2.value(() => { - const payload = bs58check$1.decode(a.address); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - }); - const _chunks = lazy$2.value(() => { - return bscript$k.decompile(a.input); - }); - const _redeem = lazy$2.value(() => { - const chunks = _chunks(); - return { - network, - output: chunks[chunks.length - 1], - input: bscript$k.compile(chunks.slice(0, -1)), - witness: a.witness || [], - }; - }); - // output dependents - lazy$2.prop(o, 'address', () => { - if (!o.hash) return; - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(o.network.scriptHash, 0); - o.hash.copy(payload, 1); - return bs58check$1.encode(payload); - }); - lazy$2.prop(o, 'hash', () => { - // in order of least effort - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().hash; - if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); - }); - lazy$2.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); - }); - // input dependents - lazy$2.prop(o, 'redeem', () => { - if (!a.input) return; - return _redeem(); - }); - lazy$2.prop(o, 'input', () => { - if (!a.redeem || !a.redeem.input || !a.redeem.output) return; - return bscript$k.compile( - [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), - ); - }); - lazy$2.prop(o, 'witness', () => { - if (o.redeem && o.redeem.witness) return o.redeem.witness; - if (o.input) return []; - }); - lazy$2.prop(o, 'name', () => { - const nameParts = ['p2sh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().version !== network.scriptHash) - throw new TypeError('Invalid version or Network mismatch'); - if (_address().hash.length !== 20) throw new TypeError('Invalid address'); - hash = _address().hash; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 23 || - a.output[0] !== OPS$3.OP_HASH160 || - a.output[1] !== 0x14 || - a.output[22] !== OPS$3.OP_EQUAL - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2, 22); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - // inlined to prevent 'no-inner-declarations' failing - const checkRedeem = redeem => { - // is the redeem output empty/invalid? - if (redeem.output) { - const decompile = bscript$k.decompile(redeem.output); - if (!decompile || decompile.length < 1) - throw new TypeError('Redeem.output too short'); - // match hash against other sources - const hash2 = bcrypto$5.hash160(redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (redeem.input) { - const hasInput = redeem.input.length > 0; - const hasWitness = redeem.witness && redeem.witness.length > 0; - if (!hasInput && !hasWitness) throw new TypeError('Empty input'); - if (hasInput && hasWitness) - throw new TypeError('Input and witness provided'); - if (hasInput) { - const richunks = bscript$k.decompile(redeem.input); - if (!bscript$k.isPushOnly(richunks)) - throw new TypeError('Non push-only scriptSig'); - } - } - }; - if (a.input) { - const chunks = _chunks(); - if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) - throw new TypeError('Input is invalid'); - checkRedeem(_redeem()); - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - if (a.input) { - const redeem = _redeem(); - if (a.redeem.output && !a.redeem.output.equals(redeem.output)) - throw new TypeError('Redeem.output mismatch'); - if (a.redeem.input && !a.redeem.input.equals(redeem.input)) - throw new TypeError('Redeem.input mismatch'); - } - checkRedeem(a.redeem); - } - if (a.witness) { - if ( - a.redeem && - a.redeem.witness && - !stacksEqual$1(a.redeem.witness, a.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - } - } - return Object.assign(o, a); - } - p2sh$1.p2sh = p2sh; - - var p2wpkh$1 = {}; - - var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; - - // pre-compute lookup table - var ALPHABET_MAP = {}; - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z); - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z; - } - - function polymodStep (pre) { - var b = pre >> 25; - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) - } - - function prefixChk (prefix) { - var chk = 1; - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' - - chk = polymodStep(chk) ^ (c >> 5); - } - chk = polymodStep(chk); - - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ (v & 0x1f); - } - return chk - } - - function encode$c (prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - - prefix = prefix.toLowerCase(); - - // determine chk mod - var chk = prefixChk(prefix); - if (typeof chk === 'string') throw new Error(chk) - - var result = prefix + '1'; - for (var i = 0; i < words.length; ++i) { - var x = words[i]; - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') - - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } - - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk); - } - chk ^= 1; - - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f; - result += ALPHABET.charAt(v); - } - - return result - } - - function __decode (str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + ' too short' - if (str.length > LIMIT) return 'Exceeds length limit' - - // don't allow mixed case - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str - str = lowered; - - var split = str.lastIndexOf('1'); - if (split === -1) return 'No separator character for ' + str - if (split === 0) return 'Missing prefix for ' + str - - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return 'Data too short' - - var chk = prefixChk(prefix); - if (typeof chk === 'string') return chk - - var words = []; - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === undefined) return 'Unknown character ' + c - chk = polymodStep(chk) ^ v; - - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v); - } - - if (chk !== 1) return 'Invalid checksum for ' + str - return { prefix: prefix, words: words } - } - - function decodeUnsafe () { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - } - - function decode$b (str) { - var res = __decode.apply(null, arguments); - if (typeof res === 'object') return res - - throw new Error(res) - } - - function convert$2 (data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - - var result = []; - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i]; - bits += inBits; - - while (bits >= outBits) { - bits -= outBits; - result.push((value >> bits) & maxV); - } - } - - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV); - } - } else { - if (bits >= inBits) return 'Excess padding' - if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' - } - - return result - } - - function toWordsUnsafe (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - } - - function toWords (bytes) { - var res = convert$2(bytes, 8, 5, true); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - function fromWordsUnsafe (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - } - - function fromWords (words) { - var res = convert$2(words, 5, 8, false); - if (Array.isArray(res)) return res - - throw new Error(res) - } - - var bech32$3 = { - decodeUnsafe: decodeUnsafe, - decode: decode$b, - encode: encode$c, - toWordsUnsafe: toWordsUnsafe, - toWords: toWords, - fromWordsUnsafe: fromWordsUnsafe, - fromWords: fromWords - }; - - Object.defineProperty(p2wpkh$1, '__esModule', { value: true }); - const bcrypto$4 = crypto$2; - const networks_1$2 = networks$3; - const bscript$j = script$1; - const lazy$1 = lazy$7; - const typef$1 = typeforce_1; - const OPS$2 = bscript$j.OPS; - const ecc$2 = js; - const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$m.alloc(0); - // witness: {signature} {pubKey} - // input: <> - // output: OP_0 {pubKeyHash} - function p2wpkh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef$1( - { - address: typef$1.maybe(typef$1.String), - hash: typef$1.maybe(typef$1.BufferN(20)), - input: typef$1.maybe(typef$1.BufferN(0)), - network: typef$1.maybe(typef$1.Object), - output: typef$1.maybe(typef$1.BufferN(22)), - pubkey: typef$1.maybe(ecc$2.isPoint), - signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), - witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), - }, - a, - ); - const _address = lazy$1.value(() => { - const result = bech32$2.decode(a.address); - const version = result.words.shift(); - const data = bech32$2.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const network = a.network || networks_1$2.bitcoin; - const o = { name: 'p2wpkh', network }; - lazy$1.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$2.toWords(o.hash); - words.unshift(0x00); - return bech32$2.encode(network.bech32, words); - }); - lazy$1.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2, 22); - if (a.address) return _address().data; - if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); - }); - lazy$1.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$j.compile([OPS$2.OP_0, o.hash]); - }); - lazy$1.prop(o, 'pubkey', () => { - if (a.pubkey) return a.pubkey; - if (!a.witness) return; - return a.witness[1]; - }); - lazy$1.prop(o, 'signature', () => { - if (!a.witness) return; - return a.witness[0]; - }); - lazy$1.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER$1; - }); - lazy$1.prop(o, 'witness', () => { - if (!a.pubkey) return; - if (!a.signature) return; - return [a.signature, a.pubkey]; - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (network && network.bech32 !== _address().prefix) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 20) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 22 || - a.output[0] !== OPS$2.OP_0 || - a.output[1] !== 0x14 - ) - throw new TypeError('Output is invalid'); - if (hash.length > 0 && !hash.equals(a.output.slice(2))) - throw new TypeError('Hash mismatch'); - else hash = a.output.slice(2); - } - if (a.pubkey) { - const pkh = bcrypto$4.hash160(a.pubkey); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - else hash = pkh; - if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) - throw new TypeError('Invalid pubkey for p2wpkh'); - } - if (a.witness) { - if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); - if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) - throw new TypeError('Witness has invalid signature'); - if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) - throw new TypeError('Witness has invalid pubkey'); - if (a.signature && !a.signature.equals(a.witness[0])) - throw new TypeError('Signature mismatch'); - if (a.pubkey && !a.pubkey.equals(a.witness[1])) - throw new TypeError('Pubkey mismatch'); - const pkh = bcrypto$4.hash160(a.witness[1]); - if (hash.length > 0 && !hash.equals(pkh)) - throw new TypeError('Hash mismatch'); - } - } - return Object.assign(o, a); - } - p2wpkh$1.p2wpkh = p2wpkh; - - var p2wsh$1 = {}; - - Object.defineProperty(p2wsh$1, '__esModule', { value: true }); - const bcrypto$3 = crypto$2; - const networks_1$1 = networks$3; - const bscript$i = script$1; - const lazy = lazy$7; - const typef = typeforce_1; - const OPS$1 = bscript$i.OPS; - const ecc$1 = js; - const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$m.alloc(0); - function stacksEqual(a, b) { - if (a.length !== b.length) return false; - return a.every((x, i) => { - return x.equals(b[i]); - }); - } - function chunkHasUncompressedPubkey(chunk) { - if ( - isBuffer(chunk) && - chunk.length === 65 && - chunk[0] === 0x04 && - ecc$1.isPoint(chunk) - ) { - return true; - } else { - return false; - } - } - // input: <> - // witness: [redeemScriptSig ...] {redeemScript} - // output: OP_0 {sha256(redeemScript)} - function p2wsh(a, opts) { - if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) - throw new TypeError('Not enough data'); - opts = Object.assign({ validate: true }, opts || {}); - typef( - { - network: typef.maybe(typef.Object), - address: typef.maybe(typef.String), - hash: typef.maybe(typef.BufferN(32)), - output: typef.maybe(typef.BufferN(34)), - redeem: typef.maybe({ - input: typef.maybe(typef.Buffer), - network: typef.maybe(typef.Object), - output: typef.maybe(typef.Buffer), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }), - input: typef.maybe(typef.BufferN(0)), - witness: typef.maybe(typef.arrayOf(typef.Buffer)), - }, - a, - ); - const _address = lazy.value(() => { - const result = bech32$1.decode(a.address); - const version = result.words.shift(); - const data = bech32$1.fromWords(result.words); - return { - version, - prefix: result.prefix, - data: Buffer$m.from(data), - }; - }); - const _rchunks = lazy.value(() => { - return bscript$i.decompile(a.redeem.input); - }); - let network = a.network; - if (!network) { - network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; - } - const o = { network }; - lazy.prop(o, 'address', () => { - if (!o.hash) return; - const words = bech32$1.toWords(o.hash); - words.unshift(0x00); - return bech32$1.encode(network.bech32, words); - }); - lazy.prop(o, 'hash', () => { - if (a.output) return a.output.slice(2); - if (a.address) return _address().data; - if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); - }); - lazy.prop(o, 'output', () => { - if (!o.hash) return; - return bscript$i.compile([OPS$1.OP_0, o.hash]); - }); - lazy.prop(o, 'redeem', () => { - if (!a.witness) return; - return { - output: a.witness[a.witness.length - 1], - input: EMPTY_BUFFER, - witness: a.witness.slice(0, -1), - }; - }); - lazy.prop(o, 'input', () => { - if (!o.witness) return; - return EMPTY_BUFFER; - }); - lazy.prop(o, 'witness', () => { - // transform redeem input to witness stack? - if ( - a.redeem && - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.output && - a.redeem.output.length > 0 - ) { - const stack = bscript$i.toStack(_rchunks()); - // assign, and blank the existing input - o.redeem = Object.assign({ witness: stack }, a.redeem); - o.redeem.input = EMPTY_BUFFER; - return [].concat(stack, a.redeem.output); - } - if (!a.redeem) return; - if (!a.redeem.output) return; - if (!a.redeem.witness) return; - return [].concat(a.redeem.witness, a.redeem.output); - }); - lazy.prop(o, 'name', () => { - const nameParts = ['p2wsh']; - if (o.redeem !== undefined) nameParts.push(o.redeem.name); - return nameParts.join('-'); - }); - // extended validation - if (opts.validate) { - let hash = Buffer$m.from([]); - if (a.address) { - if (_address().prefix !== network.bech32) - throw new TypeError('Invalid prefix or Network mismatch'); - if (_address().version !== 0x00) - throw new TypeError('Invalid address version'); - if (_address().data.length !== 32) - throw new TypeError('Invalid address data'); - hash = _address().data; - } - if (a.hash) { - if (hash.length > 0 && !hash.equals(a.hash)) - throw new TypeError('Hash mismatch'); - else hash = a.hash; - } - if (a.output) { - if ( - a.output.length !== 34 || - a.output[0] !== OPS$1.OP_0 || - a.output[1] !== 0x20 - ) - throw new TypeError('Output is invalid'); - const hash2 = a.output.slice(2); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem) { - if (a.redeem.network && a.redeem.network !== network) - throw new TypeError('Network mismatch'); - // is there two redeem sources? - if ( - a.redeem.input && - a.redeem.input.length > 0 && - a.redeem.witness && - a.redeem.witness.length > 0 - ) - throw new TypeError('Ambiguous witness source'); - // is the redeem output non-empty? - if (a.redeem.output) { - if (bscript$i.decompile(a.redeem.output).length === 0) - throw new TypeError('Redeem.output is invalid'); - // match hash against other sources - const hash2 = bcrypto$3.sha256(a.redeem.output); - if (hash.length > 0 && !hash.equals(hash2)) - throw new TypeError('Hash mismatch'); - else hash = hash2; - } - if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) - throw new TypeError('Non push-only scriptSig'); - if ( - a.witness && - a.redeem.witness && - !stacksEqual(a.witness, a.redeem.witness) - ) - throw new TypeError('Witness and redeem.witness mismatch'); - if ( - (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || - (a.redeem.output && - (bscript$i.decompile(a.redeem.output) || []).some( - chunkHasUncompressedPubkey, - )) - ) { - throw new TypeError( - 'redeem.input or redeem.output contains uncompressed pubkey', - ); - } - } - if (a.witness && a.witness.length > 0) { - const wScript = a.witness[a.witness.length - 1]; - if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) - throw new TypeError('Witness and redeem.output mismatch'); - if ( - a.witness.some(chunkHasUncompressedPubkey) || - (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) - ) - throw new TypeError('Witness contains uncompressed pubkey'); - } - } - return Object.assign(o, a); - } - p2wsh$1.p2wsh = p2wsh; - - Object.defineProperty(payments$4, '__esModule', { value: true }); - const embed_1 = embed; - payments$4.embed = embed_1.p2data; - const p2ms_1 = p2ms$3; - payments$4.p2ms = p2ms_1.p2ms; - const p2pk_1 = p2pk$3; - payments$4.p2pk = p2pk_1.p2pk; - const p2pkh_1 = p2pkh$3; - payments$4.p2pkh = p2pkh_1.p2pkh; - const p2sh_1 = p2sh$1; - payments$4.p2sh = p2sh_1.p2sh; - const p2wpkh_1 = p2wpkh$1; - payments$4.p2wpkh = p2wpkh_1.p2wpkh; - const p2wsh_1 = p2wsh$1; - payments$4.p2wsh = p2wsh_1.p2wsh; - - Object.defineProperty(address$1, '__esModule', { value: true }); - const networks$2 = networks$3; - const payments$3 = payments$4; - const bscript$h = script$1; - const types$8 = types$a; - const bech32 = bech32$3; - const bs58check = bs58check$5; - const typeforce$7 = typeforce_1; - function fromBase58Check(address) { - const payload = bs58check.decode(address); - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short'); - if (payload.length > 21) throw new TypeError(address + ' is too long'); - const version = payload.readUInt8(0); - const hash = payload.slice(1); - return { version, hash }; - } - address$1.fromBase58Check = fromBase58Check; - function fromBech32(address) { - const result = bech32.decode(address); - const data = bech32.fromWords(result.words.slice(1)); - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer$m.from(data), - }; - } - address$1.fromBech32 = fromBech32; - function toBase58Check(hash, version) { - typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$m.allocUnsafe(21); - payload.writeUInt8(version, 0); - hash.copy(payload, 1); - return bs58check.encode(payload); - } - address$1.toBase58Check = toBase58Check; - function toBech32(data, version, prefix) { - const words = bech32.toWords(data); - words.unshift(version); - return bech32.encode(prefix, words); - } - address$1.toBech32 = toBech32; - function fromOutputScript(output, network) { - // TODO: Network - network = network || networks$2.bitcoin; - try { - return payments$3.p2pkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2sh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wpkh({ output, network }).address; - } catch (e) {} - try { - return payments$3.p2wsh({ output, network }).address; - } catch (e) {} - throw new Error(bscript$h.toASM(output) + ' has no matching Address'); - } - address$1.fromOutputScript = fromOutputScript; - function toOutputScript(address, network) { - network = network || networks$2.bitcoin; - let decodeBase58; - let decodeBech32; - try { - decodeBase58 = fromBase58Check(address); - } catch (e) {} - if (decodeBase58) { - if (decodeBase58.version === network.pubKeyHash) - return payments$3.p2pkh({ hash: decodeBase58.hash }).output; - if (decodeBase58.version === network.scriptHash) - return payments$3.p2sh({ hash: decodeBase58.hash }).output; - } else { - try { - decodeBech32 = fromBech32(address); - } catch (e) {} - if (decodeBech32) { - if (decodeBech32.prefix !== network.bech32) - throw new Error(address + ' has an invalid prefix'); - if (decodeBech32.version === 0) { - if (decodeBech32.data.length === 20) - return payments$3.p2wpkh({ hash: decodeBech32.data }).output; - if (decodeBech32.data.length === 32) - return payments$3.p2wsh({ hash: decodeBech32.data }).output; - } - } - } - throw new Error(address + ' has no matching Script'); - } - address$1.toOutputScript = toOutputScript; - - var ecpair = {}; - - var browser$1 = {exports: {}}; - - // limit of Crypto.getRandomValues() - // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues - var MAX_BYTES = 65536; - - // Node supports requesting up to this number of bytes - // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 - var MAX_UINT32 = 4294967295; - - function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') - } - - var Buffer$1 = safeBuffer.exports.Buffer; - var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; - - if (crypto$1 && crypto$1.getRandomValues) { - browser$1.exports = randomBytes$1; - } else { - browser$1.exports = oldBrowser; - } - - function randomBytes$1 (size, cb) { - // phantomjs needs to throw - if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') - - var bytes = Buffer$1.allocUnsafe(size); - - if (size > 0) { // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues - // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - for (var generated = 0; generated < size; generated += MAX_BYTES) { - // buffer.slice automatically checks if the end is past the end of - // the buffer so we don't have to here - crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); - } - } else { - crypto$1.getRandomValues(bytes); - } - } - - if (typeof cb === 'function') { - return nextTick(function () { - cb(null, bytes); - }) - } - - return bytes - } - - Object.defineProperty(ecpair, '__esModule', { value: true }); - const NETWORKS = networks$3; - const types$7 = types$a; - const ecc = js; - const randomBytes = browser$1.exports; - const typeforce$6 = typeforce_1; - const wif = wif$2; - const isOptions = typeforce$6.maybe( - typeforce$6.compile({ - compressed: types$7.maybe(types$7.Boolean), - network: types$7.maybe(types$7.Network), - }), - ); - class ECPair$2 { - constructor(__D, __Q, options) { - this.__D = __D; - this.__Q = __Q; - this.lowR = false; - if (options === undefined) options = {}; - this.compressed = - options.compressed === undefined ? true : options.compressed; - this.network = options.network || NETWORKS.bitcoin; - if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); - } - get privateKey() { - return this.__D; - } - get publicKey() { - if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); - return this.__Q; - } - toWIF() { - if (!this.__D) throw new Error('Missing private key'); - return wif.encode(this.network.wif, this.__D, this.compressed); - } - sign(hash, lowR) { - if (!this.__D) throw new Error('Missing private key'); - if (lowR === undefined) lowR = this.lowR; - if (lowR === false) { - return ecc.sign(hash, this.__D); - } else { - let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$m.alloc(32, 0); - let counter = 0; - // if first try is lowR, skip the loop - // for second try and on, add extra entropy counting up - while (sig[0] > 0x7f) { - counter++; - extraData.writeUIntLE(counter, 0, 6); - sig = ecc.signWithEntropy(hash, this.__D, extraData); - } - return sig; - } - } - verify(hash, signature) { - return ecc.verify(hash, this.publicKey, signature); - } - } - function fromPrivateKey(buffer, options) { - typeforce$6(types$7.Buffer256bit, buffer); - if (!ecc.isPrivate(buffer)) - throw new TypeError('Private key not in range [1, n)'); - typeforce$6(isOptions, options); - return new ECPair$2(buffer, undefined, options); - } - ecpair.fromPrivateKey = fromPrivateKey; - function fromPublicKey(buffer, options) { - typeforce$6(ecc.isPoint, buffer); - typeforce$6(isOptions, options); - return new ECPair$2(undefined, buffer, options); - } - ecpair.fromPublicKey = fromPublicKey; - function fromWIF(wifString, network) { - const decoded = wif.decode(wifString); - const version = decoded.version; - // list of networks? - if (types$7.Array(network)) { - network = network - .filter(x => { - return version === x.wif; - }) - .pop(); - if (!network) throw new Error('Unknown network version'); - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin; - if (version !== network.wif) throw new Error('Invalid network version'); - } - return fromPrivateKey(decoded.privateKey, { - compressed: decoded.compressed, - network: network, - }); - } - ecpair.fromWIF = fromWIF; - function makeRandom(options) { - typeforce$6(isOptions, options); - if (options === undefined) options = {}; - const rng = options.rng || randomBytes; - let d; - do { - d = rng(32); - typeforce$6(types$7.Buffer256bit, d); - } while (!ecc.isPrivate(d)); - return fromPrivateKey(d, options); - } - ecpair.makeRandom = makeRandom; - - var block = {}; - - var bufferutils = {}; - - var Buffer = safeBuffer.exports.Buffer; - - // Number.MAX_SAFE_INTEGER - var MAX_SAFE_INTEGER$5 = 9007199254740991; - - function checkUInt53$1 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER$5 || n % 1 !== 0) throw new RangeError('value out of range') - } - - function encode$b (number, buffer, offset) { - checkUInt53$1(number); - - if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset); - encode$b.bytes = 1; - - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; - - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; - - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(number >>> 0, offset + 1); - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; - } - - return buffer - } - - function decode$a (buffer, offset) { - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0; - - var first = buffer.readUInt8(offset); - - // 8 bit - if (first < 0xfd) { - decode$a.bytes = 1; - return first - - // 16 bit - } else if (first === 0xfd) { - decode$a.bytes = 3; - return buffer.readUInt16LE(offset + 1) - - // 32 bit - } else if (first === 0xfe) { - decode$a.bytes = 5; - return buffer.readUInt32LE(offset + 1) - - // 64 bit - } else { - decode$a.bytes = 9; - var lo = buffer.readUInt32LE(offset + 1); - var hi = buffer.readUInt32LE(offset + 5); - var number = hi * 0x0100000000 + lo; - checkUInt53$1(number); - - return number - } - } - - function encodingLength$1 (number) { - checkUInt53$1(number); - - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) - } - - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; - - Object.defineProperty(bufferutils, '__esModule', { value: true }); - const types$6 = types$a; - const typeforce$5 = typeforce_1; - const varuint$6 = varuintBitcoin; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint$1(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE$1(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint$1(b + a, 0x001fffffffffffff); - return b + a; - } - bufferutils.readUInt64LE = readUInt64LE$1; - function writeUInt64LE$1(buffer, value, offset) { - verifuint$1(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - bufferutils.writeUInt64LE = writeUInt64LE$1; - function reverseBuffer$1(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - bufferutils.reverseBuffer = reverseBuffer$1; - function cloneBuffer(buffer) { - const clone = Buffer$m.allocUnsafe(buffer.length); - buffer.copy(clone); - return clone; - } - bufferutils.cloneBuffer = cloneBuffer; - /** - * Helper class for serialization of bitcoin data types into a pre-allocated buffer. - */ - class BufferWriter$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - writeUInt8(i) { - this.offset = this.buffer.writeUInt8(i, this.offset); - } - writeInt32(i) { - this.offset = this.buffer.writeInt32LE(i, this.offset); - } - writeUInt32(i) { - this.offset = this.buffer.writeUInt32LE(i, this.offset); - } - writeUInt64(i) { - this.offset = writeUInt64LE$1(this.buffer, i, this.offset); - } - writeVarInt(i) { - varuint$6.encode(i, this.buffer, this.offset); - this.offset += varuint$6.encode.bytes; - } - writeSlice(slice) { - if (this.buffer.length < this.offset + slice.length) { - throw new Error('Cannot write slice out of bounds'); - } - this.offset += slice.copy(this.buffer, this.offset); - } - writeVarSlice(slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - } - writeVector(vector) { - this.writeVarInt(vector.length); - vector.forEach(buf => this.writeVarSlice(buf)); - } - } - bufferutils.BufferWriter = BufferWriter$1; - /** - * Helper class for reading of bitcoin data types from a buffer. - */ - class BufferReader$1 { - constructor(buffer, offset = 0) { - this.buffer = buffer; - this.offset = offset; - typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); - } - readUInt8() { - const result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - } - readInt32() { - const result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt32() { - const result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - } - readUInt64() { - const result = readUInt64LE$1(this.buffer, this.offset); - this.offset += 8; - return result; - } - readVarInt() { - const vi = varuint$6.decode(this.buffer, this.offset); - this.offset += varuint$6.decode.bytes; - return vi; - } - readSlice(n) { - if (this.buffer.length < this.offset + n) { - throw new Error('Cannot read slice out of bounds'); - } - const result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - } - readVarSlice() { - return this.readSlice(this.readVarInt()); - } - readVector() { - const count = this.readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); - return vector; - } - } - bufferutils.BufferReader = BufferReader$1; - - var transaction = {}; - - Object.defineProperty(transaction, '__esModule', { value: true }); - const bufferutils_1$3 = bufferutils; - const bcrypto$2 = crypto$2; - const bscript$g = script$1; - const script_1$b = script$1; - const types$5 = types$a; - const typeforce$4 = typeforce_1; - const varuint$5 = varuintBitcoin; - function varSliceSize(someScript) { - const length = someScript.length; - return varuint$5.encodingLength(length) + length; - } - function vectorSize(someVector) { - const length = someVector.length; - return ( - varuint$5.encodingLength(length) + - someVector.reduce((sum, witness) => { - return sum + varSliceSize(witness); - }, 0) - ); - } - const EMPTY_SCRIPT = Buffer$m.allocUnsafe(0); - const EMPTY_WITNESS = []; - const ZERO = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000000', - 'hex', - ); - const ONE = Buffer$m.from( - '0000000000000000000000000000000000000000000000000000000000000001', - 'hex', - ); - const VALUE_UINT64_MAX = Buffer$m.from('ffffffffffffffff', 'hex'); - const BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX, - }; - function isOutput(out) { - return out.value !== undefined; - } - class Transaction { - constructor() { - this.version = 1; - this.locktime = 0; - this.ins = []; - this.outs = []; - } - static fromBuffer(buffer, _NO_STRICT) { - const bufferReader = new bufferutils_1$3.BufferReader(buffer); - const tx = new Transaction(); - tx.version = bufferReader.readInt32(); - const marker = bufferReader.readUInt8(); - const flag = bufferReader.readUInt8(); - let hasWitnesses = false; - if ( - marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG - ) { - hasWitnesses = true; - } else { - bufferReader.offset -= 2; - } - const vinLen = bufferReader.readVarInt(); - for (let i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: bufferReader.readSlice(32), - index: bufferReader.readUInt32(), - script: bufferReader.readVarSlice(), - sequence: bufferReader.readUInt32(), - witness: EMPTY_WITNESS, - }); - } - const voutLen = bufferReader.readVarInt(); - for (let i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: bufferReader.readUInt64(), - script: bufferReader.readVarSlice(), - }); - } - if (hasWitnesses) { - for (let i = 0; i < vinLen; ++i) { - tx.ins[i].witness = bufferReader.readVector(); - } - // was this pointless? - if (!tx.hasWitnesses()) - throw new Error('Transaction has superfluous witness data'); - } - tx.locktime = bufferReader.readUInt32(); - if (_NO_STRICT) return tx; - if (bufferReader.offset !== buffer.length) - throw new Error('Transaction has unexpected data'); - return tx; - } - static fromHex(hex) { - return Transaction.fromBuffer(Buffer$m.from(hex, 'hex'), false); - } - static isCoinbaseHash(buffer) { - typeforce$4(types$5.Hash256bit, buffer); - for (let i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false; - } - return true; - } - isCoinbase() { - return ( - this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) - ); - } - addInput(hash, index, sequence, scriptSig) { - typeforce$4( - types$5.tuple( - types$5.Hash256bit, - types$5.UInt32, - types$5.maybe(types$5.UInt32), - types$5.maybe(types$5.Buffer), - ), - arguments, - ); - if (types$5.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE; - } - // Add the input and return the input's index - return ( - this.ins.push({ - hash, - index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS, - }) - 1 - ); - } - addOutput(scriptPubKey, value) { - typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); - // Add the output and return the output's index - return ( - this.outs.push({ - script: scriptPubKey, - value, - }) - 1 - ); - } - hasWitnesses() { - return this.ins.some(x => { - return x.witness.length !== 0; - }); - } - weight() { - const base = this.byteLength(false); - const total = this.byteLength(true); - return base * 3 + total; - } - virtualSize() { - return Math.ceil(this.weight() / 4); - } - byteLength(_ALLOW_WITNESS = true) { - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - return ( - (hasWitnesses ? 10 : 8) + - varuint$5.encodingLength(this.ins.length) + - varuint$5.encodingLength(this.outs.length) + - this.ins.reduce((sum, input) => { - return sum + 40 + varSliceSize(input.script); - }, 0) + - this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0) + - (hasWitnesses - ? this.ins.reduce((sum, input) => { - return sum + vectorSize(input.witness); - }, 0) - : 0) - ); - } - clone() { - const newTx = new Transaction(); - newTx.version = this.version; - newTx.locktime = this.locktime; - newTx.ins = this.ins.map(txIn => { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness, - }; - }); - newTx.outs = this.outs.map(txOut => { - return { - script: txOut.script, - value: txOut.value, - }; - }); - return newTx; - } - /** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ - hashForSignature(inIndex, prevOutScript, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), - arguments, - ); - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE; - // ignore OP_CODESEPARATOR - const ourScript = bscript$g.compile( - bscript$g.decompile(prevOutScript).filter(x => { - return x !== script_1$b.OPS.OP_CODESEPARATOR; - }), - ); - const txTmp = this.clone(); - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = []; - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, i) => { - if (i === inIndex) return; - input.sequence = 0; - }); - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE; - // truncate outputs after - txTmp.outs.length = inIndex + 1; - // "blank" outputs before - for (let i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT; - } - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach((input, y) => { - if (y === inIndex) return; - input.sequence = 0; - }); - } - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]]; - txTmp.ins[0].script = ourScript; - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(input => { - input.script = EMPTY_SCRIPT; - }); - txTmp.ins[inIndex].script = ourScript; - } - // serialize and hash - const buffer = Buffer$m.allocUnsafe(txTmp.byteLength(false) + 4); - buffer.writeInt32LE(hashType, buffer.length - 4); - txTmp.__toBuffer(buffer, 0, false); - return bcrypto$2.hash256(buffer); - } - hashForWitnessV0(inIndex, prevOutScript, value, hashType) { - typeforce$4( - types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), - arguments, - ); - let tbuffer = Buffer$m.from([]); - let bufferWriter; - let hashOutputs = ZERO; - let hashPrevouts = ZERO; - let hashSequence = ZERO; - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$m.allocUnsafe(36 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - }); - hashPrevouts = bcrypto$2.hash256(tbuffer); - } - if ( - !(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - tbuffer = Buffer$m.allocUnsafe(4 * this.ins.length); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.ins.forEach(txIn => { - bufferWriter.writeUInt32(txIn.sequence); - }); - hashSequence = bcrypto$2.hash256(tbuffer); - } - if ( - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE - ) { - const txOutsSize = this.outs.reduce((sum, output) => { - return sum + 8 + varSliceSize(output.script); - }, 0); - tbuffer = Buffer$m.allocUnsafe(txOutsSize); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - this.outs.forEach(out => { - bufferWriter.writeUInt64(out.value); - bufferWriter.writeVarSlice(out.script); - }); - hashOutputs = bcrypto$2.hash256(tbuffer); - } else if ( - (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && - inIndex < this.outs.length - ) { - const output = this.outs[inIndex]; - tbuffer = Buffer$m.allocUnsafe(8 + varSliceSize(output.script)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - bufferWriter.writeUInt64(output.value); - bufferWriter.writeVarSlice(output.script); - hashOutputs = bcrypto$2.hash256(tbuffer); - } - tbuffer = Buffer$m.allocUnsafe(156 + varSliceSize(prevOutScript)); - bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); - const input = this.ins[inIndex]; - bufferWriter.writeUInt32(this.version); - bufferWriter.writeSlice(hashPrevouts); - bufferWriter.writeSlice(hashSequence); - bufferWriter.writeSlice(input.hash); - bufferWriter.writeUInt32(input.index); - bufferWriter.writeVarSlice(prevOutScript); - bufferWriter.writeUInt64(value); - bufferWriter.writeUInt32(input.sequence); - bufferWriter.writeSlice(hashOutputs); - bufferWriter.writeUInt32(this.locktime); - bufferWriter.writeUInt32(hashType); - return bcrypto$2.hash256(tbuffer); - } - getHash(forWitness) { - // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$m.alloc(32, 0); - return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); - } - getId() { - // transaction hash's are displayed in reverse order - return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); - } - toBuffer(buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true); - } - toHex() { - return this.toBuffer(undefined, undefined).toString('hex'); - } - setInputScript(index, scriptSig) { - typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); - this.ins[index].script = scriptSig; - } - setWitness(index, witness) { - typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); - this.ins[index].witness = witness; - } - __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$m.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); - const bufferWriter = new bufferutils_1$3.BufferWriter( - buffer, - initialOffset || 0, - ); - bufferWriter.writeInt32(this.version); - const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); - if (hasWitnesses) { - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); - bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); - } - bufferWriter.writeVarInt(this.ins.length); - this.ins.forEach(txIn => { - bufferWriter.writeSlice(txIn.hash); - bufferWriter.writeUInt32(txIn.index); - bufferWriter.writeVarSlice(txIn.script); - bufferWriter.writeUInt32(txIn.sequence); - }); - bufferWriter.writeVarInt(this.outs.length); - this.outs.forEach(txOut => { - if (isOutput(txOut)) { - bufferWriter.writeUInt64(txOut.value); - } else { - bufferWriter.writeSlice(txOut.valueBuffer); - } - bufferWriter.writeVarSlice(txOut.script); - }); - if (hasWitnesses) { - this.ins.forEach(input => { - bufferWriter.writeVector(input.witness); - }); - } - bufferWriter.writeUInt32(this.locktime); - // avoid slicing unless necessary - if (initialOffset !== undefined) - return buffer.slice(initialOffset, bufferWriter.offset); - return buffer; - } - } - Transaction.DEFAULT_SEQUENCE = 0xffffffff; - Transaction.SIGHASH_ALL = 0x01; - Transaction.SIGHASH_NONE = 0x02; - Transaction.SIGHASH_SINGLE = 0x03; - Transaction.SIGHASH_ANYONECANPAY = 0x80; - Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; - Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; - transaction.Transaction = Transaction; - - // constant-space merkle root calculation algorithm - var fastRoot = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') - - var length = values.length; - var results = values.concat(); - - while (length > 1) { - var j = 0; - - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i]; - var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$m.concat([left, right]); - - results[j] = digestFn(data); - } - - length = j; - } - - return results[0] - }; - - Object.defineProperty(block, '__esModule', { value: true }); - const bufferutils_1$2 = bufferutils; - const bcrypto$1 = crypto$2; - const transaction_1$3 = transaction; - const types$4 = types$a; - const fastMerkleRoot = fastRoot; - const typeforce$3 = typeforce_1; - const varuint$4 = varuintBitcoin; - const errorMerkleNoTxes = new TypeError( - 'Cannot compute merkle root for zero transactions', - ); - const errorWitnessNotSegwit = new TypeError( - 'Cannot compute witness commit for non-segwit block', - ); - class Block { - constructor() { - this.version = 1; - this.prevHash = undefined; - this.merkleRoot = undefined; - this.timestamp = 0; - this.witnessCommit = undefined; - this.bits = 0; - this.nonce = 0; - this.transactions = undefined; - } - static fromBuffer(buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); - const bufferReader = new bufferutils_1$2.BufferReader(buffer); - const block = new Block(); - block.version = bufferReader.readInt32(); - block.prevHash = bufferReader.readSlice(32); - block.merkleRoot = bufferReader.readSlice(32); - block.timestamp = bufferReader.readUInt32(); - block.bits = bufferReader.readUInt32(); - block.nonce = bufferReader.readUInt32(); - if (buffer.length === 80) return block; - const readTransaction = () => { - const tx = transaction_1$3.Transaction.fromBuffer( - bufferReader.buffer.slice(bufferReader.offset), - true, - ); - bufferReader.offset += tx.byteLength(); - return tx; - }; - const nTransactions = bufferReader.readVarInt(); - block.transactions = []; - for (let i = 0; i < nTransactions; ++i) { - const tx = readTransaction(); - block.transactions.push(tx); - } - const witnessCommit = block.getWitnessCommit(); - // This Block contains a witness commit - if (witnessCommit) block.witnessCommit = witnessCommit; - return block; - } - static fromHex(hex) { - return Block.fromBuffer(Buffer$m.from(hex, 'hex')); - } - static calculateTarget(bits) { - const exponent = ((bits & 0xff000000) >> 24) - 3; - const mantissa = bits & 0x007fffff; - const target = Buffer$m.alloc(32, 0); - target.writeUIntBE(mantissa, 29 - exponent, 3); - return target; - } - static calculateMerkleRoot(transactions, forWitness) { - typeforce$3([{ getHash: types$4.Function }], transactions); - if (transactions.length === 0) throw errorMerkleNoTxes; - if (forWitness && !txesHaveWitnessCommit(transactions)) - throw errorWitnessNotSegwit; - const hashes = transactions.map(transaction => - transaction.getHash(forWitness), - ); - const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); - return forWitness - ? bcrypto$1.hash256( - Buffer$m.concat([rootHash, transactions[0].ins[0].witness[0]]), - ) - : rootHash; - } - getWitnessCommit() { - if (!txesHaveWitnessCommit(this.transactions)) return null; - // The merkle root for the witness data is in an OP_RETURN output. - // There is no rule for the index of the output, so use filter to find it. - // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed - // If multiple commits are found, the output with highest index is assumed. - const witnessCommits = this.transactions[0].outs - .filter(out => - out.script.slice(0, 6).equals(Buffer$m.from('6a24aa21a9ed', 'hex')), - ) - .map(out => out.script.slice(6, 38)); - if (witnessCommits.length === 0) return null; - // Use the commit with the highest output (should only be one though) - const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$m && result.length === 32)) return null; - return result; - } - hasWitnessCommit() { - if ( - this.witnessCommit instanceof Buffer$m && - this.witnessCommit.length === 32 - ) - return true; - if (this.getWitnessCommit() !== null) return true; - return false; - } - hasWitness() { - return anyTxHasWitness(this.transactions); - } - weight() { - const base = this.byteLength(false, false); - const total = this.byteLength(false, true); - return base * 3 + total; - } - byteLength(headersOnly, allowWitness = true) { - if (headersOnly || !this.transactions) return 80; - return ( - 80 + - varuint$4.encodingLength(this.transactions.length) + - this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) - ); - } - getHash() { - return bcrypto$1.hash256(this.toBuffer(true)); - } - getId() { - return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); - } - getUTCDate() { - const date = new Date(0); // epoch - date.setUTCSeconds(this.timestamp); - return date; - } - // TODO: buffer, offset compatibility - toBuffer(headersOnly) { - const buffer = Buffer$m.allocUnsafe(this.byteLength(headersOnly)); - const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); - bufferWriter.writeInt32(this.version); - bufferWriter.writeSlice(this.prevHash); - bufferWriter.writeSlice(this.merkleRoot); - bufferWriter.writeUInt32(this.timestamp); - bufferWriter.writeUInt32(this.bits); - bufferWriter.writeUInt32(this.nonce); - if (headersOnly || !this.transactions) return buffer; - varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); - bufferWriter.offset += varuint$4.encode.bytes; - this.transactions.forEach(tx => { - const txSize = tx.byteLength(); // TODO: extract from toBuffer? - tx.toBuffer(buffer, bufferWriter.offset); - bufferWriter.offset += txSize; - }); - return buffer; - } - toHex(headersOnly) { - return this.toBuffer(headersOnly).toString('hex'); - } - checkTxRoots() { - // If the Block has segwit transactions but no witness commit, - // there's no way it can be valid, so fail the check. - const hasWitnessCommit = this.hasWitnessCommit(); - if (!hasWitnessCommit && this.hasWitness()) return false; - return ( - this.__checkMerkleRoot() && - (hasWitnessCommit ? this.__checkWitnessCommit() : true) - ); - } - checkProofOfWork() { - const hash = bufferutils_1$2.reverseBuffer(this.getHash()); - const target = Block.calculateTarget(this.bits); - return hash.compare(target) <= 0; - } - __checkMerkleRoot() { - if (!this.transactions) throw errorMerkleNoTxes; - const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); - return this.merkleRoot.compare(actualMerkleRoot) === 0; - } - __checkWitnessCommit() { - if (!this.transactions) throw errorMerkleNoTxes; - if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; - const actualWitnessCommit = Block.calculateMerkleRoot( - this.transactions, - true, - ); - return this.witnessCommit.compare(actualWitnessCommit) === 0; - } - } - block.Block = Block; - function txesHaveWitnessCommit(transactions) { - return ( - transactions instanceof Array && - transactions[0] && - transactions[0].ins && - transactions[0].ins instanceof Array && - transactions[0].ins[0] && - transactions[0].ins[0].witness && - transactions[0].ins[0].witness instanceof Array && - transactions[0].ins[0].witness.length > 0 - ); - } - function anyTxHasWitness(transactions) { - return ( - transactions instanceof Array && - transactions.some( - tx => - typeof tx === 'object' && - tx.ins instanceof Array && - tx.ins.some( - input => - typeof input === 'object' && - input.witness instanceof Array && - input.witness.length > 0, - ), - ) - ); - } - - var psbt$1 = {}; - - var psbt = {}; - - var combiner = {}; - - var parser = {}; - - var fromBuffer = {}; - - var converter = {}; - - var typeFields = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - (function(GlobalTypes) { - GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; - GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; - })((exports.GlobalTypes || (exports.GlobalTypes = {}))); - exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; - (function(InputTypes) { - InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; - InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; - InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; - InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; - InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; - InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; - InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; - InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; - InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; - InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; - })((exports.InputTypes || (exports.InputTypes = {}))); - exports.INPUT_TYPE_NAMES = [ - 'nonWitnessUtxo', - 'witnessUtxo', - 'partialSig', - 'sighashType', - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - 'finalScriptSig', - 'finalScriptWitness', - 'porCommitment', - ]; - (function(OutputTypes) { - OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; - OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; - OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; - })((exports.OutputTypes || (exports.OutputTypes = {}))); - exports.OUTPUT_TYPE_NAMES = [ - 'redeemScript', - 'witnessScript', - 'bip32Derivation', - ]; - }(typeFields)); - - var globalXpub$1 = {}; - - Object.defineProperty(globalXpub$1, '__esModule', { value: true }); - const typeFields_1$b = typeFields; - const range$4 = n => [...Array(n).keys()]; - function decode$9(keyVal) { - if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { - throw new Error( - 'Decode Error: could not decode globalXpub with key 0x' + - keyVal.key.toString('hex'), - ); - } - if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { - throw new Error( - 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', - ); - } - const extendedPubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - extendedPubkey, - path: 'm', - }; - for (const i of range$4(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - globalXpub$1.decode = decode$9; - function encode$a(data) { - const head = Buffer$m.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$m.concat([head, data.extendedPubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - globalXpub$1.encode = encode$a; - globalXpub$1.expected = - '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; - function check$l(data) { - const epk = data.extendedPubkey; - const mfp = data.masterFingerprint; - const p = data.path; - return ( - isBuffer(epk) && - epk.length === 78 && - [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && - mfp.length === 4 && - typeof p === 'string' && - !!p.match(/^m(\/\d+'?)+$/) - ); - } - globalXpub$1.check = check$l; - function canAddToArray$1(array, item, dupeSet) { - const dupeString = item.extendedPubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return ( - array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 - ); - } - globalXpub$1.canAddToArray = canAddToArray$1; - - var unsignedTx$1 = {}; - - Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); - const typeFields_1$a = typeFields; - function encode$9(data) { - return { - key: Buffer$m.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), - value: data.toBuffer(), - }; - } - unsignedTx$1.encode = encode$9; - - var finalScriptSig$1 = {}; - - Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); - const typeFields_1$9 = typeFields; - function decode$8(keyVal) { - if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { - throw new Error( - 'Decode Error: could not decode finalScriptSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptSig$1.decode = decode$8; - function encode$8(data) { - const key = Buffer$m.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); - return { - key, - value: data, - }; - } - finalScriptSig$1.encode = encode$8; - finalScriptSig$1.expected = 'Buffer'; - function check$k(data) { - return isBuffer(data); - } - finalScriptSig$1.check = check$k; - function canAdd$5(currentData, newData) { - return !!currentData && !!newData && currentData.finalScriptSig === undefined; - } - finalScriptSig$1.canAdd = canAdd$5; - - var finalScriptWitness$1 = {}; - - Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); - const typeFields_1$8 = typeFields; - function decode$7(keyVal) { - if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { - throw new Error( - 'Decode Error: could not decode finalScriptWitness with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - finalScriptWitness$1.decode = decode$7; - function encode$7(data) { - const key = Buffer$m.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); - return { - key, - value: data, - }; - } - finalScriptWitness$1.encode = encode$7; - finalScriptWitness$1.expected = 'Buffer'; - function check$j(data) { - return isBuffer(data); - } - finalScriptWitness$1.check = check$j; - function canAdd$4(currentData, newData) { - return ( - !!currentData && !!newData && currentData.finalScriptWitness === undefined - ); - } - finalScriptWitness$1.canAdd = canAdd$4; - - var nonWitnessUtxo$1 = {}; - - Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$7 = typeFields; - function decode$6(keyVal) { - if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode nonWitnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { - return { - key: Buffer$m.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), - value: data, - }; - } - nonWitnessUtxo$1.encode = encode$6; - nonWitnessUtxo$1.expected = 'Buffer'; - function check$i(data) { - return isBuffer(data); - } - nonWitnessUtxo$1.check = check$i; - function canAdd$3(currentData, newData) { - return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; - } - nonWitnessUtxo$1.canAdd = canAdd$3; - - var partialSig$1 = {}; - - Object.defineProperty(partialSig$1, '__esModule', { value: true }); - const typeFields_1$6 = typeFields; - function decode$5(keyVal) { - if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { - throw new Error( - 'Decode Error: could not decode partialSig with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: partialSig has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - const pubkey = keyVal.key.slice(1); - return { - pubkey, - signature: keyVal.value, - }; - } - partialSig$1.decode = decode$5; - function encode$5(pSig) { - const head = Buffer$m.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); - return { - key: Buffer$m.concat([head, pSig.pubkey]), - value: pSig.signature, - }; - } - partialSig$1.encode = encode$5; - partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; - function check$h(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - isDerSigWithSighash(data.signature) - ); - } - partialSig$1.check = check$h; - function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; - if (buf[0] !== 0x30) return false; - if (buf.length !== buf[1] + 3) return false; - if (buf[2] !== 0x02) return false; - const rLen = buf[3]; - if (rLen > 33 || rLen < 1) return false; - if (buf[3 + rLen + 1] !== 0x02) return false; - const sLen = buf[3 + rLen + 2]; - if (sLen > 33 || sLen < 1) return false; - if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; - return true; - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - partialSig$1.canAddToArray = canAddToArray; - - var porCommitment$1 = {}; - - Object.defineProperty(porCommitment$1, '__esModule', { value: true }); - const typeFields_1$5 = typeFields; - function decode$4(keyVal) { - if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { - throw new Error( - 'Decode Error: could not decode porCommitment with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.toString('utf8'); - } - porCommitment$1.decode = decode$4; - function encode$4(data) { - const key = Buffer$m.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); - return { - key, - value: Buffer$m.from(data, 'utf8'), - }; - } - porCommitment$1.encode = encode$4; - porCommitment$1.expected = 'string'; - function check$g(data) { - return typeof data === 'string'; - } - porCommitment$1.check = check$g; - function canAdd$2(currentData, newData) { - return !!currentData && !!newData && currentData.porCommitment === undefined; - } - porCommitment$1.canAdd = canAdd$2; - - var sighashType$1 = {}; - - Object.defineProperty(sighashType$1, '__esModule', { value: true }); - const typeFields_1$4 = typeFields; - function decode$3(keyVal) { - if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { - throw new Error( - 'Decode Error: could not decode sighashType with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value.readUInt32LE(0); - } - sighashType$1.decode = decode$3; - function encode$3(data) { - const key = Buffer$m.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$m.allocUnsafe(4); - value.writeUInt32LE(data, 0); - return { - key, - value, - }; - } - sighashType$1.encode = encode$3; - sighashType$1.expected = 'number'; - function check$f(data) { - return typeof data === 'number'; - } - sighashType$1.check = check$f; - function canAdd$1(currentData, newData) { - return !!currentData && !!newData && currentData.sighashType === undefined; - } - sighashType$1.canAdd = canAdd$1; - - var witnessUtxo$1 = {}; - - var tools = {}; - - var varint$1 = {}; - - Object.defineProperty(varint$1, '__esModule', { value: true }); - // Number.MAX_SAFE_INTEGER - const MAX_SAFE_INTEGER$4 = 9007199254740991; - function checkUInt53(n) { - if (n < 0 || n > MAX_SAFE_INTEGER$4 || n % 1 !== 0) - throw new RangeError('value out of range'); - } - function encode$2(_number, buffer, offset) { - checkUInt53(_number); - if (!buffer) buffer = Buffer$m.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - // 8 bit - if (_number < 0xfd) { - buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); - // 16 bit - } else if (_number <= 0xffff) { - buffer.writeUInt8(0xfd, offset); - buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); - // 32 bit - } else if (_number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset); - buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); - // 64 bit - } else { - buffer.writeUInt8(0xff, offset); - buffer.writeUInt32LE(_number >>> 0, offset + 1); - buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); - } - return buffer; - } - varint$1.encode = encode$2; - function decode$2(buffer, offset) { - if (!isBuffer(buffer)) - throw new TypeError('buffer must be a Buffer instance'); - if (!offset) offset = 0; - const first = buffer.readUInt8(offset); - // 8 bit - if (first < 0xfd) { - Object.assign(decode$2, { bytes: 1 }); - return first; - // 16 bit - } else if (first === 0xfd) { - Object.assign(decode$2, { bytes: 3 }); - return buffer.readUInt16LE(offset + 1); - // 32 bit - } else if (first === 0xfe) { - Object.assign(decode$2, { bytes: 5 }); - return buffer.readUInt32LE(offset + 1); - // 64 bit - } else { - Object.assign(decode$2, { bytes: 9 }); - const lo = buffer.readUInt32LE(offset + 1); - const hi = buffer.readUInt32LE(offset + 5); - const _number = hi * 0x0100000000 + lo; - checkUInt53(_number); - return _number; - } - } - varint$1.decode = decode$2; - function encodingLength(_number) { - checkUInt53(_number); - return _number < 0xfd - ? 1 - : _number <= 0xffff - ? 3 - : _number <= 0xffffffff - ? 5 - : 9; - } - varint$1.encodingLength = encodingLength; - - Object.defineProperty(tools, '__esModule', { value: true }); - const varuint$3 = varint$1; - tools.range = n => [...Array(n).keys()]; - function reverseBuffer(buffer) { - if (buffer.length < 1) return buffer; - let j = buffer.length - 1; - let tmp = 0; - for (let i = 0; i < buffer.length / 2; i++) { - tmp = buffer[i]; - buffer[i] = buffer[j]; - buffer[j] = tmp; - j--; - } - return buffer; - } - tools.reverseBuffer = reverseBuffer; - function keyValsToBuffer(keyVals) { - const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$m.from([0])); - return Buffer$m.concat(buffers); - } - tools.keyValsToBuffer = keyValsToBuffer; - function keyValToBuffer(keyVal) { - const keyLen = keyVal.key.length; - const valLen = keyVal.value.length; - const keyVarIntLen = varuint$3.encodingLength(keyLen); - const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$m.allocUnsafe( - keyVarIntLen + keyLen + valVarIntLen + valLen, - ); - varuint$3.encode(keyLen, buffer, 0); - keyVal.key.copy(buffer, keyVarIntLen); - varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); - keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); - return buffer; - } - tools.keyValToBuffer = keyValToBuffer; - // https://github.com/feross/buffer/blob/master/index.js#L1127 - function verifuint(value, max) { - if (typeof value !== 'number') - throw new Error('cannot write a non-number as a number'); - if (value < 0) - throw new Error('specified a negative value for writing an unsigned value'); - if (value > max) throw new Error('RangeError: value out of range'); - if (Math.floor(value) !== value) - throw new Error('value has a fractional component'); - } - function readUInt64LE(buffer, offset) { - const a = buffer.readUInt32LE(offset); - let b = buffer.readUInt32LE(offset + 4); - b *= 0x100000000; - verifuint(b + a, 0x001fffffffffffff); - return b + a; - } - tools.readUInt64LE = readUInt64LE; - function writeUInt64LE(buffer, value, offset) { - verifuint(value, 0x001fffffffffffff); - buffer.writeInt32LE(value & -1, offset); - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); - return offset + 8; - } - tools.writeUInt64LE = writeUInt64LE; - - Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); - const typeFields_1$3 = typeFields; - const tools_1$2 = tools; - const varuint$2 = varint$1; - function decode$1(keyVal) { - if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { - throw new Error( - 'Decode Error: could not decode witnessUtxo with key 0x' + - keyVal.key.toString('hex'), - ); - } - const value = tools_1$2.readUInt64LE(keyVal.value, 0); - let _offset = 8; - const scriptLen = varuint$2.decode(keyVal.value, _offset); - _offset += varuint$2.encodingLength(scriptLen); - const script = keyVal.value.slice(_offset); - if (script.length !== scriptLen) { - throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); - } - return { - script, - value, - }; - } - witnessUtxo$1.decode = decode$1; - function encode$1(data) { - const { script, value } = data; - const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$m.allocUnsafe(8 + varintLen + script.length); - tools_1$2.writeUInt64LE(result, value, 0); - varuint$2.encode(script.length, result, 8); - script.copy(result, 8 + varintLen); - return { - key: Buffer$m.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), - value: result, - }; - } - witnessUtxo$1.encode = encode$1; - witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; - function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; - } - witnessUtxo$1.check = check$e; - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.witnessUtxo === undefined; - } - witnessUtxo$1.canAdd = canAdd; - - var bip32Derivation$1 = {}; - - Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); - const range$3 = n => [...Array(n).keys()]; - function makeConverter$2(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode bip32Derivation with key 0x' + - keyVal.key.toString('hex'), - ); - } - if ( - !(keyVal.key.length === 34 || keyVal.key.length === 66) || - ![2, 3, 4].includes(keyVal.key[1]) - ) { - throw new Error( - 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + - keyVal.key.toString('hex'), - ); - } - if ((keyVal.value.length / 4) % 1 !== 0) { - throw new Error( - 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', - ); - } - const pubkey = keyVal.key.slice(1); - const data = { - masterFingerprint: keyVal.value.slice(0, 4), - pubkey, - path: 'm', - }; - for (const i of range$3(keyVal.value.length / 4 - 1)) { - const val = keyVal.value.readUInt32LE(i * 4 + 4); - const isHard = !!(val & 0x80000000); - const idx = val & 0x7fffffff; - data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); - } - return data; - } - function encode(data) { - const head = Buffer$m.from([TYPE_BYTE]); - const key = Buffer$m.concat([head, data.pubkey]); - const splitPath = data.path.split('/'); - const value = Buffer$m.allocUnsafe(splitPath.length * 4); - data.masterFingerprint.copy(value, 0); - let offset = 4; - splitPath.slice(1).forEach(level => { - const isHard = level.slice(-1) === "'"; - let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); - if (isHard) num += 0x80000000; - value.writeUInt32LE(num, offset); - offset += 4; - }); - return { - key, - value, - }; - } - const expected = - '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; - function check(data) { - return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && - typeof data.path === 'string' && - [33, 65].includes(data.pubkey.length) && - [2, 3, 4].includes(data.pubkey[0]) && - data.masterFingerprint.length === 4 - ); - } - function canAddToArray(array, item, dupeSet) { - const dupeString = item.pubkey.toString('hex'); - if (dupeSet.has(dupeString)) return false; - dupeSet.add(dupeString); - return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; - } - return { - decode, - encode, - check, - expected, - canAddToArray, - }; - } - bip32Derivation$1.makeConverter = makeConverter$2; - - var checkPubkey$1 = {}; - - Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); - function makeChecker(pubkeyTypes) { - return checkPubkey; - function checkPubkey(keyVal) { - let pubkey; - if (pubkeyTypes.includes(keyVal.key[0])) { - pubkey = keyVal.key.slice(1); - if ( - !(pubkey.length === 33 || pubkey.length === 65) || - ![2, 3, 4].includes(pubkey[0]) - ) { - throw new Error( - 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), - ); - } - } - return pubkey; - } - } - checkPubkey$1.makeChecker = makeChecker; - - var redeemScript$1 = {}; - - Object.defineProperty(redeemScript$1, '__esModule', { value: true }); - function makeConverter$1(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode redeemScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return !!currentData && !!newData && currentData.redeemScript === undefined; - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - redeemScript$1.makeConverter = makeConverter$1; - - var witnessScript$1 = {}; - - Object.defineProperty(witnessScript$1, '__esModule', { value: true }); - function makeConverter(TYPE_BYTE) { - function decode(keyVal) { - if (keyVal.key[0] !== TYPE_BYTE) { - throw new Error( - 'Decode Error: could not decode witnessScript with key 0x' + - keyVal.key.toString('hex'), - ); - } - return keyVal.value; - } - function encode(data) { - const key = Buffer$m.from([TYPE_BYTE]); - return { - key, - value: data, - }; - } - const expected = 'Buffer'; - function check(data) { - return isBuffer(data); - } - function canAdd(currentData, newData) { - return ( - !!currentData && !!newData && currentData.witnessScript === undefined - ); - } - return { - decode, - encode, - check, - expected, - canAdd, - }; - } - witnessScript$1.makeConverter = makeConverter; - - Object.defineProperty(converter, '__esModule', { value: true }); - const typeFields_1$2 = typeFields; - const globalXpub = globalXpub$1; - const unsignedTx = unsignedTx$1; - const finalScriptSig = finalScriptSig$1; - const finalScriptWitness = finalScriptWitness$1; - const nonWitnessUtxo = nonWitnessUtxo$1; - const partialSig = partialSig$1; - const porCommitment = porCommitment$1; - const sighashType = sighashType$1; - const witnessUtxo = witnessUtxo$1; - const bip32Derivation = bip32Derivation$1; - const checkPubkey = checkPubkey$1; - const redeemScript = redeemScript$1; - const witnessScript = witnessScript$1; - const globals = { - unsignedTx, - globalXpub, - // pass an Array of key bytes that require pubkey beside the key - checkPubkey: checkPubkey.makeChecker([]), - }; - converter.globals = globals; - const inputs = { - nonWitnessUtxo, - partialSig, - sighashType, - finalScriptSig, - finalScriptWitness, - porCommitment, - witnessUtxo, - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.InputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.InputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.InputTypes.PARTIAL_SIG, - typeFields_1$2.InputTypes.BIP32_DERIVATION, - ]), - }; - converter.inputs = inputs; - const outputs = { - bip32Derivation: bip32Derivation.makeConverter( - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ), - redeemScript: redeemScript.makeConverter( - typeFields_1$2.OutputTypes.REDEEM_SCRIPT, - ), - witnessScript: witnessScript.makeConverter( - typeFields_1$2.OutputTypes.WITNESS_SCRIPT, - ), - checkPubkey: checkPubkey.makeChecker([ - typeFields_1$2.OutputTypes.BIP32_DERIVATION, - ]), - }; - converter.outputs = outputs; - - Object.defineProperty(fromBuffer, '__esModule', { value: true }); - const convert$1 = converter; - const tools_1$1 = tools; - const varuint$1 = varint$1; - const typeFields_1$1 = typeFields; - function psbtFromBuffer(buffer, txGetter) { - let offset = 0; - function varSlice() { - const keyLen = varuint$1.decode(buffer, offset); - offset += varuint$1.encodingLength(keyLen); - const key = buffer.slice(offset, offset + keyLen); - offset += keyLen; - return key; - } - function readUInt32BE() { - const num = buffer.readUInt32BE(offset); - offset += 4; - return num; - } - function readUInt8() { - const num = buffer.readUInt8(offset); - offset += 1; - return num; - } - function getKeyValue() { - const key = varSlice(); - const value = varSlice(); - return { - key, - value, - }; - } - function checkEndOfKeyValPairs() { - if (offset >= buffer.length) { - throw new Error('Format Error: Unexpected End of PSBT'); - } - const isEnd = buffer.readUInt8(offset) === 0; - if (isEnd) { - offset++; - } - return isEnd; - } - if (readUInt32BE() !== 0x70736274) { - throw new Error('Format Error: Invalid Magic Number'); - } - if (readUInt8() !== 0xff) { - throw new Error( - 'Format Error: Magic Number must be followed by 0xff separator', - ); - } - const globalMapKeyVals = []; - const globalKeyIndex = {}; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (globalKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for global keymap: key ' + hexKey, - ); - } - globalKeyIndex[hexKey] = 1; - globalMapKeyVals.push(keyVal); - } - const unsignedTxMaps = globalMapKeyVals.filter( - keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (unsignedTxMaps.length !== 1) { - throw new Error('Format Error: Only one UNSIGNED_TX allowed'); - } - const unsignedTx = txGetter(unsignedTxMaps[0].value); - // Get input and output counts to loop the respective fields - const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); - const inputKeyVals = []; - const outputKeyVals = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const inputKeyIndex = {}; - const input = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (inputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each input: ' + - 'input index ' + - index + - ' key ' + - hexKey, - ); - } - inputKeyIndex[hexKey] = 1; - input.push(keyVal); - } - inputKeyVals.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const outputKeyIndex = {}; - const output = []; - while (!checkEndOfKeyValPairs()) { - const keyVal = getKeyValue(); - const hexKey = keyVal.key.toString('hex'); - if (outputKeyIndex[hexKey]) { - throw new Error( - 'Format Error: Keys must be unique for each output: ' + - 'output index ' + - index + - ' key ' + - hexKey, - ); - } - outputKeyIndex[hexKey] = 1; - output.push(keyVal); - } - outputKeyVals.push(output); - } - return psbtFromKeyVals(unsignedTx, { - globalMapKeyVals, - inputKeyVals, - outputKeyVals, - }); - } - fromBuffer.psbtFromBuffer = psbtFromBuffer; - function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$m.from([keyNum]))) { - throw new Error( - `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, - ); - } - } - fromBuffer.checkKeyBuffer = checkKeyBuffer; - function psbtFromKeyVals( - unsignedTx, - { globalMapKeyVals, inputKeyVals, outputKeyVals }, - ) { - // That was easy :-) - const globalMap = { - unsignedTx, - }; - let txCount = 0; - for (const keyVal of globalMapKeyVals) { - // If a globalMap item needs pubkey, uncomment - // const pubkey = convert.globals.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.GlobalTypes.UNSIGNED_TX: - checkKeyBuffer( - 'global', - keyVal.key, - typeFields_1$1.GlobalTypes.UNSIGNED_TX, - ); - if (txCount > 0) { - throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); - } - txCount++; - break; - case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: - if (globalMap.globalXpub === undefined) { - globalMap.globalXpub = []; - } - globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); - break; - default: - // This will allow inclusion during serialization. - if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; - globalMap.unknownKeyVals.push(keyVal); - } - } - // Get input and output counts to loop the respective fields - const inputCount = inputKeyVals.length; - const outputCount = outputKeyVals.length; - const inputs = []; - const outputs = []; - // Get input fields - for (const index of tools_1$1.range(inputCount)) { - const input = {}; - for (const keyVal of inputKeyVals[index]) { - convert$1.inputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.NON_WITNESS_UTXO, - ); - if (input.nonWitnessUtxo !== undefined) { - throw new Error( - 'Format Error: Input has multiple NON_WITNESS_UTXO', - ); - } - input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_UTXO: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_UTXO, - ); - if (input.witnessUtxo !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_UTXO'); - } - input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); - break; - case typeFields_1$1.InputTypes.PARTIAL_SIG: - if (input.partialSig === undefined) { - input.partialSig = []; - } - input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); - break; - case typeFields_1$1.InputTypes.SIGHASH_TYPE: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.SIGHASH_TYPE, - ); - if (input.sighashType !== undefined) { - throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); - } - input.sighashType = convert$1.inputs.sighashType.decode(keyVal); - break; - case typeFields_1$1.InputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.REDEEM_SCRIPT, - ); - if (input.redeemScript !== undefined) { - throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); - } - input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.WITNESS_SCRIPT, - ); - if (input.witnessScript !== undefined) { - throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); - } - input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.InputTypes.BIP32_DERIVATION: - if (input.bip32Derivation === undefined) { - input.bip32Derivation = []; - } - input.bip32Derivation.push( - convert$1.inputs.bip32Derivation.decode(keyVal), - ); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, - ); - input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); - break; - case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, - ); - input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( - keyVal, - ); - break; - case typeFields_1$1.InputTypes.POR_COMMITMENT: - checkKeyBuffer( - 'input', - keyVal.key, - typeFields_1$1.InputTypes.POR_COMMITMENT, - ); - input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); - break; - default: - // This will allow inclusion during serialization. - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - } - } - inputs.push(input); - } - for (const index of tools_1$1.range(outputCount)) { - const output = {}; - for (const keyVal of outputKeyVals[index]) { - convert$1.outputs.checkPubkey(keyVal); - switch (keyVal.key[0]) { - case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.REDEEM_SCRIPT, - ); - if (output.redeemScript !== undefined) { - throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); - } - output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: - checkKeyBuffer( - 'output', - keyVal.key, - typeFields_1$1.OutputTypes.WITNESS_SCRIPT, - ); - if (output.witnessScript !== undefined) { - throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); - } - output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); - break; - case typeFields_1$1.OutputTypes.BIP32_DERIVATION: - if (output.bip32Derivation === undefined) { - output.bip32Derivation = []; - } - output.bip32Derivation.push( - convert$1.outputs.bip32Derivation.decode(keyVal), - ); - break; - default: - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - } - } - outputs.push(output); - } - return { globalMap, inputs, outputs }; - } - fromBuffer.psbtFromKeyVals = psbtFromKeyVals; - - var toBuffer = {}; - - Object.defineProperty(toBuffer, '__esModule', { value: true }); - const convert = converter; - const tools_1 = tools; - function psbtToBuffer({ globalMap, inputs, outputs }) { - const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ - globalMap, - inputs, - outputs, - }); - const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); - const keyValsOrEmptyToBuffer = keyVals => - keyVals.length === 0 - ? [Buffer$m.from([0])] - : keyVals.map(tools_1.keyValsToBuffer); - const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); - const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$m.allocUnsafe(5); - header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$m.concat( - [header, globalBuffer].concat(inputBuffers, outputBuffers), - ); - } - toBuffer.psbtToBuffer = psbtToBuffer; - const sortKeyVals = (a, b) => { - return a.key.compare(b.key); - }; - function keyValsFromMap(keyValMap, converterFactory) { - const keyHexSet = new Set(); - const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { - if (key === 'unknownKeyVals') return result; - // We are checking for undefined anyways. So ignore TS error - // @ts-ignore - const converter = converterFactory[key]; - if (converter === undefined) return result; - const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( - converter.encode, - ); - const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); - keyHexes.forEach(hex => { - if (keyHexSet.has(hex)) - throw new Error('Serialize Error: Duplicate key: ' + hex); - keyHexSet.add(hex); - }); - return result.concat(encodedKeyVals); - }, []); - // Get other keyVals that have not yet been gotten - const otherKeyVals = keyValMap.unknownKeyVals - ? keyValMap.unknownKeyVals.filter(keyVal => { - return !keyHexSet.has(keyVal.key.toString('hex')); - }) - : []; - return keyVals.concat(otherKeyVals).sort(sortKeyVals); - } - function psbtToKeyVals({ globalMap, inputs, outputs }) { - // First parse the global keyVals - // Get any extra keyvals to pass along - return { - globalKeyVals: keyValsFromMap(globalMap, convert.globals), - inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), - outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), - }; - } - toBuffer.psbtToKeyVals = psbtToKeyVals; - - (function (exports) { - function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - Object.defineProperty(exports, '__esModule', { value: true }); - __export(fromBuffer); - __export(toBuffer); - }(parser)); - - Object.defineProperty(combiner, '__esModule', { value: true }); - const parser_1$1 = parser; - function combine(psbts) { - const self = psbts[0]; - const selfKeyVals = parser_1$1.psbtToKeyVals(self); - const others = psbts.slice(1); - if (others.length === 0) throw new Error('Combine: Nothing to combine'); - const selfTx = getTx(self); - if (selfTx === undefined) { - throw new Error('Combine: Self missing transaction'); - } - const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); - const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); - const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); - for (const other of others) { - const otherTx = getTx(other); - if ( - otherTx === undefined || - !otherTx.toBuffer().equals(selfTx.toBuffer()) - ) { - throw new Error( - 'Combine: One of the Psbts does not have the same transaction.', - ); - } - const otherKeyVals = parser_1$1.psbtToKeyVals(other); - const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); - otherGlobalSet.forEach( - keyPusher( - selfGlobalSet, - selfKeyVals.globalKeyVals, - otherKeyVals.globalKeyVals, - ), - ); - const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); - otherInputSets.forEach((inputSet, idx) => - inputSet.forEach( - keyPusher( - selfInputSets[idx], - selfKeyVals.inputKeyVals[idx], - otherKeyVals.inputKeyVals[idx], - ), - ), - ); - const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); - otherOutputSets.forEach((outputSet, idx) => - outputSet.forEach( - keyPusher( - selfOutputSets[idx], - selfKeyVals.outputKeyVals[idx], - otherKeyVals.outputKeyVals[idx], - ), - ), - ); - } - return parser_1$1.psbtFromKeyVals(selfTx, { - globalMapKeyVals: selfKeyVals.globalKeyVals, - inputKeyVals: selfKeyVals.inputKeyVals, - outputKeyVals: selfKeyVals.outputKeyVals, - }); - } - combiner.combine = combine; - function keyPusher(selfSet, selfKeyVals, otherKeyVals) { - return key => { - if (selfSet.has(key)) return; - const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; - selfKeyVals.push(newKv); - selfSet.add(key); - }; - } - function getTx(psbt) { - return psbt.globalMap.unsignedTx; - } - function getKeySet(keyVals) { - const set = new Set(); - keyVals.forEach(keyVal => { - const hex = keyVal.key.toString('hex'); - if (set.has(hex)) - throw new Error('Combine: KeyValue Map keys should be unique'); - set.add(hex); - }); - return set; - } - - var utils = {}; - - (function (exports) { - Object.defineProperty(exports, '__esModule', { value: true }); - const converter$1 = converter; - function checkForInput(inputs, inputIndex) { - const input = inputs[inputIndex]; - if (input === undefined) throw new Error(`No input #${inputIndex}`); - return input; - } - exports.checkForInput = checkForInput; - function checkForOutput(outputs, outputIndex) { - const output = outputs[outputIndex]; - if (output === undefined) throw new Error(`No output #${outputIndex}`); - return output; - } - exports.checkForOutput = checkForOutput; - function checkHasKey(checkKeyVal, keyVals, enumLength) { - if (checkKeyVal.key[0] < enumLength) { - throw new Error( - `Use the method for your specific key instead of addUnknownKeyVal*`, - ); - } - if ( - keyVals && - keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 - ) { - throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); - } - } - exports.checkHasKey = checkHasKey; - function getEnumLength(myenum) { - let count = 0; - Object.keys(myenum).forEach(val => { - if (Number(isNaN(Number(val)))) { - count++; - } - }); - return count; - } - exports.getEnumLength = getEnumLength; - function inputCheckUncleanFinalized(inputIndex, input) { - let result = false; - if (input.nonWitnessUtxo || input.witnessUtxo) { - const needScriptSig = !!input.redeemScript; - const needWitnessScript = !!input.witnessScript; - const scriptSigOK = !needScriptSig || !!input.finalScriptSig; - const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; - const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; - result = scriptSigOK && witnessScriptOK && hasOneFinal; - } - if (result === false) { - throw new Error( - `Input #${inputIndex} has too much or too little data to clean`, - ); - } - } - exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; - function throwForUpdateMaker(typeName, name, expected, data) { - throw new Error( - `Data for ${typeName} key ${name} is incorrect: Expected ` + - `${expected} and got ${JSON.stringify(data)}`, - ); - } - function updateMaker(typeName) { - return (updateData, mainData) => { - for (const name of Object.keys(updateData)) { - // @ts-ignore - const data = updateData[name]; - // @ts-ignore - const { canAdd, canAddToArray, check, expected } = - // @ts-ignore - converter$1[typeName + 's'][name] || {}; - const isArray = !!canAddToArray; - // If unknown data. ignore and do not add - if (check) { - if (isArray) { - if ( - !Array.isArray(data) || - // @ts-ignore - (mainData[name] && !Array.isArray(mainData[name])) - ) { - throw new Error(`Key type ${name} must be an array`); - } - if (!data.every(check)) { - throwForUpdateMaker(typeName, name, expected, data); - } - // @ts-ignore - const arr = mainData[name] || []; - const dupeCheckSet = new Set(); - if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { - throw new Error('Can not add duplicate data to array'); - } - // @ts-ignore - mainData[name] = arr.concat(data); - } else { - if (!check(data)) { - throwForUpdateMaker(typeName, name, expected, data); - } - if (!canAdd(mainData, data)) { - throw new Error(`Can not add duplicate data to ${typeName}`); - } - // @ts-ignore - mainData[name] = data; - } - } - } - }; - } - exports.updateGlobal = updateMaker('global'); - exports.updateInput = updateMaker('input'); - exports.updateOutput = updateMaker('output'); - function addInputAttributes(inputs, data) { - const index = inputs.length - 1; - const input = checkForInput(inputs, index); - exports.updateInput(data, input); - } - exports.addInputAttributes = addInputAttributes; - function addOutputAttributes(outputs, data) { - const index = outputs.length - 1; - const output = checkForInput(outputs, index); - exports.updateOutput(data, output); - } - exports.addOutputAttributes = addOutputAttributes; - function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Version: Invalid Transaction'); - } - txBuf.writeUInt32LE(version, 0); - return txBuf; - } - exports.defaultVersionSetter = defaultVersionSetter; - function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { - throw new Error('Set Locktime: Invalid Transaction'); - } - txBuf.writeUInt32LE(locktime, txBuf.length - 4); - return txBuf; - } - exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); - - Object.defineProperty(psbt, '__esModule', { value: true }); - const combiner_1 = combiner; - const parser_1 = parser; - const typeFields_1 = typeFields; - const utils_1$1 = utils; - class Psbt$1 { - constructor(tx) { - this.inputs = []; - this.outputs = []; - this.globalMap = { - unsignedTx: tx, - }; - } - static fromBase64(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromHex(data, txFromBuffer) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, txFromBuffer); - } - static fromBuffer(buffer, txFromBuffer) { - const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); - const psbt = new this(results.globalMap.unsignedTx); - Object.assign(psbt, results); - return psbt; - } - toBase64() { - const buffer = this.toBuffer(); - return buffer.toString('base64'); - } - toHex() { - const buffer = this.toBuffer(); - return buffer.toString('hex'); - } - toBuffer() { - return parser_1.psbtToBuffer(this); - } - updateGlobal(updateData) { - utils_1$1.updateGlobal(updateData, this.globalMap); - return this; - } - updateInput(inputIndex, updateData) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.updateInput(updateData, input); - return this; - } - updateOutput(outputIndex, updateData) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.updateOutput(updateData, output); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - utils_1$1.checkHasKey( - keyVal, - this.globalMap.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.GlobalTypes), - ); - if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; - this.globalMap.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.checkHasKey( - keyVal, - input.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.InputTypes), - ); - if (!input.unknownKeyVals) input.unknownKeyVals = []; - input.unknownKeyVals.push(keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - const output = utils_1$1.checkForOutput(this.outputs, outputIndex); - utils_1$1.checkHasKey( - keyVal, - output.unknownKeyVals, - utils_1$1.getEnumLength(typeFields_1.OutputTypes), - ); - if (!output.unknownKeyVals) output.unknownKeyVals = []; - output.unknownKeyVals.push(keyVal); - return this; - } - addInput(inputData) { - this.globalMap.unsignedTx.addInput(inputData); - this.inputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = inputData.unknownKeyVals || []; - const inputIndex = this.inputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(inputIndex, keyVal), - ); - utils_1$1.addInputAttributes(this.inputs, inputData); - return this; - } - addOutput(outputData) { - this.globalMap.unsignedTx.addOutput(outputData); - this.outputs.push({ - unknownKeyVals: [], - }); - const addKeyVals = outputData.unknownKeyVals || []; - const outputIndex = this.outputs.length - 1; - if (!Array.isArray(addKeyVals)) { - throw new Error('unknownKeyVals must be an Array'); - } - addKeyVals.forEach(keyVal => - this.addUnknownKeyValToInput(outputIndex, keyVal), - ); - utils_1$1.addOutputAttributes(this.outputs, outputData); - return this; - } - clearFinalizedInput(inputIndex) { - const input = utils_1$1.checkForInput(this.inputs, inputIndex); - utils_1$1.inputCheckUncleanFinalized(inputIndex, input); - for (const key of Object.keys(input)) { - if ( - ![ - 'witnessUtxo', - 'nonWitnessUtxo', - 'finalScriptSig', - 'finalScriptWitness', - 'unknownKeyVals', - ].includes(key) - ) { - // @ts-ignore - delete input[key]; - } - } - return this; - } - combine(...those) { - // Combine this with those. - // Return self for chaining. - const result = combiner_1.combine([this].concat(those)); - Object.assign(this, result); - return this; - } - getTransaction() { - return this.globalMap.unsignedTx.toBuffer(); - } - } - psbt.Psbt = Psbt$1; - - Object.defineProperty(psbt$1, '__esModule', { value: true }); - const bip174_1 = psbt; - const varuint = varint$1; - const utils_1 = utils; - const address_1 = address$1; - const bufferutils_1$1 = bufferutils; - const crypto_1$1 = crypto$2; - const ecpair_1 = ecpair; - const networks_1 = networks$3; - const payments$2 = payments$4; - const bscript$f = script$1; - const transaction_1$2 = transaction; - /** - * These are the default arguments for a Psbt instance. - */ - const DEFAULT_OPTS = { - /** - * A bitcoinjs Network object. This is only used if you pass an `address` - * parameter to addOutput. Otherwise it is not needed and can be left default. - */ - network: networks_1.bitcoin, - /** - * When extractTransaction is called, the fee rate is checked. - * THIS IS NOT TO BE RELIED ON. - * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. - */ - maximumFeeRate: 5000, - }; - /** - * Psbt class can parse and generate a PSBT binary based off of the BIP174. - * There are 6 roles that this class fulfills. (Explained in BIP174) - * - * Creator: This can be done with `new Psbt()` - * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, - * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to - * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, - * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` - * addInput requires hash: Buffer | string; and index: number; as attributes - * and can also include any attributes that are used in updateInput method. - * addOutput requires script: Buffer; and value: number; and likewise can include - * data for updateOutput. - * For a list of what attributes should be what types. Check the bip174 library. - * Also, check the integration tests for some examples of usage. - * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input - * information for your pubkey or pubkeyhash, and only sign inputs where it finds - * your info. Or you can explicitly sign a specific input with signInput and - * signInputAsync. For the async methods you can create a SignerAsync object - * and use something like a hardware wallet to sign with. (You must implement this) - * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` - * the psbt calling combine will always have precedence when a conflict occurs. - * Combine checks if the internal bitcoin transaction is the same, so be sure that - * all sequences, version, locktime, etc. are the same before combining. - * Input Finalizer: This role is fairly important. Not only does it need to construct - * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. - * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` - * Running any finalize method will delete any data in the input(s) that are no longer - * needed due to the finalized scripts containing the information. - * Transaction Extractor: This role will perform some checks before returning a - * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. - */ - class Psbt { - constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { - this.data = data; - // set defaults - this.opts = Object.assign({}, DEFAULT_OPTS, opts); - this.__CACHE = { - __NON_WITNESS_UTXO_TX_CACHE: [], - __NON_WITNESS_UTXO_BUF_CACHE: [], - __TX_IN_CACHE: {}, - __TX: this.data.globalMap.unsignedTx.tx, - // Old TransactionBuilder behavior was to not confirm input values - // before signing. Even though we highly encourage people to get - // the full parent transaction to verify values, the ability to - // sign non-segwit inputs without the full transaction was often - // requested. So the only way to activate is to use @ts-ignore. - // We will disable exporting the Psbt when unsafe sign is active. - // because it is not BIP174 compliant. - __UNSAFE_SIGN_NONSEGWIT: false, - }; - if (this.data.inputs.length === 0) this.setVersion(2); - // Make data hidden when enumerating - const dpew = (obj, attr, enumerable, writable) => - Object.defineProperty(obj, attr, { - enumerable, - writable, - }); - dpew(this, '__CACHE', false, true); - dpew(this, 'opts', false, true); - } - static fromBase64(data, opts = {}) { - const buffer = Buffer$m.from(data, 'base64'); - return this.fromBuffer(buffer, opts); - } - static fromHex(data, opts = {}) { - const buffer = Buffer$m.from(data, 'hex'); - return this.fromBuffer(buffer, opts); - } - static fromBuffer(buffer, opts = {}) { - const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); - const psbt = new Psbt(opts, psbtBase); - checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); - return psbt; - } - get inputCount() { - return this.data.inputs.length; - } - get version() { - return this.__CACHE.__TX.version; - } - set version(version) { - this.setVersion(version); - } - get locktime() { - return this.__CACHE.__TX.locktime; - } - set locktime(locktime) { - this.setLocktime(locktime); - } - get txInputs() { - return this.__CACHE.__TX.ins.map(input => ({ - hash: bufferutils_1$1.cloneBuffer(input.hash), - index: input.index, - sequence: input.sequence, - })); - } - get txOutputs() { - return this.__CACHE.__TX.outs.map(output => { - let address; - try { - address = address_1.fromOutputScript(output.script, this.opts.network); - } catch (_) {} - return { - script: bufferutils_1$1.cloneBuffer(output.script), - value: output.value, - address, - }; - }); - } - combine(...those) { - this.data.combine(...those.map(o => o.data)); - return this; - } - clone() { - // TODO: more efficient cloning - const res = Psbt.fromBuffer(this.data.toBuffer()); - res.opts = JSON.parse(JSON.stringify(this.opts)); - return res; - } - setMaximumFeeRate(satoshiPerByte) { - check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw - this.opts.maximumFeeRate = satoshiPerByte; - } - setVersion(version) { - check32Bit(version); - checkInputsForPartialSig(this.data.inputs, 'setVersion'); - const c = this.__CACHE; - c.__TX.version = version; - c.__EXTRACTED_TX = undefined; - return this; - } - setLocktime(locktime) { - check32Bit(locktime); - checkInputsForPartialSig(this.data.inputs, 'setLocktime'); - const c = this.__CACHE; - c.__TX.locktime = locktime; - c.__EXTRACTED_TX = undefined; - return this; - } - setInputSequence(inputIndex, sequence) { - check32Bit(sequence); - checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); - const c = this.__CACHE; - if (c.__TX.ins.length <= inputIndex) { - throw new Error('Input index too high'); - } - c.__TX.ins[inputIndex].sequence = sequence; - c.__EXTRACTED_TX = undefined; - return this; - } - addInputs(inputDatas) { - inputDatas.forEach(inputData => this.addInput(inputData)); - return this; - } - addInput(inputData) { - if ( - arguments.length > 1 || - !inputData || - inputData.hash === undefined || - inputData.index === undefined - ) { - throw new Error( - `Invalid arguments for Psbt.addInput. ` + - `Requires single object with at least [hash] and [index]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addInput'); - if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); - const c = this.__CACHE; - this.data.addInput(inputData); - const txIn = c.__TX.ins[c.__TX.ins.length - 1]; - checkTxInputCache(c, txIn); - const inputIndex = this.data.inputs.length - 1; - const input = this.data.inputs[inputIndex]; - if (input.nonWitnessUtxo) { - addNonWitnessTxCache(this.__CACHE, input, inputIndex); - } - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - addOutputs(outputDatas) { - outputDatas.forEach(outputData => this.addOutput(outputData)); - return this; - } - addOutput(outputData) { - if ( - arguments.length > 1 || - !outputData || - outputData.value === undefined || - (outputData.address === undefined && outputData.script === undefined) - ) { - throw new Error( - `Invalid arguments for Psbt.addOutput. ` + - `Requires single object with at least [script or address] and [value]`, - ); - } - checkInputsForPartialSig(this.data.inputs, 'addOutput'); - const { address } = outputData; - if (typeof address === 'string') { - const { network } = this.opts; - const script = address_1.toOutputScript(address, network); - outputData = Object.assign(outputData, { script }); - } - const c = this.__CACHE; - this.data.addOutput(outputData); - c.__FEE = undefined; - c.__FEE_RATE = undefined; - c.__EXTRACTED_TX = undefined; - return this; - } - extractTransaction(disableFeeCheck) { - if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); - const c = this.__CACHE; - if (!disableFeeCheck) { - checkFees(this, c, this.opts); - } - if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; - const tx = c.__TX.clone(); - inputFinalizeGetAmts(this.data.inputs, tx, c, true); - return tx; - } - getFeeRate() { - return getTxCacheValue( - '__FEE_RATE', - 'fee rate', - this.data.inputs, - this.__CACHE, - ); - } - getFee() { - return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); - } - finalizeAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - range$2(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); - return this; - } - finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( - inputIndex, - input, - this.__CACHE, - ); - if (!script) throw new Error(`No script found for input #${inputIndex}`); - checkPartialSigSighashes(input); - const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( - inputIndex, - input, - script, - isSegwit, - isP2SH, - isP2WSH, - ); - if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); - if (finalScriptWitness) - this.data.updateInput(inputIndex, { finalScriptWitness }); - if (!finalScriptSig && !finalScriptWitness) - throw new Error(`Unknown error finalizing input #${inputIndex}`); - this.data.clearFinalizedInput(inputIndex); - return this; - } - getInputType(inputIndex) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); - const result = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), - input.witnessScript || - redeemFromFinalWitnessScript(input.finalScriptWitness), - ); - const type = result.type === 'raw' ? '' : result.type + '-'; - const mainType = classifyScript(result.meaningfulScript); - return type + mainType; - } - inputHasPubkey(inputIndex, pubkey) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); - } - inputHasHDKey(inputIndex, root) { - const input = utils_1.checkForInput(this.data.inputs, inputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) - ); - } - outputHasPubkey(outputIndex, pubkey) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); - } - outputHasHDKey(outputIndex, root) { - const output = utils_1.checkForOutput(this.data.outputs, outputIndex); - const derivationIsMine = bip32DerivationIsMine(root); - return ( - !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) - ); - } - validateSignaturesOfAllInputs() { - utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one - const results = range$2(this.data.inputs.length).map(idx => - this.validateSignaturesOfInput(idx), - ); - return results.reduce((final, res) => res === true && final, true); - } - validateSignaturesOfInput(inputIndex, pubkey) { - const input = this.data.inputs[inputIndex]; - const partialSig = (input || {}).partialSig; - if (!input || !partialSig || partialSig.length < 1) - throw new Error('No signatures to validate'); - const mySigs = pubkey - ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) - : partialSig; - if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); - const results = []; - let hashCache; - let scriptCache; - let sighashCache; - for (const pSig of mySigs) { - const sig = bscript$f.signature.decode(pSig.signature); - const { hash, script } = - sighashCache !== sig.hashType - ? getHashForSig( - inputIndex, - Object.assign({}, input, { sighashType: sig.hashType }), - this.__CACHE, - true, - ) - : { hash: hashCache, script: scriptCache }; - sighashCache = sig.hashType; - hashCache = hash; - scriptCache = script; - checkScriptForPubkey(pSig.pubkey, script, 'verify'); - const keypair = ecpair_1.fromPublicKey(pSig.pubkey); - results.push(keypair.verify(hash, sig.signature)); - } - return results.every(res => res === true); - } - signAllInputsHD( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInputHD(i, hdKeyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsHDAsync( - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const results = []; - const promises = []; - for (const i of range$2(this.data.inputs.length)) { - promises.push( - this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInputHD( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - throw new Error('Need HDSigner to sign input'); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); - return this; - } - signInputHDAsync( - inputIndex, - hdKeyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { - return reject(new Error('Need HDSigner to sign input')); - } - const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); - const promises = signers.map(signer => - this.signInputAsync(inputIndex, signer, sighashTypes), - ); - return Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); - } - signAllInputs( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - for (const i of range$2(this.data.inputs.length)) { - try { - this.signInput(i, keyPair, sighashTypes); - results.push(true); - } catch (err) { - results.push(false); - } - } - if (results.every(v => v === false)) { - throw new Error('No inputs were signed'); - } - return this; - } - signAllInputsAsync( - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return new Promise((resolve, reject) => { - if (!keyPair || !keyPair.publicKey) - return reject(new Error('Need Signer to sign input')); - // TODO: Add a pubkey/pubkeyhash cache to each input - // as input information is added, then eventually - // optimize this method. - const results = []; - const promises = []; - for (const [i] of this.data.inputs.entries()) { - promises.push( - this.signInputAsync(i, keyPair, sighashTypes).then( - () => { - results.push(true); - }, - () => { - results.push(false); - }, - ), - ); - } - return Promise.all(promises).then(() => { - if (results.every(v => v === false)) { - return reject(new Error('No inputs were signed')); - } - resolve(); - }); - }); - } - signInput( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - return this; - } - signInputAsync( - inputIndex, - keyPair, - sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], - ) { - return Promise.resolve().then(() => { - if (!keyPair || !keyPair.publicKey) - throw new Error('Need Signer to sign input'); - const { hash, sighashType } = getHashAndSighashType( - this.data.inputs, - inputIndex, - keyPair.publicKey, - this.__CACHE, - sighashTypes, - ); - return Promise.resolve(keyPair.sign(hash)).then(signature => { - const partialSig = [ - { - pubkey: keyPair.publicKey, - signature: bscript$f.signature.encode(signature, sighashType), - }, - ]; - this.data.updateInput(inputIndex, { partialSig }); - }); - }); - } - toBuffer() { - checkCache(this.__CACHE); - return this.data.toBuffer(); - } - toHex() { - checkCache(this.__CACHE); - return this.data.toHex(); - } - toBase64() { - checkCache(this.__CACHE); - return this.data.toBase64(); - } - updateGlobal(updateData) { - this.data.updateGlobal(updateData); - return this; - } - updateInput(inputIndex, updateData) { - if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); - this.data.updateInput(inputIndex, updateData); - if (updateData.nonWitnessUtxo) { - addNonWitnessTxCache( - this.__CACHE, - this.data.inputs[inputIndex], - inputIndex, - ); - } - return this; - } - updateOutput(outputIndex, updateData) { - this.data.updateOutput(outputIndex, updateData); - return this; - } - addUnknownKeyValToGlobal(keyVal) { - this.data.addUnknownKeyValToGlobal(keyVal); - return this; - } - addUnknownKeyValToInput(inputIndex, keyVal) { - this.data.addUnknownKeyValToInput(inputIndex, keyVal); - return this; - } - addUnknownKeyValToOutput(outputIndex, keyVal) { - this.data.addUnknownKeyValToOutput(outputIndex, keyVal); - return this; - } - clearFinalizedInput(inputIndex) { - this.data.clearFinalizedInput(inputIndex); - return this; - } - } - psbt$1.Psbt = Psbt; - /** - * This function is needed to pass to the bip174 base class's fromBuffer. - * It takes the "transaction buffer" portion of the psbt buffer and returns a - * Transaction (From the bip174 library) interface. - */ - const transactionFromBuffer = buffer => new PsbtTransaction(buffer); - /** - * This class implements the Transaction interface from bip174 library. - * It contains a bitcoinjs-lib Transaction object. - */ - class PsbtTransaction { - constructor(buffer = Buffer$m.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { - this.tx = transaction_1$2.Transaction.fromBuffer(buffer); - checkTxEmpty(this.tx); - Object.defineProperty(this, 'tx', { - enumerable: false, - writable: true, - }); - } - getInputOutputCounts() { - return { - inputCount: this.tx.ins.length, - outputCount: this.tx.outs.length, - }; - } - addInput(input) { - if ( - input.hash === undefined || - input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || - typeof input.index !== 'number' - ) { - throw new Error('Error adding input.'); - } - const hash = - typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash, 'hex')) - : input.hash; - this.tx.addInput(hash, input.index, input.sequence); - } - addOutput(output) { - if ( - output.script === undefined || - output.value === undefined || - !isBuffer(output.script) || - typeof output.value !== 'number' - ) { - throw new Error('Error adding output.'); - } - this.tx.addOutput(output.script, output.value); - } - toBuffer() { - return this.tx.toBuffer(); - } - } - function canFinalize(input, script, scriptType) { - switch (scriptType) { - case 'pubkey': - case 'pubkeyhash': - case 'witnesspubkeyhash': - return hasSigs(1, input.partialSig); - case 'multisig': - const p2ms = payments$2.p2ms({ output: script }); - return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); - default: - return false; - } - } - function checkCache(cache) { - if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { - throw new Error('Not BIP174 compliant, can not export'); - } - } - function hasSigs(neededSigs, partialSig, pubkeys) { - if (!partialSig) return false; - let sigs; - if (pubkeys) { - sigs = pubkeys - .map(pkey => { - const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) - .publicKey; - return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); - }) - .filter(v => !!v); - } else { - sigs = partialSig; - } - if (sigs.length > neededSigs) throw new Error('Too many signatures'); - return sigs.length === neededSigs; - } - function isFinalized(input) { - return !!input.finalScriptSig || !!input.finalScriptWitness; - } - function isPaymentFactory(payment) { - return script => { - try { - payment({ output: script }); - return true; - } catch (err) { - return false; - } - }; - } - const isP2MS = isPaymentFactory(payments$2.p2ms); - const isP2PK = isPaymentFactory(payments$2.p2pk); - const isP2PKH = isPaymentFactory(payments$2.p2pkh); - const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); - const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); - const isP2SHScript = isPaymentFactory(payments$2.p2sh); - function bip32DerivationIsMine(root) { - return d => { - if (!d.masterFingerprint.equals(root.fingerprint)) return false; - if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; - return true; - }; - } - function check32Bit(num) { - if ( - typeof num !== 'number' || - num !== Math.floor(num) || - num > 0xffffffff || - num < 0 - ) { - throw new Error('Invalid 32 bit integer'); - } - } - function checkFees(psbt, cache, opts) { - const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); - const vsize = cache.__EXTRACTED_TX.virtualSize(); - const satoshis = feeRate * vsize; - if (feeRate >= opts.maximumFeeRate) { - throw new Error( - `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + - `fees, which is ${feeRate} satoshi per byte for a transaction ` + - `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + - `byte). Use setMaximumFeeRate method to raise your threshold, or ` + - `pass true to the first arg of extractTransaction.`, - ); - } - } - function checkInputsForPartialSig(inputs, action) { - inputs.forEach(input => { - let throws = false; - let pSigs = []; - if ((input.partialSig || []).length === 0) { - if (!input.finalScriptSig && !input.finalScriptWitness) return; - pSigs = getPsigsFromInputFinalScripts(input); - } else { - pSigs = input.partialSig; - } - pSigs.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - const whitelist = []; - const isAnyoneCanPay = - hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; - if (isAnyoneCanPay) whitelist.push('addInput'); - const hashMod = hashType & 0x1f; - switch (hashMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - case transaction_1$2.Transaction.SIGHASH_NONE: - whitelist.push('addOutput'); - whitelist.push('setInputSequence'); - break; - } - if (whitelist.indexOf(action) === -1) { - throws = true; - } - }); - if (throws) { - throw new Error('Can not modify transaction, signatures exist.'); - } - }); - } - function checkPartialSigSighashes(input) { - if (!input.sighashType || !input.partialSig) return; - const { partialSig, sighashType } = input; - partialSig.forEach(pSig => { - const { hashType } = bscript$f.signature.decode(pSig.signature); - if (sighashType !== hashType) { - throw new Error('Signature sighash does not match input sighash type'); - } - }); - } - function checkScriptForPubkey(pubkey, script, action) { - if (!pubkeyInScript(pubkey, script)) { - throw new Error( - `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, - ); - } - } - function checkTxEmpty(tx) { - const isEmpty = tx.ins.every( - input => - input.script && - input.script.length === 0 && - input.witness && - input.witness.length === 0, - ); - if (!isEmpty) { - throw new Error('Format Error: Transaction ScriptSigs are not empty'); - } - } - function checkTxForDupeIns(tx, cache) { - tx.ins.forEach(input => { - checkTxInputCache(cache, input); - }); - } - function checkTxInputCache(cache, input) { - const key = - bufferutils_1$1.reverseBuffer(Buffer$m.from(input.hash)).toString('hex') + - ':' + - input.index; - if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); - cache.__TX_IN_CACHE[key] = 1; - } - function scriptCheckerFactory(payment, paymentScriptName) { - return (inputIndex, scriptPubKey, redeemScript, ioType) => { - const redeemScriptOutput = payment({ - redeem: { output: redeemScript }, - }).output; - if (!scriptPubKey.equals(redeemScriptOutput)) { - throw new Error( - `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, - ); - } - }; - } - const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); - const checkWitnessScript = scriptCheckerFactory( - payments$2.p2wsh, - 'Witness script', - ); - function getTxCacheValue(key, name, inputs, c) { - if (!inputs.every(isFinalized)) - throw new Error(`PSBT must be finalized to calculate ${name}`); - if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; - if (key === '__FEE' && c.__FEE) return c.__FEE; - let tx; - let mustFinalize = true; - if (c.__EXTRACTED_TX) { - tx = c.__EXTRACTED_TX; - mustFinalize = false; - } else { - tx = c.__TX.clone(); - } - inputFinalizeGetAmts(inputs, tx, c, mustFinalize); - if (key === '__FEE_RATE') return c.__FEE_RATE; - else if (key === '__FEE') return c.__FEE; - } - function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { - const scriptType = classifyScript(script); - if (!canFinalize(input, script, scriptType)) - throw new Error(`Can not finalize input #${inputIndex}`); - return prepareFinalScripts( - script, - scriptType, - input.partialSig, - isSegwit, - isP2SH, - isP2WSH, - ); - } - function prepareFinalScripts( - script, - scriptType, - partialSig, - isSegwit, - isP2SH, - isP2WSH, - ) { - let finalScriptSig; - let finalScriptWitness; - // Wow, the payments API is very handy - const payment = getPayment(script, scriptType, partialSig); - const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); - const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); - if (isSegwit) { - if (p2wsh) { - finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); - } else { - finalScriptWitness = witnessStackToScriptWitness(payment.witness); - } - if (p2sh) { - finalScriptSig = p2sh.input; - } - } else { - if (p2sh) { - finalScriptSig = p2sh.input; - } else { - finalScriptSig = payment.input; - } - } - return { - finalScriptSig, - finalScriptWitness, - }; - } - function getHashAndSighashType( - inputs, - inputIndex, - pubkey, - cache, - sighashTypes, - ) { - const input = utils_1.checkForInput(inputs, inputIndex); - const { hash, sighashType, script } = getHashForSig( - inputIndex, - input, - cache, - false, - sighashTypes, - ); - checkScriptForPubkey(pubkey, script, 'sign'); - return { - hash, - sighashType, - }; - } - function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { - const unsignedTx = cache.__TX; - const sighashType = - input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; - if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { - const str = sighashTypeToString(sighashType); - throw new Error( - `Sighash type is not allowed. Retry the sign method passing the ` + - `sighashTypes array of whitelisted types. Sighash type: ${str}`, - ); - } - let hash; - let prevout; - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutHash = unsignedTx.ins[inputIndex].hash; - const utxoHash = nonWitnessUtxoTx.getHash(); - // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout - if (!prevoutHash.equals(utxoHash)) { - throw new Error( - `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, - ); - } - const prevoutIndex = unsignedTx.ins[inputIndex].index; - prevout = nonWitnessUtxoTx.outs[prevoutIndex]; - } else if (input.witnessUtxo) { - prevout = input.witnessUtxo; - } else { - throw new Error('Need a Utxo input item for signing'); - } - const { meaningfulScript, type } = getMeaningfulScript( - prevout.script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { - hash = unsignedTx.hashForWitnessV0( - inputIndex, - meaningfulScript, - prevout.value, - sighashType, - ); - } else if (isP2WPKH(meaningfulScript)) { - // P2WPKH uses the P2PKH template for prevoutScript when signing - const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) - .output; - hash = unsignedTx.hashForWitnessV0( - inputIndex, - signingScript, - prevout.value, - sighashType, - ); - } else { - // non-segwit - if ( - input.nonWitnessUtxo === undefined && - cache.__UNSAFE_SIGN_NONSEGWIT === false - ) - throw new Error( - `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + - `${meaningfulScript.toString('hex')}`, - ); - if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) - console.warn( - 'Warning: Signing non-segwit inputs without the full parent transaction ' + - 'means there is a chance that a miner could feed you incorrect information ' + - 'to trick you into paying large fees. This behavior is the same as the old ' + - 'TransactionBuilder class when signing non-segwit scripts. You are not ' + - 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + - 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + - '*********************', - ); - hash = unsignedTx.hashForSignature( - inputIndex, - meaningfulScript, - sighashType, - ); - } - return { - script: meaningfulScript, - sighashType, - hash, - }; - } - function getPayment(script, scriptType, partialSig) { - let payment; - switch (scriptType) { - case 'multisig': - const sigs = getSortedSigs(script, partialSig); - payment = payments$2.p2ms({ - output: script, - signatures: sigs, - }); - break; - case 'pubkey': - payment = payments$2.p2pk({ - output: script, - signature: partialSig[0].signature, - }); - break; - case 'pubkeyhash': - payment = payments$2.p2pkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - case 'witnesspubkeyhash': - payment = payments$2.p2wpkh({ - output: script, - pubkey: partialSig[0].pubkey, - signature: partialSig[0].signature, - }); - break; - } - return payment; - } - function getPsigsFromInputFinalScripts(input) { - const scriptItems = !input.finalScriptSig - ? [] - : bscript$f.decompile(input.finalScriptSig) || []; - const witnessItems = !input.finalScriptWitness - ? [] - : bscript$f.decompile(input.finalScriptWitness) || []; - return scriptItems - .concat(witnessItems) - .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); - }) - .map(sig => ({ signature: sig })); - } - function getScriptFromInput(inputIndex, input, cache) { - const unsignedTx = cache.__TX; - const res = { - script: null, - isSegwit: false, - isP2SH: false, - isP2WSH: false, - }; - res.isP2SH = !!input.redeemScript; - res.isP2WSH = !!input.witnessScript; - if (input.witnessScript) { - res.script = input.witnessScript; - } else if (input.redeemScript) { - res.script = input.redeemScript; - } else { - if (input.nonWitnessUtxo) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - const prevoutIndex = unsignedTx.ins[inputIndex].index; - res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; - } else if (input.witnessUtxo) { - res.script = input.witnessUtxo.script; - } - } - if (input.witnessScript || isP2WPKH(res.script)) { - res.isSegwit = true; - } - return res; - } - function getSignersFromHD(inputIndex, inputs, hdKeyPair) { - const input = utils_1.checkForInput(inputs, inputIndex); - if (!input.bip32Derivation || input.bip32Derivation.length === 0) { - throw new Error('Need bip32Derivation to sign with HD'); - } - const myDerivations = input.bip32Derivation - .map(bipDv => { - if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { - return bipDv; - } else { - return; - } - }) - .filter(v => !!v); - if (myDerivations.length === 0) { - throw new Error( - 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', - ); - } - const signers = myDerivations.map(bipDv => { - const node = hdKeyPair.derivePath(bipDv.path); - if (!bipDv.pubkey.equals(node.publicKey)) { - throw new Error('pubkey did not match bip32Derivation'); - } - return node; - }); - return signers; - } - function getSortedSigs(script, partialSig) { - const p2ms = payments$2.p2ms({ output: script }); - // for each pubkey in order of p2ms script - return p2ms.pubkeys - .map(pk => { - // filter partialSig array by pubkey being equal - return ( - partialSig.filter(ps => { - return ps.pubkey.equals(pk); - })[0] || {} - ).signature; - // Any pubkey without a match will return undefined - // this last filter removes all the undefined items in the array. - }) - .filter(v => !!v); - } - function scriptWitnessToWitnessStack(buffer) { - let offset = 0; - function readSlice(n) { - offset += n; - return buffer.slice(offset - n, offset); - } - function readVarInt() { - const vi = varuint.decode(buffer, offset); - offset += varuint.decode.bytes; - return vi; - } - function readVarSlice() { - return readSlice(readVarInt()); - } - function readVector() { - const count = readVarInt(); - const vector = []; - for (let i = 0; i < count; i++) vector.push(readVarSlice()); - return vector; - } - return readVector(); - } - function sighashTypeToString(sighashType) { - let text = - sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY - ? 'SIGHASH_ANYONECANPAY | ' - : ''; - const sigMod = sighashType & 0x1f; - switch (sigMod) { - case transaction_1$2.Transaction.SIGHASH_ALL: - text += 'SIGHASH_ALL'; - break; - case transaction_1$2.Transaction.SIGHASH_SINGLE: - text += 'SIGHASH_SINGLE'; - break; - case transaction_1$2.Transaction.SIGHASH_NONE: - text += 'SIGHASH_NONE'; - break; - } - return text; - } - function witnessStackToScriptWitness(witness) { - let buffer = Buffer$m.allocUnsafe(0); - function writeSlice(slice) { - buffer = Buffer$m.concat([buffer, Buffer$m.from(slice)]); - } - function writeVarInt(i) { - const currentLen = buffer.length; - const varintLen = varuint.encodingLength(i); - buffer = Buffer$m.concat([buffer, Buffer$m.allocUnsafe(varintLen)]); - varuint.encode(i, buffer, currentLen); - } - function writeVarSlice(slice) { - writeVarInt(slice.length); - writeSlice(slice); - } - function writeVector(vector) { - writeVarInt(vector.length); - vector.forEach(writeVarSlice); - } - writeVector(witness); - return buffer; - } - function addNonWitnessTxCache(cache, input, inputIndex) { - cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; - const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); - cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; - const self = cache; - const selfIndex = inputIndex; - delete input.nonWitnessUtxo; - Object.defineProperty(input, 'nonWitnessUtxo', { - enumerable: true, - get() { - const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; - const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; - if (buf !== undefined) { - return buf; - } else { - const newBuf = txCache.toBuffer(); - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; - return newBuf; - } - }, - set(data) { - self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; - }, - }); - } - function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { - let inputAmount = 0; - inputs.forEach((input, idx) => { - if (mustFinalize && input.finalScriptSig) - tx.ins[idx].script = input.finalScriptSig; - if (mustFinalize && input.finalScriptWitness) { - tx.ins[idx].witness = scriptWitnessToWitnessStack( - input.finalScriptWitness, - ); - } - if (input.witnessUtxo) { - inputAmount += input.witnessUtxo.value; - } else if (input.nonWitnessUtxo) { - const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); - const vout = tx.ins[idx].index; - const out = nwTx.outs[vout]; - inputAmount += out.value; - } - }); - const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); - const fee = inputAmount - outputAmount; - if (fee < 0) { - throw new Error('Outputs are spending more than Inputs'); - } - const bytes = tx.virtualSize(); - cache.__FEE = fee; - cache.__EXTRACTED_TX = tx; - cache.__FEE_RATE = Math.floor(fee / bytes); - } - function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { - const c = cache.__NON_WITNESS_UTXO_TX_CACHE; - if (!c[inputIndex]) { - addNonWitnessTxCache(cache, input, inputIndex); - } - return c[inputIndex]; - } - function getScriptFromUtxo(inputIndex, input, cache) { - if (input.witnessUtxo !== undefined) { - return input.witnessUtxo.script; - } else if (input.nonWitnessUtxo !== undefined) { - const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( - cache, - input, - inputIndex, - ); - return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; - } else { - throw new Error("Can't find pubkey in input without Utxo data"); - } - } - function pubkeyInInput(pubkey, input, inputIndex, cache) { - const script = getScriptFromUtxo(inputIndex, input, cache); - const { meaningfulScript } = getMeaningfulScript( - script, - inputIndex, - 'input', - input.redeemScript, - input.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function pubkeyInOutput(pubkey, output, outputIndex, cache) { - const script = cache.__TX.outs[outputIndex].script; - const { meaningfulScript } = getMeaningfulScript( - script, - outputIndex, - 'output', - output.redeemScript, - output.witnessScript, - ); - return pubkeyInScript(pubkey, meaningfulScript); - } - function redeemFromFinalScriptSig(finalScript) { - if (!finalScript) return; - const decomp = bscript$f.decompile(finalScript); - if (!decomp) return; - const lastItem = decomp[decomp.length - 1]; - if ( - !isBuffer(lastItem) || - isPubkeyLike(lastItem) || - isSigLike(lastItem) - ) - return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function redeemFromFinalWitnessScript(finalScript) { - if (!finalScript) return; - const decomp = scriptWitnessToWitnessStack(finalScript); - const lastItem = decomp[decomp.length - 1]; - if (isPubkeyLike(lastItem)) return; - const sDecomp = bscript$f.decompile(lastItem); - if (!sDecomp) return; - return lastItem; - } - function isPubkeyLike(buf) { - return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); - } - function isSigLike(buf) { - return bscript$f.isCanonicalScriptSignature(buf); - } - function getMeaningfulScript( - script, - index, - ioType, - redeemScript, - witnessScript, - ) { - const isP2SH = isP2SHScript(script); - const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); - const isP2WSH = isP2WSHScript(script); - if (isP2SH && redeemScript === undefined) - throw new Error('scriptPubkey is P2SH but redeemScript missing'); - if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) - throw new Error( - 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', - ); - let meaningfulScript; - if (isP2SHP2WSH) { - meaningfulScript = witnessScript; - checkRedeemScript(index, script, redeemScript, ioType); - checkWitnessScript(index, redeemScript, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2WSH) { - meaningfulScript = witnessScript; - checkWitnessScript(index, script, witnessScript, ioType); - checkInvalidP2WSH(meaningfulScript); - } else if (isP2SH) { - meaningfulScript = redeemScript; - checkRedeemScript(index, script, redeemScript, ioType); - } else { - meaningfulScript = script; - } - return { - meaningfulScript, - type: isP2SHP2WSH - ? 'p2sh-p2wsh' - : isP2SH - ? 'p2sh' - : isP2WSH - ? 'p2wsh' - : 'raw', - }; - } - function checkInvalidP2WSH(script) { - if (isP2WPKH(script) || isP2SHScript(script)) { - throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); - } - } - function pubkeyInScript(pubkey, script) { - const pubkeyHash = crypto_1$1.hash160(pubkey); - const decompiled = bscript$f.decompile(script); - if (decompiled === null) throw new Error('Unknown script error'); - return decompiled.some(element => { - if (typeof element === 'number') return false; - return element.equals(pubkey) || element.equals(pubkeyHash); - }); - } - function classifyScript(script) { - if (isP2WPKH(script)) return 'witnesspubkeyhash'; - if (isP2PKH(script)) return 'pubkeyhash'; - if (isP2MS(script)) return 'multisig'; - if (isP2PK(script)) return 'pubkey'; - return 'nonstandard'; - } - function range$2(n) { - return [...Array(n).keys()]; - } - - var transaction_builder = {}; - - var classify$1 = {}; - - var multisig$1 = {}; - - var input$b = {}; - - // OP_0 [signatures ...] - Object.defineProperty(input$b, '__esModule', { value: true }); - const bscript$e = script$1; - const script_1$a = script$1; - function partialSignature(value) { - return ( - value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) - ); - } - function check$d(script, allowIncomplete) { - const chunks = bscript$e.decompile(script); - if (chunks.length < 2) return false; - if (chunks[0] !== script_1$a.OPS.OP_0) return false; - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature); - } - return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); - } - input$b.check = check$d; - check$d.toJSON = () => { - return 'multisig input'; - }; - - var output$e = {}; - - // m [pubKeys ...] n OP_CHECKMULTISIG - Object.defineProperty(output$e, '__esModule', { value: true }); - const bscript$d = script$1; - const script_1$9 = script$1; - const types$3 = types$a; - const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 - function check$c(script, allowIncomplete) { - const chunks = bscript$d.decompile(script); - if (chunks.length < 4) return false; - if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; - if (!types$3.Number(chunks[0])) return false; - if (!types$3.Number(chunks[chunks.length - 2])) return false; - const m = chunks[0] - OP_INT_BASE; - const n = chunks[chunks.length - 2] - OP_INT_BASE; - if (m <= 0) return false; - if (n > 16) return false; - if (m > n) return false; - if (n !== chunks.length - 3) return false; - if (allowIncomplete) return true; - const keys = chunks.slice(1, -2); - return keys.every(bscript$d.isCanonicalPubKey); - } - output$e.check = check$c; - check$c.toJSON = () => { - return 'multi-sig output'; - }; - - Object.defineProperty(multisig$1, '__esModule', { value: true }); - const input$a = input$b; - multisig$1.input = input$a; - const output$d = output$e; - multisig$1.output = output$d; - - var nulldata = {}; - - Object.defineProperty(nulldata, '__esModule', { value: true }); - // OP_RETURN {data} - const bscript$c = script$1; - const OPS = bscript$c.OPS; - function check$b(script) { - const buffer = bscript$c.compile(script); - return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; - } - nulldata.check = check$b; - check$b.toJSON = () => { - return 'null data output'; - }; - const output$c = { check: check$b }; - nulldata.output = output$c; - - var pubkey = {}; - - var input$9 = {}; - - // {signature} - Object.defineProperty(input$9, '__esModule', { value: true }); - const bscript$b = script$1; - function check$a(script) { - const chunks = bscript$b.decompile(script); - return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); - } - input$9.check = check$a; - check$a.toJSON = () => { - return 'pubKey input'; - }; - - var output$b = {}; - - // {pubKey} OP_CHECKSIG - Object.defineProperty(output$b, '__esModule', { value: true }); - const bscript$a = script$1; - const script_1$8 = script$1; - function check$9(script) { - const chunks = bscript$a.decompile(script); - return ( - chunks.length === 2 && - bscript$a.isCanonicalPubKey(chunks[0]) && - chunks[1] === script_1$8.OPS.OP_CHECKSIG - ); - } - output$b.check = check$9; - check$9.toJSON = () => { - return 'pubKey output'; - }; - - Object.defineProperty(pubkey, '__esModule', { value: true }); - const input$8 = input$9; - pubkey.input = input$8; - const output$a = output$b; - pubkey.output = output$a; - - var pubkeyhash = {}; - - var input$7 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$7, '__esModule', { value: true }); - const bscript$9 = script$1; - function check$8(script) { - const chunks = bscript$9.decompile(script); - return ( - chunks.length === 2 && - bscript$9.isCanonicalScriptSignature(chunks[0]) && - bscript$9.isCanonicalPubKey(chunks[1]) - ); - } - input$7.check = check$8; - check$8.toJSON = () => { - return 'pubKeyHash input'; - }; - - var output$9 = {}; - - // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - Object.defineProperty(output$9, '__esModule', { value: true }); - const bscript$8 = script$1; - const script_1$7 = script$1; - function check$7(script) { - const buffer = bscript$8.compile(script); - return ( - buffer.length === 25 && - buffer[0] === script_1$7.OPS.OP_DUP && - buffer[1] === script_1$7.OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && - buffer[24] === script_1$7.OPS.OP_CHECKSIG - ); - } - output$9.check = check$7; - check$7.toJSON = () => { - return 'pubKeyHash output'; - }; - - Object.defineProperty(pubkeyhash, '__esModule', { value: true }); - const input$6 = input$7; - pubkeyhash.input = input$6; - const output$8 = output$9; - pubkeyhash.output = output$8; - - var scripthash = {}; - - var input$5 = {}; - - var output$7 = {}; - - // OP_0 {pubKeyHash} - Object.defineProperty(output$7, '__esModule', { value: true }); - const bscript$7 = script$1; - const script_1$6 = script$1; - function check$6(script) { - const buffer = bscript$7.compile(script); - return ( - buffer.length === 22 && - buffer[0] === script_1$6.OPS.OP_0 && - buffer[1] === 0x14 - ); - } - output$7.check = check$6; - check$6.toJSON = () => { - return 'Witness pubKeyHash output'; - }; - - var output$6 = {}; - - // OP_0 {scriptHash} - Object.defineProperty(output$6, '__esModule', { value: true }); - const bscript$6 = script$1; - const script_1$5 = script$1; - function check$5(script) { - const buffer = bscript$6.compile(script); - return ( - buffer.length === 34 && - buffer[0] === script_1$5.OPS.OP_0 && - buffer[1] === 0x20 - ); - } - output$6.check = check$5; - check$5.toJSON = () => { - return 'Witness scriptHash output'; - }; - - // {serialized scriptPubKey script} - Object.defineProperty(input$5, '__esModule', { value: true }); - const bscript$5 = script$1; - const p2ms$1 = multisig$1; - const p2pk$1 = pubkey; - const p2pkh$1 = pubkeyhash; - const p2wpkho = output$7; - const p2wsho = output$6; - function check$4(script, allowIncomplete) { - const chunks = bscript$5.decompile(script); - if (chunks.length < 1) return false; - const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; - const scriptSigChunks = bscript$5.decompile( - bscript$5.compile(chunks.slice(0, -1)), - ); - const redeemScriptChunks = bscript$5.decompile(lastChunk); - // is redeemScript a valid script? - if (!redeemScriptChunks) return false; - // is redeemScriptSig push only? - if (!bscript$5.isPushOnly(scriptSigChunks)) return false; - // is witness? - if (chunks.length === 1) { - return ( - p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) - ); - } - // match types - if ( - p2pkh$1.input.check(scriptSigChunks) && - p2pkh$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2ms$1.input.check(scriptSigChunks, allowIncomplete) && - p2ms$1.output.check(redeemScriptChunks) - ) - return true; - if ( - p2pk$1.input.check(scriptSigChunks) && - p2pk$1.output.check(redeemScriptChunks) - ) - return true; - return false; - } - input$5.check = check$4; - check$4.toJSON = () => { - return 'scriptHash input'; - }; - - var output$5 = {}; - - // OP_HASH160 {scriptHash} OP_EQUAL - Object.defineProperty(output$5, '__esModule', { value: true }); - const bscript$4 = script$1; - const script_1$4 = script$1; - function check$3(script) { - const buffer = bscript$4.compile(script); - return ( - buffer.length === 23 && - buffer[0] === script_1$4.OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === script_1$4.OPS.OP_EQUAL - ); - } - output$5.check = check$3; - check$3.toJSON = () => { - return 'scriptHash output'; - }; - - Object.defineProperty(scripthash, '__esModule', { value: true }); - const input$4 = input$5; - scripthash.input = input$4; - const output$4 = output$5; - scripthash.output = output$4; - - var witnesscommitment = {}; - - var output$3 = {}; - - // OP_RETURN {aa21a9ed} {commitment} - Object.defineProperty(output$3, '__esModule', { value: true }); - const bscript$3 = script$1; - const script_1$3 = script$1; - const types$2 = types$a; - const typeforce$2 = typeforce_1; - const HEADER = Buffer$m.from('aa21a9ed', 'hex'); - function check$2(script) { - const buffer = bscript$3.compile(script); - return ( - buffer.length > 37 && - buffer[0] === script_1$3.OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) - ); - } - output$3.check = check$2; - check$2.toJSON = () => { - return 'Witness commitment output'; - }; - function encode(commitment) { - typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$m.allocUnsafe(36); - HEADER.copy(buffer, 0); - commitment.copy(buffer, 4); - return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); - } - output$3.encode = encode; - function decode(buffer) { - typeforce$2(check$2, buffer); - return bscript$3.decompile(buffer)[1].slice(4, 36); - } - output$3.decode = decode; - - Object.defineProperty(witnesscommitment, '__esModule', { value: true }); - const output$2 = output$3; - witnesscommitment.output = output$2; - - var witnesspubkeyhash = {}; - - var input$3 = {}; - - // {signature} {pubKey} - Object.defineProperty(input$3, '__esModule', { value: true }); - const bscript$2 = script$1; - function isCompressedCanonicalPubKey(pubKey) { - return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; - } - function check$1(script) { - const chunks = bscript$2.decompile(script); - return ( - chunks.length === 2 && - bscript$2.isCanonicalScriptSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) - ); - } - input$3.check = check$1; - check$1.toJSON = () => { - return 'witnessPubKeyHash input'; - }; - - Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); - const input$2 = input$3; - witnesspubkeyhash.input = input$2; - const output$1 = output$7; - witnesspubkeyhash.output = output$1; - - var witnessscripthash = {}; - - var input$1 = {}; - - // {serialized scriptPubKey script} - Object.defineProperty(input$1, '__esModule', { value: true }); - const bscript$1 = script$1; - const typeforce$1 = typeforce_1; - const p2ms = multisig$1; - const p2pk = pubkey; - const p2pkh = pubkeyhash; - function check(chunks, allowIncomplete) { - typeforce$1(typeforce$1.Array, chunks); - if (chunks.length < 1) return false; - const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; - const witnessScriptChunks = bscript$1.decompile(witnessScript); - // is witnessScript a valid script? - if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; - const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); - // match types - if ( - p2pkh.input.check(witnessRawScriptSig) && - p2pkh.output.check(witnessScriptChunks) - ) - return true; - if ( - p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks) - ) - return true; - if ( - p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks) - ) - return true; - return false; - } - input$1.check = check; - check.toJSON = () => { - return 'witnessScriptHash input'; - }; - - Object.defineProperty(witnessscripthash, '__esModule', { value: true }); - const input = input$1; - witnessscripthash.input = input; - const output = output$6; - witnessscripthash.output = output; - - Object.defineProperty(classify$1, '__esModule', { value: true }); - const script_1$2 = script$1; - const multisig = multisig$1; - const nullData = nulldata; - const pubKey = pubkey; - const pubKeyHash = pubkeyhash; - const scriptHash = scripthash; - const witnessCommitment = witnesscommitment; - const witnessPubKeyHash = witnesspubkeyhash; - const witnessScriptHash = witnessscripthash; - const types$1 = { - P2MS: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment', - }; - classify$1.types = types$1; - function classifyOutput(script) { - if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; - if (witnessScriptHash.output.check(script)) return types$1.P2WSH; - if (pubKeyHash.output.check(script)) return types$1.P2PKH; - if (scriptHash.output.check(script)) return types$1.P2SH; - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (multisig.output.check(chunks)) return types$1.P2MS; - if (pubKey.output.check(chunks)) return types$1.P2PK; - if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; - if (nullData.output.check(chunks)) return types$1.NULLDATA; - return types$1.NONSTANDARD; - } - classify$1.output = classifyOutput; - function classifyInput(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; - if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; - if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; - if (pubKey.input.check(chunks)) return types$1.P2PK; - return types$1.NONSTANDARD; - } - classify$1.input = classifyInput; - function classifyWitness(script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - const chunks = script_1$2.decompile(script); - if (!chunks) throw new TypeError('Invalid script'); - if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; - if (witnessScriptHash.input.check(chunks, allowIncomplete)) - return types$1.P2WSH; - return types$1.NONSTANDARD; - } - classify$1.witness = classifyWitness; - - Object.defineProperty(transaction_builder, '__esModule', { value: true }); - const baddress = address$1; - const bufferutils_1 = bufferutils; - const classify = classify$1; - const bcrypto = crypto$2; - const ECPair$1 = ecpair; - const networks$1 = networks$3; - const payments$1 = payments$4; - const bscript = script$1; - const script_1$1 = script$1; - const transaction_1$1 = transaction; - const types = types$a; - const typeforce = typeforce_1; - const SCRIPT_TYPES = classify.types; - const PREVOUT_TYPES = new Set([ - // Raw - 'p2pkh', - 'p2pk', - 'p2wpkh', - 'p2ms', - // P2SH wrapped - 'p2sh-p2pkh', - 'p2sh-p2pk', - 'p2sh-p2wpkh', - 'p2sh-p2ms', - // P2WSH wrapped - 'p2wsh-p2pkh', - 'p2wsh-p2pk', - 'p2wsh-p2ms', - // P2SH-P2WSH wrapper - 'p2sh-p2wsh-p2pkh', - 'p2sh-p2wsh-p2pk', - 'p2sh-p2wsh-p2ms', - ]); - function tfMessage(type, value, message) { - try { - typeforce(type, value); - } catch (err) { - throw new Error(message); - } - } - function txIsString(tx) { - return typeof tx === 'string' || tx instanceof String; - } - function txIsTransaction(tx) { - return tx instanceof transaction_1$1.Transaction; - } - class TransactionBuilder { - // WARNING: maximumFeeRate is __NOT__ to be relied on, - // it's just another potential safety mechanism (safety in-depth) - constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { - this.network = network; - this.maximumFeeRate = maximumFeeRate; - this.__PREV_TX_SET = {}; - this.__INPUTS = []; - this.__TX = new transaction_1$1.Transaction(); - this.__TX.version = 2; - this.__USE_LOW_R = false; - console.warn( - 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + - '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + - 'are available in the transactions-psbt.js integration test file on our ' + - 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + - 'files as well.', - ); - } - static fromTransaction(transaction, network) { - const txb = new TransactionBuilder(network); - // Copy transaction fields - txb.setVersion(transaction.version); - txb.setLockTime(transaction.locktime); - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(txOut => { - txb.addOutput(txOut.script, txOut.value); - }); - // Copy inputs - transaction.ins.forEach(txIn => { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness, - }); - }); - // fix some things not possible through the public API - txb.__INPUTS.forEach((input, i) => { - fixMultisigOrder(input, transaction, i); - }); - return txb; - } - setLowR(setting) { - typeforce(typeforce.maybe(typeforce.Boolean), setting); - if (setting === undefined) { - setting = true; - } - this.__USE_LOW_R = setting; - return setting; - } - setLockTime(locktime) { - typeforce(types.UInt32, locktime); - // if any signatures exist, throw - if ( - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(s => s !== undefined); - }) - ) { - throw new Error('No, this would invalidate signatures'); - } - this.__TX.locktime = locktime; - } - setVersion(version) { - typeforce(types.UInt32, version); - // XXX: this might eventually become more complex depending on what the versions represent - this.__TX.version = version; - } - addInput(txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures'); - } - let value; - // is it a hex string? - if (txIsString(txHash)) { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$m.from(txHash, 'hex')); - // is it a Transaction object? - } else if (txIsTransaction(txHash)) { - const txOut = txHash.outs[vout]; - prevOutScript = txOut.script; - value = txOut.value; - txHash = txHash.getHash(false); - } - return this.__addInputUnsafe(txHash, vout, { - sequence, - prevOutScript, - value, - }); - } - addOutput(scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures'); - } - // Attempt to get a script if it's a base58 or bech32 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); - } - return this.__TX.addOutput(scriptPubKey, value); - } - build() { - return this.__build(false); - } - buildIncomplete() { - return this.__build(true); - } - sign( - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - ) { - trySign( - getSigningData( - this.network, - this.__INPUTS, - this.__needsOutputs.bind(this), - this.__TX, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - this.__USE_LOW_R, - ), - ); - } - __addInputUnsafe(txHash, vout, options) { - if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported'); - } - const prevTxOut = txHash.toString('hex') + ':' + vout; - if (this.__PREV_TX_SET[prevTxOut] !== undefined) - throw new Error('Duplicate TxOut: ' + prevTxOut); - let input = {}; - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []); - } - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value; - } - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - let prevOutType; - if (!input.pubkeys && !input.signatures) { - const expanded = expandOutput(options.prevOutScript); - if (expanded.pubkeys) { - input.pubkeys = expanded.pubkeys; - input.signatures = expanded.signatures; - } - prevOutType = expanded.type; - } - input.prevOutScript = options.prevOutScript; - input.prevOutType = prevOutType || classify.output(options.prevOutScript); - } - const vin = this.__TX.addInput( - txHash, - vout, - options.sequence, - options.scriptSig, - ); - this.__INPUTS[vin] = input; - this.__PREV_TX_SET[prevTxOut] = true; - return vin; - } - __build(allowIncomplete) { - if (!allowIncomplete) { - if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); - if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); - } - const tx = this.__TX.clone(); - // create script signatures from inputs - this.__INPUTS.forEach((input, i) => { - if (!input.prevOutType && !allowIncomplete) - throw new Error('Transaction is not complete'); - const result = build(input.prevOutType, input, allowIncomplete); - if (!result) { - if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) - throw new Error('Unknown input type'); - if (!allowIncomplete) throw new Error('Not enough information'); - return; - } - tx.setInputScript(i, result.input); - tx.setWitness(i, result.witness); - }); - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees'); - } - } - return tx; - } - __canModifyInputs() { - return this.__INPUTS.every(input => { - if (!input.signatures) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return ( - (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 - ); - }); - }); - } - __needsOutputs(signingHashType) { - if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { - return this.__TX.outs.length === 0; - } - // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs - // .build() will fail, but .buildIncomplete() is OK - return ( - this.__TX.outs.length === 0 && - this.__INPUTS.some(input => { - if (!input.signatures) return false; - return input.signatures.some(signature => { - if (!signature) return false; // no signature, no issue - const hashType = signatureHashType(signature); - if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs - return true; // SIGHASH_* does care - }); - }) - ); - } - __canModifyOutputs() { - const nInputs = this.__TX.ins.length; - const nOutputs = this.__TX.outs.length; - return this.__INPUTS.every(input => { - if (input.signatures === undefined) return true; - return input.signatures.every(signature => { - if (!signature) return true; - const hashType = signatureHashType(signature); - const hashTypeMod = hashType & 0x1f; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; - if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs; - } - return false; - }); - }); - } - __overMaximumFees(bytes) { - // not all inputs will have .value defined - const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); - const fee = incoming - outgoing; - const feeRate = fee / bytes; - return feeRate > this.maximumFeeRate; - } - } - transaction_builder.TransactionBuilder = TransactionBuilder; - function expandInput(scriptSig, witnessStack, type, scriptPubKey) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {}; - if (!type) { - let ssType = classify.input(scriptSig, true); - let wsType = classify.witness(witnessStack, true); - if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; - if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; - type = ssType || wsType; - } - switch (type) { - case SCRIPT_TYPES.P2WPKH: { - const { output, pubkey, signature } = payments$1.p2wpkh({ - witness: witnessStack, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WPKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PKH: { - const { output, pubkey, signature } = payments$1.p2pkh({ - input: scriptSig, - }); - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2PKH, - pubkeys: [pubkey], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2PK: { - const { signature } = payments$1.p2pk({ input: scriptSig }); - return { - prevOutType: SCRIPT_TYPES.P2PK, - pubkeys: [undefined], - signatures: [signature], - }; - } - case SCRIPT_TYPES.P2MS: { - const { m, pubkeys, signatures } = payments$1.p2ms( - { - input: scriptSig, - output: scriptPubKey, - }, - { allowIncomplete: true }, - ); - return { - prevOutType: SCRIPT_TYPES.P2MS, - pubkeys, - signatures, - maxSignatures: m, - }; - } - } - if (type === SCRIPT_TYPES.P2SH) { - const { output, redeem } = payments$1.p2sh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - const expanded = expandInput( - redeem.input, - redeem.witness, - outputType, - redeem.output, - ); - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2SH, - redeemScript: redeem.output, - redeemScriptType: expanded.prevOutType, - witnessScript: expanded.witnessScript, - witnessScriptType: expanded.witnessScriptType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - if (type === SCRIPT_TYPES.P2WSH) { - const { output, redeem } = payments$1.p2wsh({ - input: scriptSig, - witness: witnessStack, - }); - const outputType = classify.output(redeem.output); - let expanded; - if (outputType === SCRIPT_TYPES.P2WPKH) { - expanded = expandInput(redeem.input, redeem.witness, outputType); - } else { - expanded = expandInput( - bscript.compile(redeem.witness), - [], - outputType, - redeem.output, - ); - } - if (!expanded.prevOutType) return {}; - return { - prevOutScript: output, - prevOutType: SCRIPT_TYPES.P2WSH, - witnessScript: redeem.output, - witnessScriptType: expanded.prevOutType, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - }; - } - return { - prevOutType: SCRIPT_TYPES.NONSTANDARD, - prevOutScript: scriptSig, - }; - } - // could be done in expandInput, but requires the original Transaction for hashForSignature - function fixMultisigOrder(input, transaction, vin) { - if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) - return; - if (input.pubkeys.length === input.signatures.length) return; - const unmatched = input.signatures.concat(); - input.signatures = input.pubkeys.map(pubKey => { - const keyPair = ECPair$1.fromPublicKey(pubKey); - let match; - // check for a signature - unmatched.some((signature, i) => { - // skip if undefined || OP_0 - if (!signature) return false; - // TODO: avoid O(n) hashForSignature - const parsed = bscript.signature.decode(signature); - const hash = transaction.hashForSignature( - vin, - input.redeemScript, - parsed.hashType, - ); - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false; - // remove matched signature from unmatched - unmatched[i] = undefined; - match = signature; - return true; - }); - return match; - }); - } - function expandOutput(script, ourPubKey) { - typeforce(types.Buffer, script); - const type = classify.output(script); - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const pkh1 = payments$1.p2pkh({ output: script }).hash; - const pkh2 = bcrypto.hash160(ourPubKey); - if (!pkh1.equals(pkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2WPKH: { - if (!ourPubKey) return { type }; - // does our hash160(pubKey) match the output scripts? - const wpkh1 = payments$1.p2wpkh({ output: script }).hash; - const wpkh2 = bcrypto.hash160(ourPubKey); - if (!wpkh1.equals(wpkh2)) return { type }; - return { - type, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2PK: { - const p2pk = payments$1.p2pk({ output: script }); - return { - type, - pubkeys: [p2pk.pubkey], - signatures: [undefined], - }; - } - case SCRIPT_TYPES.P2MS: { - const p2ms = payments$1.p2ms({ output: script }); - return { - type, - pubkeys: p2ms.pubkeys, - signatures: p2ms.pubkeys.map(() => undefined), - maxSignatures: p2ms.m, - }; - } - } - return { type }; - } - function prepareInput(input, ourPubKey, redeemScript, witnessScript) { - if (redeemScript && witnessScript) { - const p2wsh = payments$1.p2wsh({ - redeem: { output: witnessScript }, - }); - const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); - // enforces P2SH(P2WSH(...)) - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); - return { - redeemScript, - redeemScriptType: SCRIPT_TYPES.P2WSH, - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (redeemScript) { - const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); - if (input.prevOutScript) { - let p2shAlt; - try { - p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); - } catch (e) { - throw new Error('PrevOutScript must be P2SH'); - } - if (!p2sh.hash.equals(p2shAlt.hash)) - throw new Error('Redeem script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2sh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as redeemScript (' + - bscript.toASM(redeemScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = redeemScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - redeemScript, - redeemScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2SH, - prevOutScript: p2sh.output, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (witnessScript) { - const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); - if (input.prevOutScript) { - const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); - if (!p2wsh.hash.equals(p2wshAlt.hash)) - throw new Error('Witness script inconsistent with prevOutScript'); - } - const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported as witnessScript (' + - bscript.toASM(witnessScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - const signScript = witnessScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) - throw new Error('P2WSH(P2WPKH) is a consensus failure'); - return { - witnessScript, - witnessScriptType: expanded.type, - prevOutType: SCRIPT_TYPES.P2WSH, - prevOutScript: p2wsh.output, - hasWitness: true, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - if (input.prevOutType && input.prevOutScript) { - // embedded scripts are not possible without extra information - if (input.prevOutType === SCRIPT_TYPES.P2SH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', - ); - if (input.prevOutType === SCRIPT_TYPES.P2WSH) - throw new Error( - 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', - ); - if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); - const expanded = expandOutput(input.prevOutScript, ourPubKey); - if (!expanded.pubkeys) - throw new Error( - expanded.type + - ' not supported (' + - bscript.toASM(input.prevOutScript) + - ')', - ); - if (input.signatures && input.signatures.some(x => x !== undefined)) { - expanded.signatures = input.signatures; - } - let signScript = input.prevOutScript; - if (expanded.type === SCRIPT_TYPES.P2WPKH) { - signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; - } - return { - prevOutType: expanded.type, - prevOutScript: input.prevOutScript, - hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, - signScript, - signType: expanded.type, - pubkeys: expanded.pubkeys, - signatures: expanded.signatures, - maxSignatures: expanded.maxSignatures, - }; - } - const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; - return { - prevOutType: SCRIPT_TYPES.P2PKH, - prevOutScript, - hasWitness: false, - signScript: prevOutScript, - signType: SCRIPT_TYPES.P2PKH, - pubkeys: [ourPubKey], - signatures: [undefined], - }; - } - function build(type, input, allowIncomplete) { - const pubkeys = input.pubkeys || []; - let signatures = input.signatures || []; - switch (type) { - case SCRIPT_TYPES.P2PKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2WPKH: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); - } - case SCRIPT_TYPES.P2PK: { - if (pubkeys.length === 0) break; - if (signatures.length === 0) break; - return payments$1.p2pk({ signature: signatures[0] }); - } - case SCRIPT_TYPES.P2MS: { - const m = input.maxSignatures; - if (allowIncomplete) { - signatures = signatures.map(x => x || script_1$1.OPS.OP_0); - } else { - signatures = signatures.filter(x => x); - } - // if the transaction is not not complete (complete), or if signatures.length === m, validate - // otherwise, the number of OP_0's may be >= m, so don't validate (boo) - const validate = !allowIncomplete || m === signatures.length; - return payments$1.p2ms( - { m, pubkeys, signatures }, - { allowIncomplete, validate }, - ); - } - case SCRIPT_TYPES.P2SH: { - const redeem = build(input.redeemScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2sh({ - redeem: { - output: redeem.output || input.redeemScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - case SCRIPT_TYPES.P2WSH: { - const redeem = build(input.witnessScriptType, input, allowIncomplete); - if (!redeem) return; - return payments$1.p2wsh({ - redeem: { - output: input.witnessScript, - input: redeem.input, - witness: redeem.witness, - }, - }); - } - } - } - function canSign(input) { - return ( - input.signScript !== undefined && - input.signType !== undefined && - input.pubkeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubkeys.length && - input.pubkeys.length > 0 && - (input.hasWitness === false || input.value !== undefined) - ); - } - function signatureHashType(buffer) { - return buffer.readUInt8(buffer.length - 1); - } - function checkSignArgs(inputs, signParams) { - if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { - throw new TypeError( - `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, - ); - } - tfMessage( - typeforce.Number, - signParams.vin, - `sign must include vin parameter as Number (input index)`, - ); - tfMessage( - types.Signer, - signParams.keyPair, - `sign must include keyPair parameter as Signer interface`, - ); - tfMessage( - typeforce.maybe(typeforce.Number), - signParams.hashType, - `sign hashType parameter must be a number`, - ); - const prevOutType = (inputs[signParams.vin] || []).prevOutType; - const posType = signParams.prevOutScriptType; - switch (posType) { - case 'p2pkh': - if (prevOutType && prevOutType !== 'pubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2pk': - if (prevOutType && prevOutType !== 'pubkey') { - throw new TypeError( - `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wpkh': - if (prevOutType && prevOutType !== 'witnesspubkeyhash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2ms': - if (prevOutType && prevOutType !== 'multisig') { - throw new TypeError( - `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2sh-p2wpkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2ms': - case 'p2sh-p2pk': - case 'p2sh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.value(undefined), - signParams.witnessScript, - `${posType} requires NO witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires redeemScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.witnessValue, - `${posType} requires NO witnessValue`, - ); - break; - case 'p2wsh-p2ms': - case 'p2wsh-p2pk': - case 'p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'witnessscripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.value(undefined), - signParams.redeemScript, - `${posType} requires NO redeemScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessValue`, - ); - break; - case 'p2sh-p2wsh-p2ms': - case 'p2sh-p2wsh-p2pk': - case 'p2sh-p2wsh-p2pkh': - if (prevOutType && prevOutType !== 'scripthash') { - throw new TypeError( - `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, - ); - } - tfMessage( - typeforce.Buffer, - signParams.witnessScript, - `${posType} requires witnessScript`, - ); - tfMessage( - typeforce.Buffer, - signParams.redeemScript, - `${posType} requires witnessScript`, - ); - tfMessage( - types.Satoshi, - signParams.witnessValue, - `${posType} requires witnessScript`, - ); - break; - } - } - function trySign({ - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR, - }) { - // enforce in order signing of public keys - let signed = false; - for (const [i, pubKey] of input.pubkeys.entries()) { - if (!ourPubKey.equals(pubKey)) continue; - if (input.signatures[i]) throw new Error('Signature already exists'); - // TODO: add tests - if (ourPubKey.length !== 33 && input.hasWitness) { - throw new Error( - 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', - ); - } - const signature = keyPair.sign(signatureHash, useLowR); - input.signatures[i] = bscript.signature.encode(signature, hashType); - signed = true; - } - if (!signed) throw new Error('Key pair cannot sign for this input'); - } - function getSigningData( - network, - inputs, - needsOutputs, - tx, - signParams, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - useLowR, - ) { - let vin; - if (typeof signParams === 'number') { - console.warn( - 'DEPRECATED: TransactionBuilder sign method arguments ' + - 'will change in v6, please use the TxbSignArg interface', - ); - vin = signParams; - } else if (typeof signParams === 'object') { - checkSignArgs(inputs, signParams); - ({ - vin, - keyPair, - redeemScript, - hashType, - witnessValue, - witnessScript, - } = signParams); - } else { - throw new TypeError( - 'TransactionBuilder sign first arg must be TxbSignArg or number', - ); - } - if (keyPair === undefined) { - throw new Error('sign requires keypair'); - } - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== network) - throw new TypeError('Inconsistent network'); - if (!inputs[vin]) throw new Error('No input at index: ' + vin); - hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; - if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); - const input = inputs[vin]; - // if redeemScript was previously provided, enforce consistency - if ( - input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript) - ) { - throw new Error('Inconsistent redeemScript'); - } - const ourPubKey = - keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) - throw new Error('Input did not match witnessValue'); - typeforce(types.Satoshi, witnessValue); - input.value = witnessValue; - } - if (!canSign(input)) { - const prepared = prepareInput( - input, - ourPubKey, - redeemScript, - witnessScript, - ); - // updates inline - Object.assign(input, prepared); - } - if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); - } - // ready to sign - let signatureHash; - if (input.hasWitness) { - signatureHash = tx.hashForWitnessV0( - vin, - input.signScript, - input.value, - hashType, - ); - } else { - signatureHash = tx.hashForSignature(vin, input.signScript, hashType); - } - return { - input, - ourPubKey, - keyPair, - signatureHash, - hashType, - useLowR: !!useLowR, - }; - } - - Object.defineProperty(src$2, '__esModule', { value: true }); - const bip32 = src$1; - src$2.bip32 = bip32; - const address = address$1; - src$2.address = address; - const crypto = crypto$2; - var crypto_1 = src$2.crypto = crypto; - const ECPair = ecpair; - src$2.ECPair = ECPair; - const networks = networks$3; - src$2.networks = networks; - const payments = payments$4; - src$2.payments = payments; - const script = script$1; - src$2.script = script; - var block_1 = block; - src$2.Block = block_1.Block; - var psbt_1 = psbt$1; - src$2.Psbt = psbt_1.Psbt; - var script_1 = script$1; - src$2.opcodes = script_1.OPS; - var transaction_1 = transaction; - src$2.Transaction = transaction_1.Transaction; - var transaction_builder_1 = transaction_builder; - src$2.TransactionBuilder = transaction_builder_1.TransactionBuilder; - - var re$b = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION$1 = '2.0.0'; - - const MAX_LENGTH$5 = 256; - const MAX_SAFE_INTEGER$3 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH$1 = 16; - - var constants$1 = { - SEMVER_SPEC_VERSION: SEMVER_SPEC_VERSION$1, - MAX_LENGTH: MAX_LENGTH$5, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$3, - MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1 - }; - - const debug$7 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1$1 = debug$7; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants$1; - const debug = debug_1$1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$b, re$b.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts$1 = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$9 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts$1.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1$1 = parseOptions$9; - - const numeric$1 = /^[0-9]+$/; - const compareIdentifiers$3 = (a, b) => { - const anum = numeric$1.test(a); - const bnum = numeric$1.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers$1 = (a, b) => compareIdentifiers$3(b, a); - - var identifiers$1 = { - compareIdentifiers: compareIdentifiers$3, - rcompareIdentifiers: rcompareIdentifiers$1 - }; - - const debug$6 = debug_1$1; - const { MAX_LENGTH: MAX_LENGTH$4, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$2 } = constants$1; - const { re: re$a, t: t$9 } = re$b.exports; - - const parseOptions$8 = parseOptions_1$1; - const { compareIdentifiers: compareIdentifiers$2 } = identifiers$1; - class SemVer$t { - constructor (version, options) { - options = parseOptions$8(options); - - if (version instanceof SemVer$t) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$4) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$4} characters` - ) - } - - debug$6('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$a[t$9.LOOSE] : re$a[t$9.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER$2 || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER$2 || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER$2 || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER$2) { - return num - } - } - return id - }); - } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug$6('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$t)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$t(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); - } - - return ( - compareIdentifiers$2(this.major, other.major) || - compareIdentifiers$2(this.minor, other.minor) || - compareIdentifiers$2(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$t)) { - other = new SemVer$t(other, this.options); - } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$6('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers$2(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } - } - - var semver$3 = SemVer$t; - - const {MAX_LENGTH: MAX_LENGTH$3} = constants$1; - const { re: re$9, t: t$8 } = re$b.exports; - const SemVer$s = semver$3; - - const parseOptions$7 = parseOptions_1$1; - const parse$b = (version, options) => { - options = parseOptions$7(options); - - if (version instanceof SemVer$s) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH$3) { - return null - } - - const r = options.loose ? re$9[t$8.LOOSE] : re$9[t$8.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$s(version, options) - } catch (er) { - return null - } - }; - - var parse_1$1 = parse$b; - - const parse$a = parse_1$1; - const valid$3 = (version, options) => { - const v = parse$a(version, options); - return v ? v.version : null - }; - var valid_1$1 = valid$3; - - const parse$9 = parse_1$1; - const clean$1 = (version, options) => { - const s = parse$9(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1$1 = clean$1; - - const SemVer$r = semver$3; - - const inc$1 = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$r(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1$1 = inc$1; - - const SemVer$q = semver$3; - const compare$l = (a, b, loose) => - new SemVer$q(a, loose).compare(new SemVer$q(b, loose)); - - var compare_1$1 = compare$l; - - const compare$k = compare_1$1; - const eq$5 = (a, b, loose) => compare$k(a, b, loose) === 0; - var eq_1$1 = eq$5; - - const parse$8 = parse_1$1; - const eq$4 = eq_1$1; - - const diff$1 = (version1, version2) => { - if (eq$4(version1, version2)) { - return null - } else { - const v1 = parse$8(version1); - const v2 = parse$8(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } - }; - var diff_1$1 = diff$1; - - const SemVer$p = semver$3; - const major$1 = (a, loose) => new SemVer$p(a, loose).major; - var major_1$1 = major$1; - - const SemVer$o = semver$3; - const minor$1 = (a, loose) => new SemVer$o(a, loose).minor; - var minor_1$1 = minor$1; - - const SemVer$n = semver$3; - const patch$1 = (a, loose) => new SemVer$n(a, loose).patch; - var patch_1$1 = patch$1; - - const parse$7 = parse_1$1; - const prerelease$1 = (version, options) => { - const parsed = parse$7(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1$1 = prerelease$1; - - const compare$j = compare_1$1; - const rcompare$1 = (a, b, loose) => compare$j(b, a, loose); - var rcompare_1$1 = rcompare$1; - - const compare$i = compare_1$1; - const compareLoose$1 = (a, b) => compare$i(a, b, true); - var compareLoose_1$1 = compareLoose$1; - - const SemVer$m = semver$3; - const compareBuild$5 = (a, b, loose) => { - const versionA = new SemVer$m(a, loose); - const versionB = new SemVer$m(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1$1 = compareBuild$5; - - const compareBuild$4 = compareBuild_1$1; - const sort$1 = (list, loose) => list.sort((a, b) => compareBuild$4(a, b, loose)); - var sort_1$1 = sort$1; - - const compareBuild$3 = compareBuild_1$1; - const rsort$1 = (list, loose) => list.sort((a, b) => compareBuild$3(b, a, loose)); - var rsort_1$1 = rsort$1; - - const compare$h = compare_1$1; - const gt$7 = (a, b, loose) => compare$h(a, b, loose) > 0; - var gt_1$1 = gt$7; - - const compare$g = compare_1$1; - const lt$5 = (a, b, loose) => compare$g(a, b, loose) < 0; - var lt_1$1 = lt$5; - - const compare$f = compare_1$1; - const neq$3 = (a, b, loose) => compare$f(a, b, loose) !== 0; - var neq_1$1 = neq$3; - - const compare$e = compare_1$1; - const gte$5 = (a, b, loose) => compare$e(a, b, loose) >= 0; - var gte_1$1 = gte$5; - - const compare$d = compare_1$1; - const lte$5 = (a, b, loose) => compare$d(a, b, loose) <= 0; - var lte_1$1 = lte$5; - - const eq$3 = eq_1$1; - const neq$2 = neq_1$1; - const gt$6 = gt_1$1; - const gte$4 = gte_1$1; - const lt$4 = lt_1$1; - const lte$4 = lte_1$1; - - const cmp$3 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq$3(a, b, loose) - - case '!=': - return neq$2(a, b, loose) - - case '>': - return gt$6(a, b, loose) - - case '>=': - return gte$4(a, b, loose) - - case '<': - return lt$4(a, b, loose) - - case '<=': - return lte$4(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1$1 = cmp$3; - - const SemVer$l = semver$3; - const parse$6 = parse_1$1; - const {re: re$8, t: t$7} = re$b.exports; - - const coerce$1 = (version, options) => { - if (version instanceof SemVer$l) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$8[t$7.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$8[t$7.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$8[t$7.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - // leave it in a clean state - re$8[t$7.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null - - return parse$6(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1$1 = coerce$1; - - var yallist = Yallist$1; - - Yallist$1.Node = Node$1; - Yallist$1.create = Yallist$1; - - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); - } - - self.tail = null; - self.head = null; - self.length = 0; - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); - } - } - - return self - } - - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - - var next = node.next; - var prev = node.prev; - - if (next) { - next.prev = prev; - } - - if (prev) { - prev.next = next; - } - - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } - - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; - - return next - }; - - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } - - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; - - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - - if (node.list) { - node.list.removeNode(node); - } - - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; - } - - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; - - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; - - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } - - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } - - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res - }; - - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; - - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; - - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; - - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; - - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res - }; - - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } - - return acc - }; - - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } - - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } - - return acc - }; - - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; - - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr - }; - - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret - }; - - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } - - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } - - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } - - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } - - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; - - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this - }; - - function insert (self, node, value) { - var inserted = node === self.head ? - new Node$1(value, null, node, self) : - new Node$1(value, node, node.next, self); - - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } - - self.length++; - - return inserted - } - - function push (self, item) { - self.tail = new Node$1(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; - } - self.length++; - } - - function unshift (self, item) { - self.head = new Node$1(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; - } - - function Node$1 (value, prev, next, list) { - if (!(this instanceof Node$1)) { - return new Node$1(value, prev, next, list) - } - - this.list = list; - this.value = value; - - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } - - if (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } - } - - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} - - // A linked list to keep track of recently-used-ness - const Yallist = yallist; - - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); - - const naiveLength = () => 1; - - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; - - if (!options) - options = {}; - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; - - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA; - trim(this); - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); - } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; - } - } - - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); - } - - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } - - const node = this[CACHE].get(key); - const item = node.value; - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } - - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true - } - - const hit = new Entry(key, value, len, now, maxAge); - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); - - return false - } - - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) - } - - get (key) { - return get$1(this, key, true) - } - - peek (key) { - return get$1(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null - - del(this, node); - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)); - } - - load (arr) { - // reset the cache - this.reset(); - - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get$1(this, key, false)); - } - } - - const get$1 = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); - } - } - return hit.value - } - }; - - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; - - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; - } - } - }; - - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); - - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); - } - }; - - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; - } - } - - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; - - var lruCache = LRUCache; - - // hoisted class for cyclic dependency - class Range$l { - constructor (range, options) { - options = parseOptions$6(options); - - if (range instanceof Range$l) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$l(range.raw, options) - } - } - - if (range instanceof Comparator$7) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this - } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet$1(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny$1(c[0])) { - this.set = [c]; - break - } - } - } - } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache$1.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$7[t$6.HYPHENRANGELOOSE] : re$7[t$6.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace$1(this.options.includePrerelease)); - debug$5('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$7[t$6.COMPARATORTRIM], comparatorTrimReplace$1); - debug$5('comparator trim', range, re$7[t$6.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$7[t$6.TILDETRIM], tildeTrimReplace$1); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$7[t$6.CARETTRIM], caretTrimReplace$1); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$7[t$6.COMPARATORLOOSE] : re$7[t$6.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator$1(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0$1(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$7(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet$1(comp)) - return [comp] - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache$1.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$l)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable$1(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable$1(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer$k(version, this.options); - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet$1(this.set[i], version, this.options)) { - return true - } - } - return false - } - } - var range$1 = Range$l; - - const LRU$1 = lruCache; - const cache$1 = new LRU$1({ max: 1000 }); - - const parseOptions$6 = parseOptions_1$1; - const Comparator$7 = comparator$1; - const debug$5 = debug_1$1; - const SemVer$k = semver$3; - const { - re: re$7, - t: t$6, - comparatorTrimReplace: comparatorTrimReplace$1, - tildeTrimReplace: tildeTrimReplace$1, - caretTrimReplace: caretTrimReplace$1 - } = re$b.exports; - - const isNullSet$1 = c => c.value === '<0.0.0-0'; - const isAny$1 = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable$1 = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator$1 = (comp, options) => { - debug$5('comp', comp, options); - comp = replaceCarets$1(comp, options); - debug$5('caret', comp); - comp = replaceTildes$1(comp, options); - debug$5('tildes', comp); - comp = replaceXRanges$1(comp, options); - debug$5('xrange', comp); - comp = replaceStars$1(comp, options); - debug$5('stars', comp); - return comp - }; - - const isX$1 = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde$1(comp, options) - }).join(' '); - - const replaceTilde$1 = (comp, options) => { - const r = options.loose ? re$7[t$6.TILDELOOSE] : re$7[t$6.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$5('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; - } - - debug$5('tilde return', ret); - return ret - }) - }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets$1 = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret$1(comp, options) - }).join(' '); - - const replaceCaret$1 = (comp, options) => { - debug$5('caret', comp, options); - const r = options.loose ? re$7[t$6.CARETLOOSE] : re$7[t$6.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$5('caret', comp, _, M, m, p, pr); - let ret; - - if (isX$1(M)) { - ret = ''; - } else if (isX$1(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX$1(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$5('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$5('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$5('caret return', ret); - return ret - }) - }; - - const replaceXRanges$1 = (comp, options) => { - debug$5('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange$1(comp, options) - }).join(' ') - }; - - const replaceXRange$1 = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$7[t$6.XRANGELOOSE] : re$7[t$6.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$5('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX$1(M); - const xm = xM || isX$1(m); - const xp = xm || isX$1(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; - } - - debug$5('xRange return', ret); - - return ret - }) - }; - - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars$1 = (comp, options) => { - debug$5('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$7[t$6.STAR], '') - }; - - const replaceGTE0$1 = (comp, options) => { - debug$5('replaceGTE0', comp, options); - return comp.trim() - .replace(re$7[options.includePrerelease ? t$6.GTE0PRE : t$6.GTE0], '') - }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace$1 = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX$1(fM)) { - from = ''; - } else if (isX$1(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX$1(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX$1(tM)) { - to = ''; - } else if (isX$1(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX$1(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() - }; - - const testSet$1 = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$5(set[i].semver); - if (set[i].semver === Comparator$7.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true - }; - - const ANY$5 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$6 { - static get ANY () { - return ANY$5 - } - constructor (comp, options) { - options = parseOptions$5(options); - - if (comp instanceof Comparator$6) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } - } - - debug$4('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$5) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } - - debug$4('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re$6[t$5.COMPARATORLOOSE] : re$6[t$5.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$5; - } else { - this.semver = new SemVer$j(m[2], this.options.loose); - } - } - - toString () { - return this.value - } - - test (version) { - debug$4('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$5 || version === ANY$5) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer$j(version, this.options); - } catch (er) { - return false - } - } - - return cmp$2(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$6)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$k(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$k(this.value, options).test(comp.semver) - } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp$2(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp$2(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } - } - - var comparator$1 = Comparator$6; - - const parseOptions$5 = parseOptions_1$1; - const {re: re$6, t: t$5} = re$b.exports; - const cmp$2 = cmp_1$1; - const debug$4 = debug_1$1; - const SemVer$j = semver$3; - const Range$k = range$1; - - const Range$j = range$1; - const satisfies$7 = (version, range, options) => { - try { - range = new Range$j(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1$1 = satisfies$7; - - const Range$i = range$1; - - // Mostly just for testing and legacy API reasons - const toComparators$1 = (range, options) => - new Range$i(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1$1 = toComparators$1; - - const SemVer$i = semver$3; - const Range$h = range$1; - - const maxSatisfying$1 = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$h(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$i(max, options); - } - } - }); - return max - }; - var maxSatisfying_1$1 = maxSatisfying$1; - - const SemVer$h = semver$3; - const Range$g = range$1; - const minSatisfying$1 = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$g(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$h(min, options); - } - } - }); - return min - }; - var minSatisfying_1$1 = minSatisfying$1; - - const SemVer$g = semver$3; - const Range$f = range$1; - const gt$5 = gt_1$1; - - const minVersion$1 = (range, loose) => { - range = new Range$f(range, loose); - - let minver = new SemVer$g('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$g('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$g(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$5(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$5(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null - }; - var minVersion_1$1 = minVersion$1; - - const Range$e = range$1; - const validRange$1 = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$e(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid$2 = validRange$1; - - const SemVer$f = semver$3; - const Comparator$5 = comparator$1; - const {ANY: ANY$4} = Comparator$5; - const Range$d = range$1; - const satisfies$6 = satisfies_1$1; - const gt$4 = gt_1$1; - const lt$3 = lt_1$1; - const lte$3 = lte_1$1; - const gte$3 = gte_1$1; - - const outside$5 = (version, range, hilo, options) => { - version = new SemVer$f(version, options); - range = new Range$d(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt$4; - ltefn = lte$3; - ltfn = lt$3; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt$3; - ltefn = gte$3; - ltfn = gt$4; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$6(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let high = null; - let low = null; - - comparators.forEach((comparator) => { - if (comparator.semver === ANY$4) { - comparator = new Comparator$5('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true - }; - - var outside_1$1 = outside$5; - - // Determine if version is greater than all the versions possible in the range. - const outside$4 = outside_1$1; - const gtr$1 = (version, range, options) => outside$4(version, range, '>', options); - var gtr_1$1 = gtr$1; - - const outside$3 = outside_1$1; - // Determine if version is less than all the versions possible in the range - const ltr$1 = (version, range, options) => outside$3(version, range, '<', options); - var ltr_1$1 = ltr$1; - - const Range$c = range$1; - const intersects$1 = (r1, r2, options) => { - r1 = new Range$c(r1, options); - r2 = new Range$c(r2, options); - return r1.intersects(r2) - }; - var intersects_1$1 = intersects$1; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$5 = satisfies_1$1; - const compare$c = compare_1$1; - var simplify$1 = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$c(a, b, options)); - for (const version of v) { - const included = satisfies$5(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; - } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; - - const Range$b = range$1; - const Comparator$4 = comparator$1; - const { ANY: ANY$3 } = Comparator$4; - const satisfies$4 = satisfies_1$1; - const compare$b = compare_1$1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset$1 = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range$b(sub, options); - dom = new Range$b(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset$1(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; - - const simpleSubset$1 = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY$3) { - if (dom.length === 1 && dom[0].semver === ANY$3) - return true - else if (options.includePrerelease) - sub = [ new Comparator$4('>=0.0.0-0') ]; - else - sub = [ new Comparator$4('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY$3) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator$4('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT$1(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT$1(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare$b(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies$4(eq, String(gt), options)) - return null - - if (lt && !satisfies$4(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies$4(eq, String(c), options)) - return false - } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT$1(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies$4(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT$1(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies$4(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false - - return true - }; - - // >=1.2.3 is lower than >1.2.3 - const higherGT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT$1 = (a, b, options) => { - if (!a) - return b - const comp = compare$b(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; - - var subset_1$1 = subset$1; - - // just pre-load all the stuff that index.js lazily exports - const internalRe$1 = re$b.exports; - var semver$2 = { - re: internalRe$1.re, - src: internalRe$1.src, - tokens: internalRe$1.t, - SEMVER_SPEC_VERSION: constants$1.SEMVER_SPEC_VERSION, - SemVer: semver$3, - compareIdentifiers: identifiers$1.compareIdentifiers, - rcompareIdentifiers: identifiers$1.rcompareIdentifiers, - parse: parse_1$1, - valid: valid_1$1, - clean: clean_1$1, - inc: inc_1$1, - diff: diff_1$1, - major: major_1$1, - minor: minor_1$1, - patch: patch_1$1, - prerelease: prerelease_1$1, - compare: compare_1$1, - rcompare: rcompare_1$1, - compareLoose: compareLoose_1$1, - compareBuild: compareBuild_1$1, - sort: sort_1$1, - rsort: rsort_1$1, - gt: gt_1$1, - lt: lt_1$1, - eq: eq_1$1, - neq: neq_1$1, - gte: gte_1$1, - lte: lte_1$1, - cmp: cmp_1$1, - coerce: coerce_1$1, - Comparator: comparator$1, - Range: range$1, - satisfies: satisfies_1$1, - toComparators: toComparators_1$1, - maxSatisfying: maxSatisfying_1$1, - minSatisfying: minSatisfying_1$1, - minVersion: minVersion_1$1, - validRange: valid$2, - outside: outside_1$1, - gtr: gtr_1$1, - ltr: ltr_1$1, - intersects: intersects_1$1, - simplifyRange: simplify$1, - subset: subset_1$1, - }; - - /* - * Bitcoin BIP32 path helpers - * (C) 2016 Alex Beregszaszi - */ - - const HARDENED = 0x80000000; - - var BIPPath = function (path) { - if (!Array.isArray(path)) { - throw new Error('Input must be an Array') - } - if (path.length === 0) { - throw new Error('Path must contain at least one level') - } - for (var i = 0; i < path.length; i++) { - if (typeof path[i] !== 'number') { - throw new Error('Path element is not a number') - } - } - this.path = path; - }; - - BIPPath.validatePathArray = function (path) { - try { - BIPPath.fromPathArray(path); - return true - } catch (e) { - return false - } - }; - - BIPPath.validateString = function (text, reqRoot) { - try { - BIPPath.fromString(text, reqRoot); - return true - } catch (e) { - return false - } - }; - - BIPPath.fromPathArray = function (path) { - return new BIPPath(path) - }; - - BIPPath.fromString = function (text, reqRoot) { - // skip the root - if (/^m\//i.test(text)) { - text = text.slice(2); - } else if (reqRoot) { - throw new Error('Root element is required') - } - - var path = text.split('/'); - var ret = new Array(path.length); - for (var i = 0; i < path.length; i++) { - var tmp = /(\d+)([hH\']?)/.exec(path[i]); - if (tmp === null) { - throw new Error('Invalid input') - } - ret[i] = parseInt(tmp[1], 10); - - if (ret[i] >= HARDENED) { - throw new Error('Invalid child index') - } - - if (tmp[2] === 'h' || tmp[2] === 'H' || tmp[2] === '\'') { - ret[i] += HARDENED; - } else if (tmp[2].length != 0) { - throw new Error('Invalid modifier') - } - } - return new BIPPath(ret) - }; - - BIPPath.prototype.toPathArray = function () { - return this.path - }; - - BIPPath.prototype.toString = function (noRoot, oldStyle) { - var ret = new Array(this.path.length); - for (var i = 0; i < this.path.length; i++) { - var tmp = this.path[i]; - if (tmp & HARDENED) { - ret[i] = (tmp & ~HARDENED) + (oldStyle ? 'h' : '\''); - } else { - ret[i] = tmp; - } - } - return (noRoot ? '' : 'm/') + ret.join('/') - }; - - BIPPath.prototype.inspect = function () { - return 'BIPPath <' + this.toString() + '>' - }; - - var bip32Path = BIPPath; - - function pathElementsToBuffer(paths) { - var buffer = Buffer$m.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } - function bip32asBuffer(path) { - var pathElements = !path ? [] : pathStringToArray(path); - return pathElementsToBuffer(pathElements); - } - function pathArrayToString(pathElements) { - // Limitation: bippath can't handle and empty path. It shouldn't affect us - // right now, but might in the future. - // TODO: Fix support for empty path. - return bip32Path.fromPathArray(pathElements).toString(); - } - function pathStringToArray(path) { - return bip32Path.fromString(path).toPathArray(); - } - function pubkeyFromXpub(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return xpubBuf.slice(xpubBuf.length - 33); - } - function getXpubComponents(xpub) { - var xpubBuf = bs58check$5.decode(xpub); - return { - chaincode: xpubBuf.slice(13, 13 + 32), - pubkey: xpubBuf.slice(xpubBuf.length - 33), - version: xpubBuf.readUInt32BE(0) - }; - } - function hardenedPathOf(pathElements) { - for (var i = pathElements.length - 1; i >= 0; i--) { - if (pathElements[i] >= 0x80000000) { - return pathElements.slice(0, i + 1); - } - } - return []; - } - - var BufferWriter = /** @class */ (function () { - function BufferWriter() { - this.bufs = []; - } - BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$m.alloc(alloc); - fn(b); - this.bufs.push(b); - }; - BufferWriter.prototype.writeUInt8 = function (i) { - this.write(1, function (b) { return b.writeUInt8(i, 0); }); - }; - BufferWriter.prototype.writeInt32 = function (i) { - this.write(4, function (b) { return b.writeInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt32 = function (i) { - this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); - }; - BufferWriter.prototype.writeUInt64 = function (i) { - this.write(8, function (b) { return b.writeBigUInt64LE(i, 0); }); - }; - BufferWriter.prototype.writeVarInt = function (i) { - this.bufs.push(varuintBitcoin.encode(i)); - }; - BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$m.from(slice)); - }; - BufferWriter.prototype.writeVarSlice = function (slice) { - this.writeVarInt(slice.length); - this.writeSlice(slice); - }; - BufferWriter.prototype.buffer = function () { - return Buffer$m.concat(this.bufs); - }; - return BufferWriter; - }()); - var BufferReader = /** @class */ (function () { - function BufferReader(buffer, offset) { - if (offset === void 0) { offset = 0; } - this.buffer = buffer; - this.offset = offset; - } - BufferReader.prototype.available = function () { - return this.buffer.length - this.offset; - }; - BufferReader.prototype.readUInt8 = function () { - var result = this.buffer.readUInt8(this.offset); - this.offset++; - return result; - }; - BufferReader.prototype.readInt32 = function () { - var result = this.buffer.readInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt32 = function () { - var result = this.buffer.readUInt32LE(this.offset); - this.offset += 4; - return result; - }; - BufferReader.prototype.readUInt64 = function () { - var result = this.buffer.readBigUInt64LE(this.offset); - this.offset += 8; - return result; - }; - BufferReader.prototype.readVarInt = function () { - var vi = varuintBitcoin.decode(this.buffer, this.offset); - this.offset += varuintBitcoin.decode.bytes; - return vi; - }; - BufferReader.prototype.readSlice = function (n) { - if (this.buffer.length < this.offset + n) { - throw new Error("Cannot read slice out of bounds"); - } - var result = this.buffer.slice(this.offset, this.offset + n); - this.offset += n; - return result; - }; - BufferReader.prototype.readVarSlice = function () { - return this.readSlice(this.readVarInt()); - }; - BufferReader.prototype.readVector = function () { - var count = this.readVarInt(); - var vector = []; - for (var i = 0; i < count; i++) - vector.push(this.readVarSlice()); - return vector; - }; - return BufferReader; - }()); - - function hashPublicKey(buffer) { - return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); - } - - var __read$3 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var Merkle = /** @class */ (function () { - function Merkle(leaves, hasher) { - if (hasher === void 0) { hasher = crypto_1.sha256; } - this.leaves = leaves; - this.h = hasher; - var nodes = this.calculateRoot(leaves); - this.rootNode = nodes.root; - this.leafNodes = nodes.leaves; - } - Merkle.prototype.getRoot = function () { - return this.rootNode.hash; - }; - Merkle.prototype.size = function () { - return this.leaves.length; - }; - Merkle.prototype.getLeaves = function () { - return this.leaves; - }; - Merkle.prototype.getLeafHash = function (index) { - return this.leafNodes[index].hash; - }; - Merkle.prototype.getProof = function (index) { - if (index >= this.leaves.length) - throw Error("Index out of bounds"); - return proveNode(this.leafNodes[index]); - }; - Merkle.prototype.calculateRoot = function (leaves) { - var n = leaves.length; - if (n == 0) { - return { - root: new Node(undefined, undefined, Buffer$m.alloc(32, 0)), - leaves: [] - }; - } - if (n == 1) { - var newNode = new Node(undefined, undefined, leaves[0]); - return { root: newNode, leaves: [newNode] }; - } - var leftCount = highestPowerOf2LessThan(n); - var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); - var rightBranch = this.calculateRoot(leaves.slice(leftCount)); - var leftChild = leftBranch.root; - var rightChild = rightBranch.root; - var hash = this.hashNode(leftChild.hash, rightChild.hash); - var node = new Node(leftChild, rightChild, hash); - leftChild.parent = node; - rightChild.parent = node; - return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; - }; - Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$m.concat([Buffer$m.of(1), left, right])); - }; - return Merkle; - }()); - function hashLeaf(buf, hashFunction) { - if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$m.of(0), buf, hashFunction); - } - function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$m.concat([bufA, bufB])); - } - var Node = /** @class */ (function () { - function Node(left, right, hash) { - this.leftChild = left; - this.rightChild = right; - this.hash = hash; - } - Node.prototype.isLeaf = function () { - return this.leftChild == undefined; - }; - return Node; - }()); - function proveNode(node) { - if (!node.parent) { - return []; - } - if (node.parent.leftChild == node) { - if (!node.parent.rightChild) { - throw new Error("Expected right child to exist"); - } - return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); - } - else { - if (!node.parent.leftChild) { - throw new Error("Expected left child to exist"); - } - return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); - } - } - function highestPowerOf2LessThan(n) { - if (n < 2) { - throw Error("Expected n >= 2"); - } - if (isPowerOf2(n)) { - return n / 2; - } - return 1 << Math.floor(Math.log2(n)); - } - function isPowerOf2(n) { - return (n & (n - 1)) == 0; - } - - var WalletPolicy = /** @class */ (function () { - /** - * For now, we only support default descriptor templates. - */ - function WalletPolicy(descriptorTemplate, key) { - this.descriptorTemplate = descriptorTemplate; - this.keys = [key]; - } - WalletPolicy.prototype.getWalletId = function () { - // wallet_id (sha256 of the wallet serialization), - return crypto_1.sha256(this.serialize()); - }; - WalletPolicy.prototype.serialize = function () { - var keyBuffers = this.keys.map(function (k) { - return Buffer$m.from(k, "ascii"); - }); - var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); - var buf = new BufferWriter(); - buf.writeUInt8(0x01); // wallet type (policy map) - buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$m.from(this.descriptorTemplate, "ascii")); - buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); - return buf.buffer(); - }; - return WalletPolicy; - }()); - function createKey$1(masterFingerprint, path, xpub) { - var accountPath = pathArrayToString(path); - return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; - } - - function extract(psbt) { - var _a, _b; - var tx = new BufferWriter(); - tx.writeUInt32(psbt.getGlobalTxVersion()); - var isSegwit = !!psbt.getInputWitnessUtxo(0); - if (isSegwit) { - tx.writeSlice(Buffer$m.of(0, 1)); - } - var inputCount = psbt.getGlobalInputCount(); - tx.writeVarInt(inputCount); - var witnessWriter = new BufferWriter(); - for (var i = 0; i < inputCount; i++) { - tx.writeSlice(psbt.getInputPreviousTxid(i)); - tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$m.of()); - tx.writeUInt32(psbt.getInputSequence(i)); - if (isSegwit) { - witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); - } - } - var outputCount = psbt.getGlobalOutputCount(); - tx.writeVarInt(outputCount); - for (var i = 0; i < outputCount; i++) { - tx.writeUInt64(BigInt(psbt.getOutputAmount(i))); - tx.writeVarSlice(psbt.getOutputScript(i)); - } - tx.writeSlice(witnessWriter.buffer()); - tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); - return tx.buffer(); - } - - var __extends$3 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __assign$6 = (undefined && undefined.__assign) || function () { - __assign$6 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$6.apply(this, arguments); - }; - var psbtGlobal; - (function (psbtGlobal) { - psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; - psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; - psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; - psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; - psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; - psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; - })(psbtGlobal || (psbtGlobal = {})); - var psbtIn; - (function (psbtIn) { - psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; - psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; - psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; - psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; - psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; - psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; - psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; - psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; - psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; - psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; - psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; - psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; - })(psbtIn || (psbtIn = {})); - var psbtOut; - (function (psbtOut) { - psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; - psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; - psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; - psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; - psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; - })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$m.of(0x70, 0x73, 0x62, 0x74, 0xff); - var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); - function NoSuchEntry() { - return _super !== null && _super.apply(this, arguments) || this; - } - return NoSuchEntry; - }(Error)); - var PsbtV2 = /** @class */ (function () { - function PsbtV2() { - this.globalMap = new Map(); - this.inputMaps = []; - this.outputMaps = []; - } - PsbtV2.prototype.setGlobalTxVersion = function (version) { - this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); - }; - PsbtV2.prototype.getGlobalTxVersion = function () { - return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { - this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); - }; - PsbtV2.prototype.getGlobalFallbackLocktime = function () { - var _a; - return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); - }; - PsbtV2.prototype.setGlobalInputCount = function (inputCount) { - this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); - }; - PsbtV2.prototype.getGlobalInputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { - this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); - }; - PsbtV2.prototype.getGlobalOutputCount = function () { - return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); - }; - PsbtV2.prototype.setGlobalTxModifiable = function (byte) { - this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); - }; - PsbtV2.prototype.getGlobalTxModifiable = function () { - return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); - }; - PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { - this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); - }; - PsbtV2.prototype.getGlobalPsbtVersion = function () { - return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); - }; - PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { - this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); - }; - PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); - }; - PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { - var buf = new BufferWriter(); - buf.writeSlice(amount); - buf.writeVarSlice(scriptPubKey); - this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); - }; - PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { - var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); - if (!utxo) - return undefined; - var buf = new BufferReader(utxo); - return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; - }; - PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { - this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); - }; - PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { - return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); - }; - PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { - this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { - if (pubkey.length != 33) - throw new Error("Invalid pubkey length: " + pubkey.length); - this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); - if (!buf) - return undefined; - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); - }; - PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); - }; - PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { - this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); - }; - PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); - }; - PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { - this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); - }; - PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); - }; - PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { - this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); - }; - PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { - return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); - }; - PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { - this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); - }; - PsbtV2.prototype.getInputSequence = function (inputIndex) { - var _a, _b; - return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); - }; - PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { - this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); - }; - PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { - return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); - }; - PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { - if (pubkey.length != 32) - throw new Error("Invalid pubkey length: " + pubkey.length); - var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); - this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { - var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { - return this.getKeyDatas(this.inputMaps[inputIndex], keyType); - }; - PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { - this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); - }; - PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); - }; - PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { - this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); - }; - PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); - return this.decodeBip32Derivation(buf); - }; - PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { - this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); - }; - PsbtV2.prototype.getOutputAmount = function (outputIndex) { - return Number(this.getOutput(outputIndex, psbtOut.AMOUNT, b()).readBigUInt64LE(0)); - }; - PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { - this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); - }; - PsbtV2.prototype.getOutputScript = function (outputIndex) { - return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); - }; - PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { - var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); - this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); - }; - PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { - var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); - return this.decodeTapBip32Derivation(buf); - }; - PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { - var _this = this; - var map = this.inputMaps[inputIndex]; - map.forEach(function (_v, k, m) { - if (_this.isKeyType(k, keyTypes)) { - m["delete"](k); - } - }); - }; - PsbtV2.prototype.copy = function (to) { - this.copyMap(this.globalMap, to.globalMap); - this.copyMaps(this.inputMaps, to.inputMaps); - this.copyMaps(this.outputMaps, to.outputMaps); - }; - PsbtV2.prototype.copyMaps = function (from, to) { - var _this = this; - from.forEach(function (m, index) { - var to_index = new Map(); - _this.copyMap(m, to_index); - to[index] = to_index; - }); - }; - PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$m.from(v)); }); - }; - PsbtV2.prototype.serialize = function () { - var buf = new BufferWriter(); - buf.writeSlice(Buffer$m.of(0x70, 0x73, 0x62, 0x74, 0xff)); - serializeMap(buf, this.globalMap); - this.inputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - this.outputMaps.forEach(function (map) { - serializeMap(buf, map); - }); - return buf.buffer(); - }; - PsbtV2.prototype.deserialize = function (psbt) { - var buf = new BufferReader(psbt); - if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { - throw new Error("Invalid magic bytes"); - } - while (this.readKeyPair(this.globalMap, buf)) - ; - for (var i = 0; i < this.getGlobalInputCount(); i++) { - this.inputMaps[i] = new Map(); - while (this.readKeyPair(this.inputMaps[i], buf)) - ; - } - for (var i = 0; i < this.getGlobalOutputCount(); i++) { - this.outputMaps[i] = new Map(); - while (this.readKeyPair(this.outputMaps[i], buf)) - ; - } - }; - PsbtV2.prototype.readKeyPair = function (map, buf) { - var keyLen = buf.readVarInt(); - if (keyLen == 0) { - return false; - } - var keyType = buf.readUInt8(); - var keyData = buf.readSlice(keyLen - 1); - var value = buf.readVarSlice(); - set(map, keyType, keyData, value); - return true; - }; - PsbtV2.prototype.getKeyDatas = function (map, keyType) { - var _this = this; - var result = []; - map.forEach(function (_v, k) { - if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$m.from(k.substring(2), "hex")); - } - }); - return result; - }; - PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$m.from(hexKey.substring(0, 2), "hex").readUInt8(0); - return keyTypes.some(function (k) { return k == keyType; }); - }; - PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$m.of()); - this.globalMap.set(key.toString(), value); - }; - PsbtV2.prototype.getGlobal = function (keyType) { - return get(this.globalMap, keyType, b(), false); - }; - PsbtV2.prototype.getGlobalOptional = function (keyType) { - return get(this.globalMap, keyType, b(), true); - }; - PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.inputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getMap = function (index, maps) { - if (maps[index]) { - return maps[index]; - } - return (maps[index] = new Map()); - }; - PsbtV2.prototype.getInput = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { - return get(this.inputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { - set(this.getMap(index, this.outputMaps), keyType, keyData, value); - }; - PsbtV2.prototype.getOutput = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, false); - }; - PsbtV2.prototype.getOutputOptional = function (index, keyType, keyData) { - return get(this.outputMaps[index], keyType, keyData, true); - }; - PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { - var buf = new BufferWriter(); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - return this.readBip32Derivation(buf); - }; - PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { - buf.writeSlice(masterFingerprint); - path.forEach(function (element) { - buf.writeUInt32(element); - }); - }; - PsbtV2.prototype.readBip32Derivation = function (buf) { - var masterFingerprint = buf.readSlice(4); - var path = []; - while (buf.offset < buf.buffer.length) { - path.push(buf.readUInt32()); - } - return { masterFingerprint: masterFingerprint, path: path }; - }; - PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { - var buf = new BufferWriter(); - buf.writeVarInt(hashes.length); - hashes.forEach(function (h) { - buf.writeSlice(h); - }); - this.writeBip32Derivation(buf, masterFingerprint, path); - return buf.buffer(); - }; - PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { - var buf = new BufferReader(buffer); - var hashCount = buf.readVarInt(); - var hashes = []; - for (var i = 0; i < hashCount; i++) { - hashes.push(buf.readSlice(32)); - } - var deriv = this.readBip32Derivation(buf); - return __assign$6({ hashes: hashes }, deriv); - }; - return PsbtV2; - }()); - function get(map, keyType, keyData, acceptUndefined) { - if (!map) - throw Error("No such map"); - var key = new Key(keyType, keyData); - var value = map.get(key.toString()); - if (!value) { - if (acceptUndefined) { - return undefined; - } - throw new NoSuchEntry(key.toString()); - } - // Make sure to return a copy, to protect the underlying data. - return Buffer$m.from(value); - } - var Key = /** @class */ (function () { - function Key(keyType, keyData) { - this.keyType = keyType; - this.keyData = keyData; - } - Key.prototype.toString = function () { - var buf = new BufferWriter(); - this.toBuffer(buf); - return buf.buffer().toString("hex"); - }; - Key.prototype.serialize = function (buf) { - buf.writeVarInt(1 + this.keyData.length); - this.toBuffer(buf); - }; - Key.prototype.toBuffer = function (buf) { - buf.writeUInt8(this.keyType); - buf.writeSlice(this.keyData); - }; - return Key; - }()); - var KeyPair = /** @class */ (function () { - function KeyPair(key, value) { - this.key = key; - this.value = value; - } - KeyPair.prototype.serialize = function (buf) { - this.key.serialize(buf); - buf.writeVarSlice(this.value); - }; - return KeyPair; - }()); - function createKey(buf) { - return new Key(buf.readUInt8(0), buf.slice(1)); - } - function serializeMap(buf, map) { - for (var k in map.keys) { - var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$m.from(k, "hex")), value); - keyPair.serialize(buf); - } - buf.writeUInt8(0); - } - function b() { - return Buffer$m.of(); - } - function set(map, keyType, keyData, value) { - var key = new Key(keyType, keyData); - map.set(key.toString(), value); - } - function uint32LE(n) { - var b = Buffer$m.alloc(4); - b.writeUInt32LE(n, 0); - return b; - } - function uint64LE(n) { - var b = Buffer$m.alloc(8); - b.writeBigUInt64LE(BigInt(n), 0); - return b; - } - function varint(n) { - var b = new BufferWriter(); - b.writeVarInt(n); - return b.buffer(); - } - function fromVarint(buf) { - return new BufferReader(buf).readVarInt(); - } - - /** - * - * @param psbt The psbt with all signatures added as partial sigs, either through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG - */ - function finalize(psbt) { - // First check that each input has a signature - var inputCount = psbt.getGlobalInputCount(); - for (var i = 0; i < inputCount; i++) { - var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); - var taprootSig = psbt.getInputTapKeySig(i); - if (legacyPubkeys.length == 0 && !taprootSig) { - throw Error("No signature for input " + i + " present"); - } - if (legacyPubkeys.length > 0) { - if (legacyPubkeys.length > 1) { - throw Error("Expected exactly one signature, got " + legacyPubkeys.length); - } - if (taprootSig) { - throw Error("Both taproot and non-taproot signatures present."); - } - var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); - var redeemScript = psbt.getInputRedeemScript(i); - var isWrappedSegwit = !!redeemScript; - var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); - if (!signature) - throw new Error("Expected partial signature for input " + i); - if (isSegwitV0) { - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(2); - witnessBuf.writeVarInt(signature.length); - witnessBuf.writeSlice(signature); - witnessBuf.writeVarInt(legacyPubkeys[0].length); - witnessBuf.writeSlice(legacyPubkeys[0]); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - if (isWrappedSegwit) { - if (!redeemScript || redeemScript.length == 0) { - throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); - } - var scriptSigBuf = new BufferWriter(); - // Push redeemScript length - scriptSigBuf.writeUInt8(redeemScript.length); - scriptSigBuf.writeSlice(redeemScript); - psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); - } - } - else { - // Legacy input - var scriptSig = new BufferWriter(); - writePush(scriptSig, signature); - writePush(scriptSig, legacyPubkeys[0]); - psbt.setInputFinalScriptsig(i, scriptSig.buffer()); - } - } - else { - // Taproot input - var signature = psbt.getInputTapKeySig(i); - if (!signature) { - throw Error("No taproot signature found"); - } - if (signature.length != 64 && signature.length != 65) { - throw Error("Unexpected length of schnorr signature."); - } - var witnessBuf = new BufferWriter(); - witnessBuf.writeVarInt(1); - witnessBuf.writeVarSlice(signature); - psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); - } - clearFinalizedInput(psbt, i); - } - } - function clearFinalizedInput(psbt, inputIndex) { - var keyTypes = [ - psbtIn.BIP32_DERIVATION, - psbtIn.PARTIAL_SIG, - psbtIn.TAP_BIP32_DERIVATION, - psbtIn.TAP_KEY_SIG, - ]; - var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); - var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); - if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { - // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. - // Segwit v1 doesn't have NON_WITNESS_UTXO set. - // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 - keyTypes.push(psbtIn.NON_WITNESS_UTXO); - } - psbt.deleteInputEntries(inputIndex, keyTypes); - } - function writePush(buf, data) { - if (data.length <= 75) { - buf.writeUInt8(data.length); - } - else if (data.length <= 256) { - buf.writeUInt8(76); - buf.writeUInt8(data.length); - } - else if (data.length <= 256 * 256) { - buf.writeUInt8(77); - var b = Buffer$m.alloc(2); - b.writeUInt16LE(data.length, 0); - buf.writeSlice(b); - } - buf.writeSlice(data); - } - - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); - } - function createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$m.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer$m.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer$m.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; - } - - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$m.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$m.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$m.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$m.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$m.concat([ - inputBuffer, - input.prevout, - Buffer$m.from([0x00]), - input.sequence, - ]) - : Buffer$m.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$m.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$m.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$m.alloc(0), - transaction.extraData || Buffer$m.alloc(0), - ]); - } - return Buffer$m.concat([ - transaction.version, - timestamp ? timestamp : Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - useWitness ? Buffer$m.from("0001", "hex") : Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); - } - - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUAL = 0x87; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; - - var __assign$5 = (undefined && undefined.__assign) || function () { - __assign$5 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$5.apply(this, arguments); - }; - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; - function canSupportApp(appAndVersion) { - return (newSupportedApps.includes(appAndVersion.name) && - semver$2.major(appAndVersion.version) >= 2); - } - var BtcNew = /** @class */ (function () { - function BtcNew(client) { - this.client = client; - } - BtcNew.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; - case 1: - xpub = _b.sent(); - xpubComponents = getXpubComponents(xpub); - if (xpubComponents.version != xpubVersion) { - throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); - } - return [2 /*return*/, xpub]; - } - }); - }); - }; - BtcNew.prototype.getWalletPublicKey = function (path, opts) { - var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { - var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { - switch (_c.label) { - case 0: - pathElements = pathStringToArray(path); - return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; - case 1: - xpub = _c.sent(); - display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; - return [4 /*yield*/, this.getWalletAddress(pathElements, accountTypeFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; - case 2: - address = _c.sent(); - components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$m.from(js.pointCompress(components.pubkey, false)); - return [2 /*return*/, { - publicKey: uncompressedPubkey.toString("hex"), - bitcoinAddress: address, - chainCode: components.chaincode.toString("hex") - }]; - } - }); - }); - }; - /** - * Get an address for the specified path. - * - * If display is true, we must get the address from the device, which would require - * us to determine WalletPolicy. This requires two *extra* queries to the device, one - * for the account xpub and one for master key fingerprint. - * - * If display is false we *could* generate the address ourselves, but chose to - * get it from the device to save development time. However, it shouldn't take - * more than a few hours to implement local address generation. - * - * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no - * way to get the address from the device. In this case we have to create it - * ourselves, but we don't at this time, and instead return an empty ("") address. - */ - BtcNew.prototype.getWalletAddress = function (pathElements, accountType, display) { - return __awaiter$e(this, void 0, void 0, function () { - var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - accountPath = hardenedPathOf(pathElements); - if (accountPath.length + 2 != pathElements.length) { - return [2 /*return*/, ""]; - } - return [4 /*yield*/, this.client.getPubkey(false, accountPath)]; - case 1: - accountXpub = _a.sent(); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 2: - masterFingerprint = _a.sent(); - policy = new WalletPolicy(accountType, createKey$1(masterFingerprint, accountPath, accountXpub)); - changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$m.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; - } - }); - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending segwit v1+ outptus - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { - var psbt, accountType, masterFp, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (arg.inputs.length == 0) { - throw Error("No inputs"); - } - psbt = new PsbtV2(); - accountType = accountTypeFromArg(arg); - psbt.setGlobalTxVersion(2); - if (arg.lockTime) { - psbt.setGlobalFallbackLocktime(arg.lockTime); - } - psbt.setGlobalInputCount(arg.inputs.length); - psbt.setGlobalPsbtVersion(2); - psbt.setGlobalTxVersion(2); - return [4 /*yield*/, this.client.getMasterFingerprint()]; - case 1: - masterFp = _a.sent(); - accountXpub = ""; - accountPath = []; - i = 0; - _a.label = 2; - case 2: - if (!(i < arg.inputs.length)) return [3 /*break*/, 7]; - pathElems = pathStringToArray(arg.associatedKeysets[i]); - if (!(accountXpub == "")) return [3 /*break*/, 4]; - // We assume all inputs belong to the same account so we set - // the account xpub and path based on the first input. - accountPath = pathElems.slice(0, -2); - return [4 /*yield*/, this.client.getPubkey(false, accountPath)]; - case 3: - accountXpub = _a.sent(); - _a.label = 4; - case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp)]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - i++; - return [3 /*break*/, 2]; - case 7: - outputsConcat = Buffer$m.from(arg.outputScriptHex, "hex"); - outputsBufferReader = new BufferReader(outputsConcat); - outputCount = outputsBufferReader.readVarInt(); - return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; - case 8: - changeData = _a.sent(); - psbt.setGlobalOutputCount(outputCount); - changeFound = !changeData; - for (i = 0; i < outputCount; i++) { - amount = Number(outputsBufferReader.readUInt64()); - outputScript = outputsBufferReader.readVarSlice(); - isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.script); - if (isChange) { - changeFound = true; - changePath = pathStringToArray(arg.changePath); - pubkey = changeData.pubkey; - if (accountType == AccountType.p2pkh) { - psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); - } - else if (accountType == AccountType.p2wpkh) { - psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); - } - else if (accountType == AccountType.p2wpkhWrapped) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - psbt.setOutputRedeemScript(i, changeData.redeemScript); - psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); - } - else if (accountType == AccountType.p2tr) { - psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath); - } - } - psbt.setOutputAmount(i, amount); - psbt.setOutputScript(i, outputScript); - } - if (!changeFound) { - throw new Error("Change script not found among outputs! " + - (changeData === null || changeData === void 0 ? void 0 : changeData.script.toString("hex"))); - } - key = createKey$1(masterFp, accountPath, accountXpub); - p = new WalletPolicy(accountType, key); - return [4 /*yield*/, this.signPsbt(psbt, p)]; - case 9: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { - var pathElems, i, xpub, pubkey, script; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - if (!path) - return [2 /*return*/, undefined]; - pathElems = pathStringToArray(path); - // Make sure path is in our account, otherwise something fishy is probably - // going on. - for (i = 0; i < accountPath.length; i++) { - if (accountPath[i] != pathElems[i]) { - throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); - } - } - return [4 /*yield*/, this.client.getPubkey(false, pathElems)]; - case 1: - xpub = _a.sent(); - pubkey = pubkeyFromXpub(xpub); - if (accountType == AccountType.p2tr) { - pubkey = pubkey.slice(1); - } - script = outputScriptOf(pubkey, accountType); - return [2 /*return*/, __assign$5(__assign$5({}, script), { pubkey: pubkey })]; - } - }); - }); - }; - BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP) { - return __awaiter$e(this, void 0, void 0, function () { - var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentOutput, expectedRedeemScript, xonly; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: - inputTx = input[0]; - spentOutputIndex = input[1]; - redeemScript = input[2]; - sequence = input[3]; - if (sequence) { - psbt.setInputSequence(i, sequence); - } - inputTxBuffer = serializeTransaction(inputTx, true); - inputTxid = crypto_1.hash256(inputTxBuffer); - return [4 /*yield*/, this.client.getPubkey(false, pathElements)]; - case 1: - xpubBase58 = _a.sent(); - pubkey = pubkeyFromXpub(xpubBase58); - if (!inputTx.outputs) - throw Error("Missing outputs array in transaction to sign"); - spentOutput = inputTx.outputs[spentOutputIndex]; - if (accountType == AccountType.p2pkh) { - psbt.setInputNonWitnessUtxo(i, inputTxBuffer); - psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); - } - else if (accountType == AccountType.p2wpkh) { - psbt.setInputNonWitnessUtxo(i, inputTxBuffer); - psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); - psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); - } - else if (accountType == AccountType.p2wpkhWrapped) { - psbt.setInputNonWitnessUtxo(i, inputTxBuffer); - psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); - if (!redeemScript) { - throw new Error("Missing redeemScript for p2wpkhWrapped input"); - } - expectedRedeemScript = createRedeemScript(pubkey); - if (redeemScript != expectedRedeemScript.toString("hex")) { - throw new Error("Unexpected redeemScript"); - } - psbt.setInputRedeemScript(i, expectedRedeemScript); - psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); - } - else if (accountType == AccountType.p2tr) { - xonly = pubkey.slice(1); - psbt.setInputTapBip32Derivation(i, xonly, [], masterFP, pathElements); - psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); - } - psbt.setInputPreviousTxId(i, inputTxid); - psbt.setInputOutputIndex(i, spentOutputIndex); - return [2 /*return*/]; - } - }); - }); - }; - BtcNew.prototype.signPsbt = function (psbt, walletPolicy) { - return __awaiter$e(this, void 0, void 0, function () { - var sigs, serializedTx; - return __generator$e(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$m.alloc(32, 0))]; - case 1: - sigs = _a.sent(); - sigs.forEach(function (v, k) { - // Note: Looking at BIP32 derivation does not work in the generic case. - // some inputs might not have a BIP32-derived pubkey. - var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); - var pubkey; - if (pubkeys.length != 1) { - // No legacy BIP32_DERIVATION, assume we're using taproot. - pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); - if (pubkey.length == 0) { - throw Error("Missing pubkey derivation for input " + k); - } - psbt.setInputTapKeySig(k, v); - } - else { - pubkey = pubkeys[0]; - psbt.setInputPartialSig(k, pubkey, v); - } - }); - finalize(psbt); - serializedTx = extract(psbt); - return [2 /*return*/, serializedTx.toString("hex")]; - } - }); - }); - }; - return BtcNew; - }()); - var AccountType; - (function (AccountType) { - AccountType["p2pkh"] = "pkh(@0)"; - AccountType["p2wpkh"] = "wpkh(@0)"; - AccountType["p2wpkhWrapped"] = "sh(wpkh(@0))"; - AccountType["p2tr"] = "tr(@0)"; - })(AccountType || (AccountType = {})); - function createRedeemScript(pubkey) { - var pubkeyHash = hashPublicKey(pubkey); - return Buffer$m.concat([Buffer$m.from("0014", "hex"), pubkeyHash]); - } - function outputScriptOf(pubkey, accountType) { - var buf = new BufferWriter(); - var pubkeyHash = hashPublicKey(pubkey); - var redeemScript; - if (accountType == AccountType.p2pkh) { - buf.writeSlice(Buffer$m.of(OP_DUP, OP_HASH160, HASH_SIZE)); - buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$m.of(OP_EQUALVERIFY, OP_CHECKSIG)); - } - else if (accountType == AccountType.p2wpkhWrapped) { - redeemScript = createRedeemScript(pubkey); - var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$m.of(OP_HASH160, HASH_SIZE)); - buf.writeSlice(scriptHash); - buf.writeUInt8(OP_EQUAL); - } - else if (accountType == AccountType.p2wpkh) { - buf.writeSlice(Buffer$m.of(0, HASH_SIZE)); - buf.writeSlice(pubkeyHash); - } - else if (accountType == AccountType.p2tr) { - console.log("Internal key: " + pubkey.toString("hex")); - var outputKey = getTaprootOutputKey(pubkey); - buf.writeSlice(Buffer$m.of(0x51, 32)); // push1, pubkeylen - buf.writeSlice(outputKey); - } - return { script: buf.buffer(), redeemScript: redeemScript }; - } - function accountTypeFrom(addressFormat) { - if (addressFormat == "legacy") - return AccountType.p2pkh; - if (addressFormat == "p2sh") - return AccountType.p2wpkhWrapped; - if (addressFormat == "bech32") - return AccountType.p2wpkh; - if (addressFormat == "bech32m") - return AccountType.p2tr; - throw new Error("Unsupported address format " + addressFormat); - } - function accountTypeFromArg(arg) { - if (arg.additionals.includes("bech32m")) - return AccountType.p2tr; - if (arg.additionals.includes("bech32")) - return AccountType.p2wpkh; - if (arg.segwit) - return AccountType.p2wpkhWrapped; - return AccountType.p2pkh; - } - /* - The following two functions are copied from wallet-btc and adapte. - They should be moved to a library to avoid code reuse. - */ - function hashTapTweak(x) { - // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 - // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$m.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$m.concat([h, h, x])); - } - function getTaprootOutputKey(internalPubkey) { - if (internalPubkey.length != 32) { - throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); - } - // A BIP32 derived key can be converted to a schnorr pubkey by dropping - // the first byte, which represent the oddness/evenness. In schnorr all - // pubkeys are even. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$m.concat([Buffer$m.of(0x02), internalPubkey]); - var tweak = hashTapTweak(internalPubkey); - // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$m.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); - // Convert to schnorr. - var outputSchnorrKey = outputEcdsaKey.slice(1); - // Create address - return outputSchnorrKey; - } - - var id$1 = 0; - var subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = function (cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } - catch (e) { - console.error(e); - } - } - } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; - } - - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log, - listen: listen - }); - - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$4.apply(this, arguments); - }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 - }; - function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); - } - - /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ - - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); - } - } - - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; - } - - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; - } - }; - - var browser = invariant; - - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$7 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$m.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$m.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$c(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$c(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$m.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$m.compare(version, Buffer$m.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$m.from([0x00]) - : Buffer$m.alloc(0); - data = Buffer$m.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$m.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$m.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$m.concat([ - output.amount, - isDecred ? Buffer$m.from([0x00, 0x00]) : Buffer$m.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$m.concat(endData); - extraPart = isDecred - ? data - : Buffer$m.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$m.concat([locktime, extraPart || Buffer$m.alloc(0)]))]; - case 20: - res = _c.sent(); - browser(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } - - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$6 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$m.concat([ - transaction.version, - transaction.timestamp || Buffer$m.alloc(0), - transaction.nVersionGroupId || Buffer$m.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$6(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$m.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$m.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$m.from([0x00]); - } - } - data = Buffer$m.concat([ - prefix, - inputValue, - isDecred ? Buffer$m.from([0x00]) : Buffer$m.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$m.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); - } - - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); - } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); - } - var hash = sha$3("sha256") - .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$m.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); - } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); - } - hash = Buffer$m.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } - - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$m.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$m.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } - - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$m.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([sigHashType]), - ]) - : Buffer$m.concat([ - pathsBuffer, - Buffer$m.from([0x00]), - lockTimeBuffer, - Buffer$m.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$m.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } - - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); - } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; - - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver$2.gte(version, "1.4.0"); - } - - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$m.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$m.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$m.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$m.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$m.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$m.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$m.concat([ - Buffer$m.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$m.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$m.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$m.concat([ - Buffer$m.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); - } - } - else { - signatureSize = Buffer$m.alloc(1); - keySize = Buffer$m.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$m.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); - } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$m.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$m.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$m.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$m.concat([ - Buffer$m.from("02", "hex"), - Buffer$m.from([signatures[i].length]), - signatures[i], - Buffer$m.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$m.concat([witness, tmpScriptData]); - } - result = Buffer$m.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$m.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$m.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$m.alloc(0), - targetTransaction.extraData || Buffer$m.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$m.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$m.concat([ - decredWitness_1, - Buffer$m.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0x00, 0x00, 0x00, 0x00]), - Buffer$m.from([0xff, 0xff, 0xff, 0xff]), - Buffer$m.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$m.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } - }); - }); - } - - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$m.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$m.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$m.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$6(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$m.alloc(0); - nullPrevout = Buffer$m.alloc(0); - defaultVersion = Buffer$m.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - startTime = Date.now(); - targetTransaction = { - inputs: [], - timestamp: Buffer$m.alloc(0), - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$m.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$m.from(trustedInput, "hex") - : Buffer$m.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$m.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$m.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$m.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var BtcOld = /** @class */ (function () { - function BtcOld(transport) { - this.transport = transport; - this.derivationsCache = {}; - } - BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { - var res; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: - if (this.derivationsCache[path]) - return [2 /*return*/, this.derivationsCache[path]]; - return [4 /*yield*/, getWalletPublicKey(this.transport, { - path: path - })]; - case 1: - res = _a.sent(); - this.derivationsCache[path] = res; - return [2 /*return*/, res]; - } - }); - }); - }; - BtcOld.prototype.getWalletXpub = function (_a) { - var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { - var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { - switch (_b.label) { - case 0: - pathElements = pathStringToArray(path); - parentPath = pathElements.slice(0, -1); - return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; - case 1: - parentDerivation = _b.sent(); - return [4 /*yield*/, this.derivatePath(path)]; - case 2: - accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$m.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$m.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$m.from(accountDerivation.publicKey, "hex"))); - return [2 /*return*/, xpub]; - } - }); - }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - BtcOld.prototype.getWalletPublicKey = function (path, opts) { - if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { - throw new Error("Unsupported address format bech32m"); - } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - BtcOld.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - BtcOld.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return createTransaction(this.transport, arg); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - BtcOld.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); - } - return signP2SHTransaction(this.transport, arg); - }; - return BtcOld; - }()); - function makeFingerprint(compressedPubKey) { - return hash160(compressedPubKey).slice(0, 4); - } - function asBufferUInt32BE(n) { - var buf = Buffer$m.allocUnsafe(4); - buf.writeUInt32BE(n, 0); - return buf; - } - var compressPublicKeySECP256 = function (publicKey) { - return Buffer$m.concat([ - Buffer$m.from([0x02 + (publicKey[64] & 0x01)]), - publicKey.slice(1, 33), - ]); - }; - function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { - var indexBuffer = asBufferUInt32BE(index); - indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$m.concat([ - asBufferUInt32BE(version), - Buffer$m.from([depth]), - parentFingerprint, - indexBuffer, - chainCode, - pubKey, - ]); - var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$m.concat([extendedKeyBytes, checksum])); - } - function sha256(buffer) { - return sha$3("sha256").update(buffer).digest(); - } - function hash256(buffer) { - return sha256(sha256(buffer)); - } - function ripemd160(buffer) { - return new ripemd160$2().update(buffer).digest(); - } - function hash160(buffer) { - return ripemd160(sha256(buffer)); - } - - var MerkleMap = /** @class */ (function () { - /** - * @param keys Sorted list of (unhashed) keys - * @param values values, in corresponding order as the keys, and of equal length - */ - function MerkleMap(keys, values) { - if (keys.length != values.length) { - throw new Error("keys and values should have the same length"); - } - // Sanity check: verify that keys are actually sorted and with no duplicates - for (var i = 0; i < keys.length - 1; i++) { - if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { - throw new Error("keys must be in strictly increasing order"); - } - } - this.keys = keys; - this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); - this.values = values; - this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); - } - MerkleMap.prototype.commitment = function () { - // returns a buffer between 65 and 73 (included) bytes long - return Buffer$m.concat([ - createVarint(this.keys.length), - this.keysTree.getRoot(), - this.valuesTree.getRoot(), - ]); - }; - return MerkleMap; - }()); - - var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$2 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); - function MerkelizedPsbt(psbt) { - var _this = _super.call(this) || this; - _this.inputMerkleMaps = []; - _this.outputMerkleMaps = []; - psbt.copy(_this); - _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); - for (var i = 0; i < _this.getGlobalInputCount(); i++) { - _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); - } - _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - for (var i = 0; i < _this.getGlobalOutputCount(); i++) { - _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); - } - _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { - return v.commitment(); - }); - return _this; - } - // These public functions are for MerkelizedPsbt. - MerkelizedPsbt.prototype.getGlobalSize = function () { - return this.globalMap.size; - }; - MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { - return this.globalMerkleMap.commitment(); - }; - MerkelizedPsbt.createMerkleMap = function (map) { - var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); - var values = sortedKeysStrings.map(function (k) { - var v = map.get(k); - if (!v) { - throw new Error("No value for key " + k); - } - return v; - }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$m.from(k, "hex"); }); - var merkleMap = new MerkleMap(sortedKeys, values); - return merkleMap; - }; - return MerkelizedPsbt; - }(PsbtV2)); - - var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __read$1 = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values$3 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var ClientCommandCode; - (function (ClientCommandCode) { - ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; - ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; - ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; - ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; - })(ClientCommandCode || (ClientCommandCode = {})); - var ClientCommand = /** @class */ (function () { - function ClientCommand() { - } - return ClientCommand; - }()); - var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); - function YieldCommand(results) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.YIELD; - _this.results = results; - return _this; - } - YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$m.from(request.subarray(1))); - return Buffer$m.from(""); - }; - return YieldCommand; - }(ClientCommand)); - var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); - function GetPreimageCommand(known_preimages, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_PREIMAGE; - _this.known_preimages = known_preimages; - _this.queue = queue; - return _this; - } - GetPreimageCommand.prototype.execute = function (request) { - var req = request.subarray(1); - // we expect no more data to read - if (req.length != 1 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (req[0] != 0) { - throw new Error("Unsupported request, the first byte should be 0"); - } - // read the hash - var hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req[1 + i]; - } - var req_hash_hex = hash.toString("hex"); - var known_preimage = this.known_preimages.get(req_hash_hex); - if (known_preimage != undefined) { - var preimage_len_varint = createVarint(known_preimage.length); - // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; - // the rest will be stored in the queue for GET_MORE_ELEMENTS - var max_payload_size = 255 - preimage_len_varint.length - 1; - var payload_size = Math.min(max_payload_size, known_preimage.length); - if (payload_size < known_preimage.length) { - for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$m.from([known_preimage[i]])); - } - } - return Buffer$m.concat([ - preimage_len_varint, - Buffer$m.from([payload_size]), - known_preimage.subarray(0, payload_size), - ]); - } - throw Error("Requested unknown preimage for: " + req_hash_hex); - }; - return GetPreimageCommand; - }(ClientCommand)); - var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); - function GetMerkleLeafProofCommand(known_trees, queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; - _this.known_trees = known_trees; - _this.queue = queue; - return _this; - } - GetMerkleLeafProofCommand.prototype.execute = function (request) { - var _a; - var req = request.subarray(1); - if (req.length != 32 + 4 + 4) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the hash - var hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - hash[i] = req.readUInt8(i); - } - var hash_hex = hash.toString("hex"); - var tree_size = req.readUInt32BE(32); - var leaf_index = req.readUInt32BE(32 + 4); - var mt = this.known_trees.get(hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); - } - if (leaf_index >= tree_size || mt.size() != tree_size) { - throw Error("Invalid index or tree size."); - } - if (this.queue.length != 0) { - throw Error("This command should not execute when the queue is not empty."); - } - var proof = mt.getProof(leaf_index); - var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); - var n_leftover_elements = proof.length - n_response_elements; - // Add to the queue any proof elements that do not fit the response - if (n_leftover_elements > 0) { - (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); - } - return Buffer$m.concat(__spreadArray$1([ - mt.getLeafHash(leaf_index), - Buffer$m.from([proof.length]), - Buffer$m.from([n_response_elements]) - ], __read$1(proof.slice(0, n_response_elements)), false)); - }; - return GetMerkleLeafProofCommand; - }(ClientCommand)); - var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); - function GetMerkleLeafIndexCommand(known_trees) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; - _this.known_trees = known_trees; - return _this; - } - GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = request.subarray(1); - if (req.length != 32 + 32) { - throw new Error("Invalid request, unexpected trailing data"); - } - // read the root hash - var root_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - root_hash[i] = req.readUInt8(i); - } - var root_hash_hex = root_hash.toString("hex"); - // read the leaf hash - var leef_hash = Buffer$m.alloc(32); - for (var i = 0; i < 32; i++) { - leef_hash[i] = req.readUInt8(32 + i); - } - var leef_hash_hex = leef_hash.toString("hex"); - var mt = this.known_trees.get(root_hash_hex); - if (!mt) { - throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); - } - var leaf_index = 0; - var found = 0; - for (var i = 0; i < mt.size(); i++) { - if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { - found = 1; - leaf_index = i; - break; - } - } - return Buffer$m.concat([Buffer$m.from([found]), createVarint(leaf_index)]); - }; - return GetMerkleLeafIndexCommand; - }(ClientCommand)); - var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); - function GetMoreElementsCommand(queue) { - var _this = _super.call(this) || this; - _this.code = ClientCommandCode.GET_MORE_ELEMENTS; - _this.queue = queue; - return _this; - } - GetMoreElementsCommand.prototype.execute = function (request) { - if (request.length != 1) { - throw new Error("Invalid request, unexpected trailing data"); - } - if (this.queue.length === 0) { - throw new Error("No elements to get"); - } - // all elements should have the same length - var element_len = this.queue[0].length; - if (this.queue.some(function (el) { return el.length != element_len; })) { - throw new Error("The queue contains elements with different byte length, which is not expected"); - } - var max_elements = Math.floor(253 / element_len); - var n_returned_elements = Math.min(max_elements, this.queue.length); - var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$m.concat(__spreadArray$1([ - Buffer$m.from([n_returned_elements]), - Buffer$m.from([element_len]) - ], __read$1(returned_elements), false)); - }; - return GetMoreElementsCommand; - }(ClientCommand)); - var ClientCommandInterpreter = /** @class */ (function () { - function ClientCommandInterpreter() { - var e_1, _a; - this.roots = new Map(); - this.preimages = new Map(); - this.yielded = []; - this.queue = []; - this.commands = new Map(); - var commands = [ - new YieldCommand(this.yielded), - new GetPreimageCommand(this.preimages, this.queue), - new GetMerkleLeafIndexCommand(this.roots), - new GetMerkleLeafProofCommand(this.roots, this.queue), - new GetMoreElementsCommand(this.queue), - ]; - try { - for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { - var cmd = commands_1_1.value; - if (this.commands.has(cmd.code)) { - throw new Error("Multiple commands with code " + cmd.code); - } - this.commands.set(cmd.code, cmd); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); - } - finally { if (e_1) throw e_1.error; } - } - } - ClientCommandInterpreter.prototype.getYielded = function () { - return this.yielded; - }; - ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { - this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); - }; - ClientCommandInterpreter.prototype.addKnownList = function (elements) { - var e_2, _a; - try { - for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { - var el = elements_1_1.value; - var preimage = Buffer$m.concat([Buffer$m.from([0]), el]); - this.addKnownPreimage(preimage); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); - } - finally { if (e_2) throw e_2.error; } - } - var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); - this.roots.set(mt.getRoot().toString("hex"), mt); - }; - ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { - this.addKnownList(mm.keys); - this.addKnownList(mm.values); - }; - ClientCommandInterpreter.prototype.execute = function (request) { - if (request.length == 0) { - throw new Error("Unexpected empty command"); - } - var cmdCode = request[0]; - var cmd = this.commands.get(cmdCode); - if (!cmd) { - throw new Error("Unexpected command code " + cmdCode); - } - return cmd.execute(request); - }; - return ClientCommandInterpreter; - }()); - - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var CLA_BTC = 0xe1; - var CLA_FRAMEWORK = 0xf8; - var BitcoinIns; - (function (BitcoinIns) { - BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; - // GET_ADDRESS = 0x01, // Removed from app - BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; - BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; - BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; - BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; - })(BitcoinIns || (BitcoinIns = {})); - var FrameworkIns; - (function (FrameworkIns) { - FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; - })(FrameworkIns || (FrameworkIns = {})); - var AppClient = /** @class */ (function () { - function AppClient(transport) { - this.transport = transport; - } - AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { - var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ - 0x9000, - 0xe000, - ])]; - case 1: - response = _a.sent(); - _a.label = 2; - case 2: - if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; - if (!cci) { - throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); - } - hwRequest = response.slice(0, -2); - commandResponse = cci.execute(hwRequest); - return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; - case 3: - response = _a.sent(); - return [3 /*break*/, 2]; - case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) - } - }); - }); - }; - AppClient.prototype.getPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { - var response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (pathElements.length > 6) { - throw new Error("Path too long. At most 6 levels allowed."); - } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$m.concat([ - Buffer$m.of(display ? 1 : 0), - pathElementsToBuffer(pathElements), - ]))]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { - var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { - switch (_a.label) { - case 0: - if (change !== 0 && change !== 1) - throw new Error("Change can only be 0 or 1"); - if (addressIndex < 0 || !Number.isInteger(addressIndex)) - throw new Error("Invalid address index"); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$m.alloc(4); - addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$m.concat([ - Buffer$m.of(display ? 1 : 0), - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - Buffer$m.of(change), - addressIndexBuffer, - ]), clientInterpreter)]; - case 1: - response = _a.sent(); - return [2 /*return*/, response.toString("ascii")]; - } - }); - }); - }; - AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC) { - return __awaiter$4(this, void 0, void 0, function () { - var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; - var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { - switch (_h.label) { - case 0: - merkelizedPsbt = new MerkelizedPsbt(psbt); - if (walletHMAC != null && walletHMAC.length != 32) { - throw new Error("Invalid HMAC length"); - } - clientInterpreter = new ClientCommandInterpreter(); - // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$m.from(k, "ascii"); })); - clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); - try { - for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { - map = _b.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { - map = _d.value; - clientInterpreter.addKnownMapping(map); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); - inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); - outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$m.concat([ - merkelizedPsbt.getGlobalKeysValuesRoot(), - createVarint(merkelizedPsbt.getGlobalInputCount()), - inputMapsRoot, - createVarint(merkelizedPsbt.getGlobalOutputCount()), - outputMapsRoot, - walletPolicy.getWalletId(), - walletHMAC || Buffer$m.alloc(32, 0), - ]), clientInterpreter)]; - case 1: - _h.sent(); - yielded = clientInterpreter.getYielded(); - ret = new Map(); - try { - for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { - inputAndSig = yielded_1_1.value; - ret.set(inputAndSig[0], inputAndSig.slice(1)); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); - } - finally { if (e_3) throw e_3.error; } - } - return [2 /*return*/, ret]; - } - }); - }); - }; - AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$m.of())]; - }); - }); - }; - return AppClient; - }()); - - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput " + i + ":"; - str += " prevout " + prevout.toString("hex"); - str += " script " + script.toString("hex"); - str += " sequence " + sequence.toString("hex"); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput " + i + ":"; - str += " amount " + amount.toString("hex"); - str += " script " + script.toString("hex"); - }); - return str; - } - - function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$m.alloc(0); - var nExpiryHeight = Buffer$m.alloc(0); - var nVersionGroupId = Buffer$m.alloc(0); - var extraData = Buffer$m.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer$m.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$m.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$m.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$m.alloc(0); - var tree = Buffer$m.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); - } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); - } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } - else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } - } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); - return t; - } - - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Bitcoin API. - * - * @example - * import Btc from "@ledgerhq/hw-app-btc"; - * const btc = new Btc(transport) - */ - var Btc = /** @class */ (function () { - function Btc(transport, scrambleKey) { - if (scrambleKey === void 0) { scrambleKey = "BTC"; } - // cache the underlying implementation (only once) - this._lazyImpl = null; - this.transport = transport; - transport.decorateAppAPIMethods(this, [ - "getWalletXpub", - "getWalletPublicKey", - "signP2SHTransaction", - "signMessageNew", - "createPaymentTransactionNew", - "getTrustedInput", - "getTrustedInputBIP143", - ], scrambleKey); - } - /** - * Get an XPUB with a ledger device - * @param arg derivation parameter - * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` - * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) - * @returns XPUB of the account - */ - Btc.prototype.getWalletXpub = function (arg) { - return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); - }; - /** - * @param path a BIP 32 path - * @param options an object with optional these fields: - * - * - verify (boolean) will ask user to confirm the address on the device - * - * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. - * - * NB The normal usage is to use: - * - * - legacy format with 44' paths - * - * - p2sh format with 49' paths - * - * - bech32 format with 173' paths - * - * - cashaddr in case of Bitcoin Cash - * - * @example - * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) - * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) - */ - Btc.prototype.getWalletPublicKey = function (path, opts) { - var options; - if (arguments.length > 2 || typeof opts === "boolean") { - console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); - options = { - verify: !!opts, - // eslint-disable-next-line prefer-rest-params - format: arguments[2] ? "p2sh" : "legacy" - }; - } - else { - options = opts || {}; - } - return this.getCorrectImpl().then(function (impl) { - return impl.getWalletPublicKey(path, options); - }); - }; - /** - * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. - * @example - btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { - var v = result['v'] + 27 + 4; - var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); - console.log("Signature : " + signature); - }).catch(function(ex) {console.log(ex);}); - */ - Btc.prototype.signMessageNew = function (path, messageHex) { - return this.old().signMessageNew(path, messageHex); - }; - /** - * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters - * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where - * - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the optional redeem script to use when consuming a Segregated Witness input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not - * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) - * @param additionals list of additionnal options - * - * - "bech32" for spending native segwit outputs - * - "bech32m" for spending native segwit outputs - * - "abc" for bch - * - "gold" for btg - * - "bipxxx" for using BIPxxx - * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) - * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions - * @return the signed transaction ready to be broadcast - * @example - btc.createTransaction({ - inputs: [ [tx1, 1] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(res => ...); - */ - Btc.prototype.createPaymentTransactionNew = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); - } - return this.getCorrectImpl().then(function (impl) { - return impl.createPaymentTransactionNew(arg); - }); - }; - /** - * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters - * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where - * * transaction is the previously computed transaction object for this UTXO - * * output_index is the output in the transaction used as input for this UTXO (counting from 0) - * * redeem script is the mandatory redeem script associated to the current P2SH input - * * sequence is the sequence number to use for this input (when using RBF), or non present - * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign - * @param lockTime is the optional lockTime of the transaction to sign, or default (0) - * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @return the signed transaction ready to be broadcast - * @example - btc.signP2SHTransaction({ - inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], - associatedKeysets: ["0'/0/0"], - outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" - }).then(result => ...); - */ - Btc.prototype.signP2SHTransaction = function (arg) { - return this.old().signP2SHTransaction(arg); - }; - /** - * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. - * @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - */ - Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); - }; - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - Btc.prototype.serializeTransactionOutputs = function (t) { - return serializeTransactionOutputs(t); - }; - Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInput(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); - }; - Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var _lazyImpl, impl; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: - _lazyImpl = this._lazyImpl; - if (_lazyImpl) - return [2 /*return*/, _lazyImpl]; - return [4 /*yield*/, this.inferCorrectImpl()]; - case 1: - impl = _a.sent(); - this._lazyImpl = impl; - return [2 /*return*/, impl]; - } - }); - }); - }; - Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { - var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; - case 1: - appAndVersion = _a.sent(); - canUseNewImplementation = canSupportApp(appAndVersion); - if (!canUseNewImplementation) { - return [2 /*return*/, new BtcOld(this.transport)]; - } - else { - return [2 /*return*/, new BtcNew(new AppClient(this.transport))]; - } - } - }); - }); - }; - Btc.prototype.old = function () { - return new BtcOld(this.transport); - }; - return Btc; - }()); - - var Btc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Btc - }); - - /* eslint-disable no-continue */ - /* eslint-disable no-unused-vars */ - /* eslint-disable no-param-reassign */ - /* eslint-disable no-prototype-builtins */ - var __values$1 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var errorClasses = {}; - var deserializers = {}; - var addCustomErrorDeserializer = function (name, deserializer) { - deserializers[name] = deserializer; - }; - var createCustomErrorClass = function (name) { - var C = function CustomError(message, fields) { - Object.assign(this, fields); - this.name = name; - this.message = message || name; - this.stack = new Error().stack; - }; - C.prototype = new Error(); - errorClasses[name] = C; - return C; - }; - // inspired from https://github.com/programble/errio/blob/master/index.js - var deserializeError = function (object) { - if (typeof object === "object" && object) { - try { - // $FlowFixMe FIXME HACK - var msg = JSON.parse(object.message); - if (msg.message && msg.name) { - object = msg; - } - } - catch (e) { - // nothing - } - var error = void 0; - if (typeof object.name === "string") { - var name_1 = object.name; - var des = deserializers[name_1]; - if (des) { - error = des(object); - } - else { - var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; - if (!constructor) { - console.warn("deserializing an unknown class '" + name_1 + "'"); - constructor = createCustomErrorClass(name_1); - } - error = Object.create(constructor.prototype); - try { - for (var prop in object) { - if (object.hasOwnProperty(prop)) { - error[prop] = object[prop]; - } - } - } - catch (e) { - // sometimes setting a property can fail (e.g. .name) - } - } - } - else { - error = new Error(object.message); - } - if (!error.stack && Error.captureStackTrace) { - Error.captureStackTrace(error, deserializeError); - } - return error; - } - return new Error(String(object)); - }; - // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js - var serializeError = function (value) { - if (!value) - return value; - if (typeof value === "object") { - return destroyCircular(value, []); - } - if (typeof value === "function") { - return "[Function: " + (value.name || "anonymous") + "]"; - } - return value; - }; - // https://www.npmjs.com/package/destroy-circular - function destroyCircular(from, seen) { - var e_1, _a; - var to = {}; - seen.push(from); - try { - for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - var value = from[key]; - if (typeof value === "function") { - continue; - } - if (!value || typeof value !== "object") { - to[key] = value; - continue; - } - if (seen.indexOf(from[key]) === -1) { - to[key] = destroyCircular(from[key], seen.slice(0)); - continue; - } - to[key] = "[Circular]"; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - if (typeof from.name === "string") { - to.name = from.name; - } - if (typeof from.message === "string") { - to.message = from.message; - } - if (typeof from.stack === "string") { - to.stack = from.stack; - } - return to; - } - - var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); - var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); - var AmountRequired = createCustomErrorClass("AmountRequired"); - var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); - var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); - var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); - var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); - var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); - var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); - var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); - var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); - var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); - var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); - var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); - var DeviceHalted = createCustomErrorClass("DeviceHalted"); - var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); - var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); - var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); - var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); - var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); - var EnpointConfigError = createCustomErrorClass("EnpointConfig"); - var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); - var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); - var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); - var HardResetFail = createCustomErrorClass("HardResetFail"); - var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); - var InvalidAddress = createCustomErrorClass("InvalidAddress"); - var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); - var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); - var UnknownMCU = createCustomErrorClass("UnknownMCU"); - var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); - var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); - var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); - var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); - var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); - var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); - var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); - var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); - var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); - var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); - var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); - var NetworkDown = createCustomErrorClass("NetworkDown"); - var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); - var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); - var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); - var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); - var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); - var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); - var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); - var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); - var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); - var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); - var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); - var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); - var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); - var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); - var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); - var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); - var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); - var RecipientRequired = createCustomErrorClass("RecipientRequired"); - var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); - var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); - var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); - var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); - var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); - var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); - var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); - var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); - var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); - var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); - var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal - var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); - var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); - var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); - var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); - var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); - var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); - var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); - var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); - var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); - var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); - var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); - var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); - var FeeRequired = createCustomErrorClass("FeeRequired"); - var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); - var SyncError = createCustomErrorClass("SyncError"); - var PairingFailed = createCustomErrorClass("PairingFailed"); - var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); - var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); - var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); - var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); - // db stuff, no need to translate - var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); - var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); - var DBNotReset = createCustomErrorClass("DBNotReset"); - /** - * TransportError is used for any generic transport errors. - * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. - */ - function TransportError(message, id) { - this.name = "TransportError"; - this.message = message; - this.stack = new Error().stack; - this.id = id; - } - TransportError.prototype = new Error(); - addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); - var StatusCodes = { - PIN_REMAINING_ATTEMPTS: 0x63c0, - INCORRECT_LENGTH: 0x6700, - MISSING_CRITICAL_PARAMETER: 0x6800, - COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, - SECURITY_STATUS_NOT_SATISFIED: 0x6982, - CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, - INCORRECT_DATA: 0x6a80, - NOT_ENOUGH_MEMORY_SPACE: 0x6a84, - REFERENCED_DATA_NOT_FOUND: 0x6a88, - FILE_ALREADY_EXISTS: 0x6a89, - INCORRECT_P1_P2: 0x6b00, - INS_NOT_SUPPORTED: 0x6d00, - CLA_NOT_SUPPORTED: 0x6e00, - TECHNICAL_PROBLEM: 0x6f00, - OK: 0x9000, - MEMORY_PROBLEM: 0x9240, - NO_EF_SELECTED: 0x9400, - INVALID_OFFSET: 0x9402, - FILE_NOT_FOUND: 0x9404, - INCONSISTENT_FILE: 0x9408, - ALGORITHM_NOT_SUPPORTED: 0x9484, - INVALID_KCV: 0x9485, - CODE_NOT_INITIALIZED: 0x9802, - ACCESS_CONDITION_NOT_FULFILLED: 0x9804, - CONTRADICTION_SECRET_CODE_STATUS: 0x9808, - CONTRADICTION_INVALIDATION: 0x9810, - CODE_BLOCKED: 0x9840, - MAX_VALUE_REACHED: 0x9850, - GP_AUTH_FAILED: 0x6300, - LICENSING: 0x6f42, - HALTED: 0x6faa - }; - function getAltStatusMessage(code) { - switch (code) { - // improve text of most common errors - case 0x6700: - return "Incorrect length"; - case 0x6800: - return "Missing critical parameter"; - case 0x6982: - return "Security not satisfied (dongle locked or have invalid access rights)"; - case 0x6985: - return "Condition of use not satisfied (denied by the user?)"; - case 0x6a80: - return "Invalid data received"; - case 0x6b00: - return "Invalid parameter received"; - } - if (0x6f00 <= code && code <= 0x6fff) { - return "Internal error, please report"; - } - } - /** - * Error thrown when a device returned a non success status. - * the error.statusCode is one of the `StatusCodes` exported by this library. - */ - function TransportStatusError(statusCode) { - this.name = "TransportStatusError"; - var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || - "UNKNOWN_ERROR"; - var smsg = getAltStatusMessage(statusCode) || statusText; - var statusCodeStr = statusCode.toString(16); - this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; - this.stack = new Error().stack; - this.statusCode = statusCode; - this.statusText = statusText; - } - TransportStatusError.prototype = new Error(); - addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - - var libEs = /*#__PURE__*/Object.freeze({ - __proto__: null, - serializeError: serializeError, - deserializeError: deserializeError, - createCustomErrorClass: createCustomErrorClass, - addCustomErrorDeserializer: addCustomErrorDeserializer, - AccountNameRequiredError: AccountNameRequiredError, - AccountNotSupported: AccountNotSupported, - AmountRequired: AmountRequired, - BluetoothRequired: BluetoothRequired, - BtcUnmatchedApp: BtcUnmatchedApp, - CantOpenDevice: CantOpenDevice, - CashAddrNotSupported: CashAddrNotSupported, - CurrencyNotSupported: CurrencyNotSupported, - DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, - DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, - DeviceNotGenuineError: DeviceNotGenuineError, - DeviceOnDashboardExpected: DeviceOnDashboardExpected, - DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, - DeviceInOSUExpected: DeviceInOSUExpected, - DeviceHalted: DeviceHalted, - DeviceNameInvalid: DeviceNameInvalid, - DeviceSocketFail: DeviceSocketFail, - DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, - DisconnectedDevice: DisconnectedDevice, - DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, - EnpointConfigError: EnpointConfigError, - EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, - FeeEstimationFailed: FeeEstimationFailed, - FirmwareNotRecognized: FirmwareNotRecognized, - HardResetFail: HardResetFail, - InvalidXRPTag: InvalidXRPTag, - InvalidAddress: InvalidAddress, - InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, - LatestMCUInstalledError: LatestMCUInstalledError, - UnknownMCU: UnknownMCU, - LedgerAPIError: LedgerAPIError, - LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, - LedgerAPINotAvailable: LedgerAPINotAvailable, - ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, - ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, - ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, - ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, - ManagerDeviceLockedError: ManagerDeviceLockedError, - ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, - ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, - ManagerUninstallBTCDep: ManagerUninstallBTCDep, - NetworkDown: NetworkDown, - NoAddressesFound: NoAddressesFound, - NotEnoughBalance: NotEnoughBalance, - NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, - NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, - NotEnoughSpendableBalance: NotEnoughSpendableBalance, - NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, - NoAccessToCamera: NoAccessToCamera, - NotEnoughGas: NotEnoughGas, - NotSupportedLegacyAddress: NotSupportedLegacyAddress, - GasLessThanEstimate: GasLessThanEstimate, - PasswordsDontMatchError: PasswordsDontMatchError, - PasswordIncorrectError: PasswordIncorrectError, - RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, - RecommendUndelegation: RecommendUndelegation, - TimeoutTagged: TimeoutTagged, - UnexpectedBootloader: UnexpectedBootloader, - MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, - RecipientRequired: RecipientRequired, - UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, - UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, - UpdateFetchFileFail: UpdateFetchFileFail, - UpdateIncorrectHash: UpdateIncorrectHash, - UpdateIncorrectSig: UpdateIncorrectSig, - UpdateYourApp: UpdateYourApp, - UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, - UserRefusedAddress: UserRefusedAddress, - UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, - UserRefusedAllowManager: UserRefusedAllowManager, - UserRefusedOnDevice: UserRefusedOnDevice, - TransportOpenUserCancelled: TransportOpenUserCancelled, - TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, - TransportRaceCondition: TransportRaceCondition, - TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, - DeviceShouldStayInApp: DeviceShouldStayInApp, - WebsocketConnectionError: WebsocketConnectionError, - WebsocketConnectionFailed: WebsocketConnectionFailed, - WrongDeviceForAccount: WrongDeviceForAccount, - WrongAppForCurrency: WrongAppForCurrency, - ETHAddressNonEIP: ETHAddressNonEIP, - CantScanQRCode: CantScanQRCode, - FeeNotLoaded: FeeNotLoaded, - FeeRequired: FeeRequired, - FeeTooHigh: FeeTooHigh, - SyncError: SyncError, - PairingFailed: PairingFailed, - GenuineCheckFailed: GenuineCheckFailed, - LedgerAPI4xx: LedgerAPI4xx, - LedgerAPI5xx: LedgerAPI5xx, - FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, - NoDBPathGiven: NoDBPathGiven, - DBWrongPassword: DBWrongPassword, - DBNotReset: DBNotReset, - TransportError: TransportError, - StatusCodes: StatusCodes, - getAltStatusMessage: getAltStatusMessage, - TransportStatusError: TransportStatusError - }); - - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __read = (undefined && undefined.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - var __values = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - /** - * Transport defines the generic interface to share between node/u2f impl - * A **Descriptor** is a parametric type that is up to be determined for the implementation. - * it can be for instance an ID, an file path, a URL,... - */ - var Transport = /** @class */ (function () { - function Transport() { - var _this = this; - this.exchangeTimeout = 30000; - this.unresponsiveTimeout = 15000; - this.deviceModel = null; - this._events = new EventEmitter$1(); - /** - * wrapper on top of exchange to simplify work of the implementation. - * @param cla - * @param ins - * @param p1 - * @param p2 - * @param data - * @param statusList is a list of accepted status code (shorts). [0x9000] by default - * @return a Promise of response buffer - */ - this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$m.alloc(0); } - if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { - var response, sw; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (data.length >= 256) { - throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); - } - return [4 /*yield*/, this.exchange(Buffer$m.concat([ - Buffer$m.from([cla, ins, p1, p2]), - Buffer$m.from([data.length]), - data, - ]))]; - case 1: - response = _a.sent(); - sw = response.readUInt16BE(response.length - 2); - if (!statusList.some(function (s) { return s === sw; })) { - throw new TransportStatusError(sw); - } - return [2 /*return*/, response]; - } - }); - }); - }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { - var resolveBusy, busyPromise, unresponsiveReached, timeout, res; - var _this = this; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - if (this.exchangeBusyPromise) { - throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); - } - busyPromise = new Promise(function (r) { - resolveBusy = r; - }); - this.exchangeBusyPromise = busyPromise; - unresponsiveReached = false; - timeout = setTimeout(function () { - unresponsiveReached = true; - _this.emit("unresponsive"); - }, this.unresponsiveTimeout); - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - return [4 /*yield*/, f()]; - case 2: - res = _a.sent(); - if (unresponsiveReached) { - this.emit("responsive"); - } - return [2 /*return*/, res]; - case 3: - clearTimeout(timeout); - if (resolveBusy) - resolveBusy(); - this.exchangeBusyPromise = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); }; - this._appAPIlock = null; - } - /** - * low level api to communicate with the device - * This method is for implementations to implement but should not be directly called. - * Instead, the recommanded way is to use send() method - * @param apdu the data to send - * @return a Promise of response data - */ - Transport.prototype.exchange = function (_apdu) { - throw new Error("exchange not implemented"); - }; - /** - * set the "scramble key" for the next exchanges with the device. - * Each App can have a different scramble key and they internally will set it at instanciation. - * @param key the scramble key - */ - Transport.prototype.setScrambleKey = function (_key) { }; - /** - * close the exchange with the device. - * @return a Promise that ends when the transport is closed. - */ - Transport.prototype.close = function () { - return Promise.resolve(); - }; - /** - * Listen to an event on an instance of transport. - * Transport implementation can have specific events. Here is the common events: - * * `"disconnect"` : triggered if Transport is disconnected - */ - Transport.prototype.on = function (eventName, cb) { - this._events.on(eventName, cb); - }; - /** - * Stop listening to an event on an instance of transport. - */ - Transport.prototype.off = function (eventName, cb) { - this._events.removeListener(eventName, cb); - }; - Transport.prototype.emit = function (event) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); - }; - /** - * Enable or not logs of the binary exchange - */ - Transport.prototype.setDebugMode = function () { - console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); - }; - /** - * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) - */ - Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { - this.exchangeTimeout = exchangeTimeout; - }; - /** - * Define the delay before emitting "unresponsive" on an exchange that does not respond - */ - Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { - this.unresponsiveTimeout = unresponsiveTimeout; - }; - /** - * create() allows to open the first descriptor available or - * throw if there is none or if timeout is reached. - * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) - * @example - TransportFoo.create().then(transport => ...) - */ - Transport.create = function (openTimeout, listenTimeout) { - var _this = this; - if (openTimeout === void 0) { openTimeout = 3000; } - return new Promise(function (resolve, reject) { - var found = false; - var sub = _this.listen({ - next: function (e) { - found = true; - if (sub) - sub.unsubscribe(); - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - _this.open(e.descriptor, openTimeout).then(resolve, reject); - }, - error: function (e) { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - reject(e); - }, - complete: function () { - if (listenTimeoutId) - clearTimeout(listenTimeoutId); - if (!found) { - reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); - } - } - }); - var listenTimeoutId = listenTimeout - ? setTimeout(function () { - sub.unsubscribe(); - reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); - }, listenTimeout) - : null; - }); - }; - Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { - var e_1, _a; - try { - for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { - var methodName = methods_1_1.value; - self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); - } - finally { if (e_1) throw e_1.error; } - } - }; - Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { - var _this = this; - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return __awaiter$2(_this, void 0, void 0, function () { - var _appAPIlock; - return __generator$2(this, function (_a) { - switch (_a.label) { - case 0: - _appAPIlock = this._appAPIlock; - if (_appAPIlock) { - return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; - } - _a.label = 1; - case 1: - _a.trys.push([1, , 3, 4]); - this._appAPIlock = methodName; - this.setScrambleKey(scrambleKey); - return [4 /*yield*/, f.apply(ctx, args)]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - this._appAPIlock = null; - return [7 /*endfinally*/]; - case 4: return [2 /*return*/]; - } - }); - }); - }; - }; - Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; - Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; - return Transport; - }()); - - var hidFraming$1 = {}; - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - - (function (exports) { - exports.__esModule = true; - var errors_1 = require$$0; - var Tag = 0x05; - function asUInt16BE(value) { - var b = Buffer$m.alloc(2); - b.writeUInt16BE(value, 0); - return b; - } - var initialAcc = { - data: Buffer$m.alloc(0), - dataLength: 0, - sequence: 0 - }; - /** - * - */ - var createHIDframing = function (channel, packetSize) { - return { - makeBlocks: function (apdu) { - var data = Buffer$m.concat([asUInt16BE(apdu.length), apdu]); - var blockSize = packetSize - 5; - var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$m.concat([ - data, - Buffer$m.alloc(nbBlocks * blockSize - data.length + 1).fill(0), - ]); - var blocks = []; - for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$m.alloc(5); - head.writeUInt16BE(channel, 0); - head.writeUInt8(Tag, 2); - head.writeUInt16BE(i, 3); - var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$m.concat([head, chunk])); - } - return blocks; - }, - reduceResponse: function (acc, chunk) { - var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; - if (chunk.readUInt16BE(0) !== channel) { - throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); - } - if (chunk.readUInt8(2) !== Tag) { - throw new errors_1.TransportError("Invalid tag", "InvalidTag"); - } - if (chunk.readUInt16BE(3) !== sequence) { - throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); - } - if (!acc) { - dataLength = chunk.readUInt16BE(5); - } - sequence++; - var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$m.concat([data, chunkData]); - if (data.length > dataLength) { - data = data.slice(0, dataLength); - } - return { - data: data, - dataLength: dataLength, - sequence: sequence - }; - }, - getReducedResult: function (acc) { - if (acc && acc.dataLength === acc.data.length) { - return acc.data; - } - } - }; - }; - exports["default"] = createHIDframing; - - }(hidFraming$1)); - - var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); - - var re$5 = {exports: {}}; - - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; - - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; - - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; - - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; - - const debug$3 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; - - var debug_1 = debug$3; - - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; - - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; - - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; - - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. - - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. - - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); - - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. - - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); - - // ## Main Version - // Three dot-separated numeric identifiers. - - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); - - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); - - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. - - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); - - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. - - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. - - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); - - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. - - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. - - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. - - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); - - createToken('FULL', `^${src[t.FULLPLAIN]}$`); - - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); - - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); - - createToken('GTLT', '((?:<|>)?=?)'); - - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); - - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); - - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); - - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; - - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); - - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; - - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; - - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); - - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); - - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); - - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; - - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; - - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); - - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers - }; - - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; - - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); - - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version; - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } - - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) - } - - debug$2('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; - - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); - } - - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer$e(other, this.options); - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } - - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break - - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.format(); - this.raw = this.version; - return this - } - } - - var semver$1 = SemVer$e; - - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; - - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); - - if (version instanceof SemVer$d) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } - - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; - - var parse_1 = parse$5; - - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; - - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; - - const SemVer$c = semver$1; - - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } - - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; - - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); - - var compare_1 = compare$a; - - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; - - const parse$2 = parse_1; - const eq$1 = eq_1; - - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } - }; - var diff_1 = diff; - - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; - - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; - - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; - - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1 = prerelease; - - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; - - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1 = compareBuild$2; - - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; - - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; - - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; - - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; - - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; - - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; - - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; - - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; - - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt$2(a, b, loose) - - case '>=': - return gte$1(a, b, loose) - - case '<': - return lt$1(a, b, loose) - - case '<=': - return lte$1(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1 = cmp$1; - - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; - - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } - - if (typeof version === 'number') { - version = String(version); - } - - if (typeof version !== 'string') { - return null - } - - options = options || {}; - - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; - } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } - - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1 = coerce; - - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); - - if (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } - } - - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this - } - - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } - } - } - } - - this.format(); - } - - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - range = range.trim(); - - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached - - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } - - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } - } - var range = Range$a; - - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); - - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; - - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; - - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); - - testComparator = remainingComparators.pop(); - } - - return result - }; - - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); - return comp - }; - - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; - - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); - - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$1('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - - debug$1('tilde return', ret); - return ret - }) }; - - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); - - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); - let ret; - - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug$1('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; - } - } else { - debug$1('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; - } - } - - debug$1('caret return', ret); - return ret - }) + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION }; + function signP2SHTransaction(transport, arg) { + return __awaiter$3(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$3(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; + nullScript = Buffer$e.alloc(0); + nullPrevout = Buffer$e.alloc(0); + defaultVersion = Buffer$e.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + startTime = Date.now(); + targetTransaction = { + inputs: [], + timestamp: Buffer$e.alloc(0), + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$e.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$e.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$e.from(trustedInput, "hex") + : Buffer$e.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$e.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$e.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$e.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); }; - - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - - if (gtlt === '=' && anyX) { - gtlt = ''; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var Btc = /** @class */ (function () { + function Btc(transport, scrambleKey) { + if (scrambleKey === void 0) { scrambleKey = "BTC"; } + this.transport = transport; + transport.decorateAppAPIMethods(this, [ + "getWalletPublicKey", + "signP2SHTransaction", + "signMessageNew", + "createPaymentTransactionNew", + "getTrustedInput", + "getTrustedInputBIP143", + ], scrambleKey); } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; - } - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + Btc.prototype.getWalletPublicKey = function (path, opts) { + var options; + if (arguments.length > 2 || typeof opts === "boolean") { + console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); + options = { + verify: !!opts, + // eslint-disable-next-line prefer-rest-params + format: arguments[2] ? "p2sh" : "legacy" + }; } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; + else { + options = opts || {}; } - } - - if (gtlt === '<') - pr = '-0'; - - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; - } - - debug$1('xRange return', ret); + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, options), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + Btc.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + Btc.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + Btc.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + /** + * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. + * @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + */ + Btc.prototype.splitTransaction = function (transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + return splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals); + }; + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + Btc.prototype.serializeTransactionOutputs = function (t) { + return serializeTransactionOutputs(t); + }; + Btc.prototype.getTrustedInput = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInput(this.transport, indexLookup, transaction, additionals); + }; + Btc.prototype.getTrustedInputBIP143 = function (indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); + }; + return Btc; + }()); - return ret - }) - }; + var Btc$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Btc + }); - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') + /* eslint-disable no-continue */ + /* eslint-disable no-unused-vars */ + /* eslint-disable no-param-reassign */ + /* eslint-disable no-prototype-builtins */ + var __values$1 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; - - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + var errorClasses = {}; + var deserializers = {}; + var addCustomErrorDeserializer = function (name, deserializer) { + deserializers[name] = deserializer; }; - - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } - - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - - return (`${from} ${to}`).trim() + var createCustomErrorClass = function (name) { + var C = function CustomError(message, fields) { + Object.assign(this, fields); + this.name = name; + this.message = message || name; + this.stack = new Error().stack; + }; + C.prototype = new Error(); + errorClasses[name] = C; + return C; }; - - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true + // inspired from https://github.com/programble/errio/blob/master/index.js + var deserializeError = function (object) { + if (typeof object === "object" && object) { + try { + // $FlowFixMe FIXME HACK + var msg = JSON.parse(object.message); + if (msg.message && msg.name) { + object = msg; + } } - } + catch (e) { + // nothing + } + var error = void 0; + if (typeof object.name === "string") { + var name_1 = object.name; + var des = deserializers[name_1]; + if (des) { + error = des(object); + } + else { + var constructor = name_1 === "Error" ? Error : errorClasses[name_1]; + if (!constructor) { + console.warn("deserializing an unknown class '" + name_1 + "'"); + constructor = createCustomErrorClass(name_1); + } + error = Object.create(constructor.prototype); + try { + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + error[prop] = object[prop]; + } + } + } + catch (e) { + // sometimes setting a property can fail (e.g. .name) + } + } + } + else { + error = new Error(object.message); + } + if (!error.stack && Error.captureStackTrace) { + Error.captureStackTrace(error, deserializeError); + } + return error; } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true + return new Error(String(object)); }; - - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 - } - constructor (comp, options) { - options = parseOptions(options); - - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value; - } - } - - debug('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } - - debug('comp', this); - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + // inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js + var serializeError = function (value) { + if (!value) + return value; + if (typeof value === "object") { + return destroyCircular(value, []); } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; - } else { - this.semver = new SemVer$4(m[2], this.options.loose); + if (typeof value === "function") { + return "[Function: " + (value.name || "anonymous") + "]"; } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose); - - if (this.semver === ANY$2 || version === ANY$2) { - return true + return value; + }; + // https://www.npmjs.com/package/destroy-circular + function destroyCircular(from, seen) { + var e_1, _a; + var to = {}; + seen.push(from); + try { + for (var _b = __values$1(Object.keys(from)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + var value = from[key]; + if (typeof value === "function") { + continue; + } + if (!value || typeof value !== "object") { + to[key] = value; + continue; + } + if (seen.indexOf(from[key]) === -1) { + to[key] = destroyCircular(from[key], seen.slice(0)); + continue; + } + to[key] = "[Circular]"; + } } - - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b["return"])) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') + if (typeof from.name === "string") { + to.name = from.name; } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + if (typeof from.message === "string") { + to.message = from.message; } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) + if (typeof from.stack === "string") { + to.stack = from.stack; } - - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); - - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } + return to; } - var comparator = Comparator$2; - - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; - - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1 = satisfies$3; - - const Range$7 = range; - - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); - - var toComparators_1 = toComparators; - - const SemVer$3 = semver$1; - const Range$6 = range; - - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } - } - }); - return max + var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired"); + var AccountNotSupported = createCustomErrorClass("AccountNotSupported"); + var AmountRequired = createCustomErrorClass("AmountRequired"); + var BluetoothRequired = createCustomErrorClass("BluetoothRequired"); + var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); + var CantOpenDevice = createCustomErrorClass("CantOpenDevice"); + var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported"); + var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported"); + var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported"); + var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose"); + var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); + var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected"); + var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected"); + var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected"); + var DeviceHalted = createCustomErrorClass("DeviceHalted"); + var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); + var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); + var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus"); + var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); + var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation"); + var EnpointConfigError = createCustomErrorClass("EnpointConfig"); + var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData"); + var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed"); + var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized"); + var HardResetFail = createCustomErrorClass("HardResetFail"); + var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); + var InvalidAddress = createCustomErrorClass("InvalidAddress"); + var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource"); + var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError"); + var UnknownMCU = createCustomErrorClass("UnknownMCU"); + var LedgerAPIError = createCustomErrorClass("LedgerAPIError"); + var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage"); + var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable"); + var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled"); + var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC"); + var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired"); + var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired"); + var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked"); + var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace"); + var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace"); + var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep"); + var NetworkDown = createCustomErrorClass("NetworkDown"); + var NoAddressesFound = createCustomErrorClass("NoAddressesFound"); + var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); + var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate"); + var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount"); + var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance"); + var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated"); + var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); + var NotEnoughGas = createCustomErrorClass("NotEnoughGas"); + var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress"); + var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate"); + var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch"); + var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect"); + var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty"); + var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation"); + var TimeoutTagged = createCustomErrorClass("TimeoutTagged"); + var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader"); + var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard"); + var RecipientRequired = createCustomErrorClass("RecipientRequired"); + var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive"); + var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend"); + var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail"); + var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash"); + var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); + var UpdateYourApp = createCustomErrorClass("UpdateYourApp"); + var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange"); + var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); + var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate"); + var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager"); + var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal + var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled"); + var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable"); + var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition"); + var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired"); + var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp"); + var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError"); + var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed"); + var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount"); + var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency"); + var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); + var CantScanQRCode = createCustomErrorClass("CantScanQRCode"); + var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); + var FeeRequired = createCustomErrorClass("FeeRequired"); + var FeeTooHigh = createCustomErrorClass("FeeTooHigh"); + var SyncError = createCustomErrorClass("SyncError"); + var PairingFailed = createCustomErrorClass("PairingFailed"); + var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); + var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); + var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); + var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired"); + // db stuff, no need to translate + var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); + var DBWrongPassword = createCustomErrorClass("DBWrongPassword"); + var DBNotReset = createCustomErrorClass("DBNotReset"); + /** + * TransportError is used for any generic transport errors. + * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. + */ + function TransportError(message, id) { + this.name = "TransportError"; + this.message = message; + this.stack = new Error().stack; + this.id = id; + } + TransportError.prototype = new Error(); + addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); }); + var StatusCodes = { + PIN_REMAINING_ATTEMPTS: 0x63c0, + INCORRECT_LENGTH: 0x6700, + MISSING_CRITICAL_PARAMETER: 0x6800, + COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, + SECURITY_STATUS_NOT_SATISFIED: 0x6982, + CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, + INCORRECT_DATA: 0x6a80, + NOT_ENOUGH_MEMORY_SPACE: 0x6a84, + REFERENCED_DATA_NOT_FOUND: 0x6a88, + FILE_ALREADY_EXISTS: 0x6a89, + INCORRECT_P1_P2: 0x6b00, + INS_NOT_SUPPORTED: 0x6d00, + CLA_NOT_SUPPORTED: 0x6e00, + TECHNICAL_PROBLEM: 0x6f00, + OK: 0x9000, + MEMORY_PROBLEM: 0x9240, + NO_EF_SELECTED: 0x9400, + INVALID_OFFSET: 0x9402, + FILE_NOT_FOUND: 0x9404, + INCONSISTENT_FILE: 0x9408, + ALGORITHM_NOT_SUPPORTED: 0x9484, + INVALID_KCV: 0x9485, + CODE_NOT_INITIALIZED: 0x9802, + ACCESS_CONDITION_NOT_FULFILLED: 0x9804, + CONTRADICTION_SECRET_CODE_STATUS: 0x9808, + CONTRADICTION_INVALIDATION: 0x9810, + CODE_BLOCKED: 0x9840, + MAX_VALUE_REACHED: 0x9850, + GP_AUTH_FAILED: 0x6300, + LICENSING: 0x6f42, + HALTED: 0x6faa }; - var maxSatisfying_1 = maxSatisfying; - - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); - } + function getAltStatusMessage(code) { + switch (code) { + // improve text of most common errors + case 0x6700: + return "Incorrect length"; + case 0x6800: + return "Missing critical parameter"; + case 0x6982: + return "Security not satisfied (dongle locked or have invalid access rights)"; + case 0x6985: + return "Condition of use not satisfied (denied by the user?)"; + case 0x6a80: + return "Invalid data received"; + case 0x6b00: + return "Invalid parameter received"; } - }); - return min - }; - var minSatisfying_1 = minSatisfying; - - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; - - const minVersion = (range, loose) => { - range = new Range$4(range, loose); - - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } - - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } - - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } - - if (minver && range.test(minver)) { - return minver - } - - return null - }; - var minVersion_1 = minVersion; - - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid = validRange; - - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; - - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); - - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + if (0x6f00 <= code && code <= 0x6fff) { + return "Internal error, please report"; + } + } + /** + * Error thrown when a device returned a non success status. + * the error.statusCode is one of the `StatusCodes` exported by this library. + */ + function TransportStatusError(statusCode) { + this.name = "TransportStatusError"; + var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) || + "UNKNOWN_ERROR"; + var smsg = getAltStatusMessage(statusCode) || statusText; + var statusCodeStr = statusCode.toString(16); + this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")"; + this.stack = new Error().stack; + this.statusCode = statusCode; + this.statusText = statusText; + } + TransportStatusError.prototype = new Error(); + addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); }); - let high = null; - let low = null; + var libEs = /*#__PURE__*/Object.freeze({ + __proto__: null, + serializeError: serializeError, + deserializeError: deserializeError, + createCustomErrorClass: createCustomErrorClass, + addCustomErrorDeserializer: addCustomErrorDeserializer, + AccountNameRequiredError: AccountNameRequiredError, + AccountNotSupported: AccountNotSupported, + AmountRequired: AmountRequired, + BluetoothRequired: BluetoothRequired, + BtcUnmatchedApp: BtcUnmatchedApp, + CantOpenDevice: CantOpenDevice, + CashAddrNotSupported: CashAddrNotSupported, + CurrencyNotSupported: CurrencyNotSupported, + DeviceAppVerifyNotSupported: DeviceAppVerifyNotSupported, + DeviceGenuineSocketEarlyClose: DeviceGenuineSocketEarlyClose, + DeviceNotGenuineError: DeviceNotGenuineError, + DeviceOnDashboardExpected: DeviceOnDashboardExpected, + DeviceOnDashboardUnexpected: DeviceOnDashboardUnexpected, + DeviceInOSUExpected: DeviceInOSUExpected, + DeviceHalted: DeviceHalted, + DeviceNameInvalid: DeviceNameInvalid, + DeviceSocketFail: DeviceSocketFail, + DeviceSocketNoBulkStatus: DeviceSocketNoBulkStatus, + DisconnectedDevice: DisconnectedDevice, + DisconnectedDeviceDuringOperation: DisconnectedDeviceDuringOperation, + EnpointConfigError: EnpointConfigError, + EthAppPleaseEnableContractData: EthAppPleaseEnableContractData, + FeeEstimationFailed: FeeEstimationFailed, + FirmwareNotRecognized: FirmwareNotRecognized, + HardResetFail: HardResetFail, + InvalidXRPTag: InvalidXRPTag, + InvalidAddress: InvalidAddress, + InvalidAddressBecauseDestinationIsAlsoSource: InvalidAddressBecauseDestinationIsAlsoSource, + LatestMCUInstalledError: LatestMCUInstalledError, + UnknownMCU: UnknownMCU, + LedgerAPIError: LedgerAPIError, + LedgerAPIErrorWithMessage: LedgerAPIErrorWithMessage, + LedgerAPINotAvailable: LedgerAPINotAvailable, + ManagerAppAlreadyInstalledError: ManagerAppAlreadyInstalledError, + ManagerAppRelyOnBTCError: ManagerAppRelyOnBTCError, + ManagerAppDepInstallRequired: ManagerAppDepInstallRequired, + ManagerAppDepUninstallRequired: ManagerAppDepUninstallRequired, + ManagerDeviceLockedError: ManagerDeviceLockedError, + ManagerFirmwareNotEnoughSpaceError: ManagerFirmwareNotEnoughSpaceError, + ManagerNotEnoughSpaceError: ManagerNotEnoughSpaceError, + ManagerUninstallBTCDep: ManagerUninstallBTCDep, + NetworkDown: NetworkDown, + NoAddressesFound: NoAddressesFound, + NotEnoughBalance: NotEnoughBalance, + NotEnoughBalanceToDelegate: NotEnoughBalanceToDelegate, + NotEnoughBalanceInParentAccount: NotEnoughBalanceInParentAccount, + NotEnoughSpendableBalance: NotEnoughSpendableBalance, + NotEnoughBalanceBecauseDestinationNotCreated: NotEnoughBalanceBecauseDestinationNotCreated, + NoAccessToCamera: NoAccessToCamera, + NotEnoughGas: NotEnoughGas, + NotSupportedLegacyAddress: NotSupportedLegacyAddress, + GasLessThanEstimate: GasLessThanEstimate, + PasswordsDontMatchError: PasswordsDontMatchError, + PasswordIncorrectError: PasswordIncorrectError, + RecommendSubAccountsToEmpty: RecommendSubAccountsToEmpty, + RecommendUndelegation: RecommendUndelegation, + TimeoutTagged: TimeoutTagged, + UnexpectedBootloader: UnexpectedBootloader, + MCUNotGenuineToDashboard: MCUNotGenuineToDashboard, + RecipientRequired: RecipientRequired, + UnavailableTezosOriginatedAccountReceive: UnavailableTezosOriginatedAccountReceive, + UnavailableTezosOriginatedAccountSend: UnavailableTezosOriginatedAccountSend, + UpdateFetchFileFail: UpdateFetchFileFail, + UpdateIncorrectHash: UpdateIncorrectHash, + UpdateIncorrectSig: UpdateIncorrectSig, + UpdateYourApp: UpdateYourApp, + UserRefusedDeviceNameChange: UserRefusedDeviceNameChange, + UserRefusedAddress: UserRefusedAddress, + UserRefusedFirmwareUpdate: UserRefusedFirmwareUpdate, + UserRefusedAllowManager: UserRefusedAllowManager, + UserRefusedOnDevice: UserRefusedOnDevice, + TransportOpenUserCancelled: TransportOpenUserCancelled, + TransportInterfaceNotAvailable: TransportInterfaceNotAvailable, + TransportRaceCondition: TransportRaceCondition, + TransportWebUSBGestureRequired: TransportWebUSBGestureRequired, + DeviceShouldStayInApp: DeviceShouldStayInApp, + WebsocketConnectionError: WebsocketConnectionError, + WebsocketConnectionFailed: WebsocketConnectionFailed, + WrongDeviceForAccount: WrongDeviceForAccount, + WrongAppForCurrency: WrongAppForCurrency, + ETHAddressNonEIP: ETHAddressNonEIP, + CantScanQRCode: CantScanQRCode, + FeeNotLoaded: FeeNotLoaded, + FeeRequired: FeeRequired, + FeeTooHigh: FeeTooHigh, + SyncError: SyncError, + PairingFailed: PairingFailed, + GenuineCheckFailed: GenuineCheckFailed, + LedgerAPI4xx: LedgerAPI4xx, + LedgerAPI5xx: LedgerAPI5xx, + FirmwareOrAppUpdateRequired: FirmwareOrAppUpdateRequired, + NoDBPathGiven: NoDBPathGiven, + DBWrongPassword: DBWrongPassword, + DBNotReset: DBNotReset, + TransportError: TransportError, + StatusCodes: StatusCodes, + getAltStatusMessage: getAltStatusMessage, + TransportStatusError: TransportStatusError + }); - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true - }; - - var outside_1 = outside$2; - - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; - - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; - - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) }; - var intersects_1 = intersects; - - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } - if (min) - set.push([min, null]); - - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range }; - - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; - - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true - - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true - - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER + var __read = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); }; - - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; - } - - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); - } - - if (eqSet.size > 1) - return null - - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null - - if (lt && !satisfies(eq, String(lt), options)) - return null - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + var __values = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + /** + * Transport defines the generic interface to share between node/u2f impl + * A **Descriptor** is a parametric type that is up to be determined for the implementation. + * it can be for instance an ID, an file path, a URL,... + */ + var Transport = /** @class */ (function () { + function Transport() { + var _this = this; + this.exchangeTimeout = 30000; + this.unresponsiveTimeout = 15000; + this.deviceModel = null; + this._events = new EventEmitter$1(); + /** + * wrapper on top of exchange to simplify work of the implementation. + * @param cla + * @param ins + * @param p1 + * @param p2 + * @param data + * @param statusList is a list of accepted status code (shorts). [0x9000] by default + * @return a Promise of response buffer + */ + this.send = function (cla, ins, p1, p2, data, statusList) { + if (data === void 0) { data = Buffer$e.alloc(0); } + if (statusList === void 0) { statusList = [StatusCodes.OK]; } + return __awaiter$2(_this, void 0, void 0, function () { + var response, sw; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (data.length >= 256) { + throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); + } + return [4 /*yield*/, this.exchange(Buffer$e.concat([ + Buffer$e.from([cla, ins, p1, p2]), + Buffer$e.from([data.length]), + data, + ]))]; + case 1: + response = _a.sent(); + sw = response.readUInt16BE(response.length - 2); + if (!statusList.some(function (s) { return s === sw; })) { + throw new TransportStatusError(sw); + } + return [2 /*return*/, response]; + } + }); + }); + }; + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + var resolveBusy, busyPromise, unresponsiveReached, timeout, res; + var _this = this; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (this.exchangeBusyPromise) { + throw new TransportRaceCondition("An action was already pending on the Ledger device. Please deny or reconnect."); + } + busyPromise = new Promise(function (r) { + resolveBusy = r; + }); + this.exchangeBusyPromise = busyPromise; + unresponsiveReached = false; + timeout = setTimeout(function () { + unresponsiveReached = true; + _this.emit("unresponsive"); + }, this.unresponsiveTimeout); + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, f()]; + case 2: + res = _a.sent(); + if (unresponsiveReached) { + this.emit("responsive"); + } + return [2 /*return*/, res]; + case 3: + clearTimeout(timeout); + if (resolveBusy) + resolveBusy(); + this.exchangeBusyPromise = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }; + this._appAPIlock = null; } - - return true - } - - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + /** + * low level api to communicate with the device + * This method is for implementations to implement but should not be directly called. + * Instead, the recommanded way is to use send() method + * @param apdu the data to send + * @return a Promise of response data + */ + Transport.prototype.exchange = function (_apdu) { + throw new Error("exchange not implemented"); + }; + /** + * set the "scramble key" for the next exchanges with the device. + * Each App can have a different scramble key and they internally will set it at instanciation. + * @param key the scramble key + */ + Transport.prototype.setScrambleKey = function (_key) { }; + /** + * close the exchange with the device. + * @return a Promise that ends when the transport is closed. + */ + Transport.prototype.close = function () { + return Promise.resolve(); + }; + /** + * Listen to an event on an instance of transport. + * Transport implementation can have specific events. Here is the common events: + * * `"disconnect"` : triggered if Transport is disconnected + */ + Transport.prototype.on = function (eventName, cb) { + this._events.on(eventName, cb); + }; + /** + * Stop listening to an event on an instance of transport. + */ + Transport.prototype.off = function (eventName, cb) { + this._events.removeListener(eventName, cb); + }; + Transport.prototype.emit = function (event) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + (_a = this._events).emit.apply(_a, __spreadArray([event], __read(args), false)); + }; + /** + * Enable or not logs of the binary exchange + */ + Transport.prototype.setDebugMode = function () { + console.warn("setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore."); + }; + /** + * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) + */ + Transport.prototype.setExchangeTimeout = function (exchangeTimeout) { + this.exchangeTimeout = exchangeTimeout; + }; + /** + * Define the delay before emitting "unresponsive" on an exchange that does not respond + */ + Transport.prototype.setExchangeUnresponsiveTimeout = function (unresponsiveTimeout) { + this.unresponsiveTimeout = unresponsiveTimeout; + }; + /** + * create() allows to open the first descriptor available or + * throw if there is none or if timeout is reached. + * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) + * @example + TransportFoo.create().then(transport => ...) + */ + Transport.create = function (openTimeout, listenTimeout) { + var _this = this; + if (openTimeout === void 0) { openTimeout = 3000; } + return new Promise(function (resolve, reject) { + var found = false; + var sub = _this.listen({ + next: function (e) { + found = true; + if (sub) + sub.unsubscribe(); + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + _this.open(e.descriptor, openTimeout).then(resolve, reject); + }, + error: function (e) { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + reject(e); + }, + complete: function () { + if (listenTimeoutId) + clearTimeout(listenTimeoutId); + if (!found) { + reject(new TransportError(_this.ErrorMessage_NoDeviceFound, "NoDeviceFound")); + } + } + }); + var listenTimeoutId = listenTimeout + ? setTimeout(function () { + sub.unsubscribe(); + reject(new TransportError(_this.ErrorMessage_ListenTimeout, "ListenTimeout")); + }, listenTimeout) + : null; + }); + }; + Transport.prototype.decorateAppAPIMethods = function (self, methods, scrambleKey) { + var e_1, _a; + try { + for (var methods_1 = __values(methods), methods_1_1 = methods_1.next(); !methods_1_1.done; methods_1_1 = methods_1.next()) { + var methodName = methods_1_1.value; + self[methodName] = this.decorateAppAPIMethod(methodName, self[methodName], self, scrambleKey); + } } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (methods_1_1 && !methods_1_1.done && (_a = methods_1["return"])) _a.call(methods_1); + } + finally { if (e_1) throw e_1.error; } } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false - } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false - - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + }; + Transport.prototype.decorateAppAPIMethod = function (methodName, f, ctx, scrambleKey) { + var _this = this; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return __awaiter$2(_this, void 0, void 0, function () { + var _appAPIlock; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + _appAPIlock = this._appAPIlock; + if (_appAPIlock) { + return [2 /*return*/, Promise.reject(new TransportError("Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked"))]; + } + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + this._appAPIlock = methodName; + this.setScrambleKey(scrambleKey); + return [4 /*yield*/, f.apply(ctx, args)]; + case 2: return [2 /*return*/, _a.sent()]; + case 3: + this._appAPIlock = null; + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); + }; + }; + Transport.ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; + Transport.ErrorMessage_NoDeviceFound = "No Ledger device found"; + return Transport; + }()); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + var hidFraming$1 = {}; - return true - }; + var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEs); - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a + (function (exports) { + exports.__esModule = true; + var errors_1 = require$$0; + var Tag = 0x05; + function asUInt16BE(value) { + var b = Buffer$e.alloc(2); + b.writeUInt16BE(value, 0); + return b; + } + var initialAcc = { + data: Buffer$e.alloc(0), + dataLength: 0, + sequence: 0 }; - - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a + /** + * + */ + var createHIDframing = function (channel, packetSize) { + return { + makeBlocks: function (apdu) { + var data = Buffer$e.concat([asUInt16BE(apdu.length), apdu]); + var blockSize = packetSize - 5; + var nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer$e.concat([ + data, + Buffer$e.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + var blocks = []; + for (var i = 0; i < nbBlocks; i++) { + var head = Buffer$e.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(Tag, 2); + head.writeUInt16BE(i, 3); + var chunk = data.slice(i * blockSize, (i + 1) * blockSize); + blocks.push(Buffer$e.concat([head, chunk])); + } + return blocks; + }, + reduceResponse: function (acc, chunk) { + var _a = acc || initialAcc, data = _a.data, dataLength = _a.dataLength, sequence = _a.sequence; + if (chunk.readUInt16BE(0) !== channel) { + throw new errors_1.TransportError("Invalid channel", "InvalidChannel"); + } + if (chunk.readUInt8(2) !== Tag) { + throw new errors_1.TransportError("Invalid tag", "InvalidTag"); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new errors_1.TransportError("Invalid sequence", "InvalidSequence"); + } + if (!acc) { + dataLength = chunk.readUInt16BE(5); + } + sequence++; + var chunkData = chunk.slice(acc ? 5 : 7); + data = Buffer$e.concat([data, chunkData]); + if (data.length > dataLength) { + data = data.slice(0, dataLength); + } + return { + data: data, + dataLength: dataLength, + sequence: sequence + }; + }, + getReducedResult: function (acc) { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + } + }; }; + exports["default"] = createHIDframing; - var subset_1 = subset; + }(hidFraming$1)); - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; + var hidFraming = /*@__PURE__*/getDefaultExportFromCjs(hidFraming$1); var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { @@ -40532,7 +17117,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$m.from(r.data.buffer); + buffer = Buffer$e.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -40626,10 +17211,291 @@ 'default': TransportWebUSB }); + var inherits$2 = inherits_browser.exports; + var HashBase = hashBase; + var Buffer$1 = safeBuffer.exports.Buffer; + + var ARRAY16 = new Array(16); + + function MD5$1 () { + HashBase.call(this, 64); + + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } + + inherits$2(MD5$1, HashBase); + + MD5$1.prototype._update = function () { + var M = ARRAY16; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; + }; + + MD5$1.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } + + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); + + // produce result + var buffer = Buffer$1.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } + + function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } + + function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } + + function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } + + var md5_js = MD5$1; + + var Buffer = safeBuffer.exports.Buffer; + var Transform = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; + var inherits$1 = inherits_browser.exports; + + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; + } + inherits$1(CipherBase, Transform); + + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc); + } + + var outData = this._update(data); + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + + return outData + }; + + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; + + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; + + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; + + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); + } + } catch (e) { + err = e; + } finally { + next(err); + } + }; + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } + + done(err); + }; + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; + + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + + return out + }; + + var cipherBase = CipherBase; + + var inherits = inherits_browser.exports; + var MD5 = md5_js; + var RIPEMD160 = ripemd160; + var sha = sha_js.exports; + var Base = cipherBase; + + function Hash (hash) { + Base.call(this, 'digest'); + + this._hash = hash; + } + + inherits(Hash, Base); + + Hash.prototype._update = function (data) { + this._hash.update(data); + }; + + Hash.prototype._final = function () { + return this._hash.digest() + }; + + var browser = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) + }; + + var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser + }, [browser])); + exports.Btc = Btc$1; exports.Log = index; exports.TransportWebUSB = TransportWebUSB$1; - exports.createHash = browser$4; + exports.createHash = browser$1; Object.defineProperty(exports, '__esModule', { value: true }); From e7dd060ce578222d69c20a13848acd9811caea77 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 09:56:03 +1100 Subject: [PATCH 58/78] speculos attempt --- js/ledger.js | 46799 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 35681 insertions(+), 11118 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 9c9e4c79..39ba1f91 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -19,6 +19,8 @@ return Object.freeze(n); } + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } @@ -997,7 +999,7 @@ var toString = {}.toString; - var isArray$3 = Array.isArray || function (arr) { + var isArray$4 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1027,12 +1029,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$e.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$e.TYPED_ARRAY_SUPPORT + return Buffer$k.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1041,14 +1043,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$e.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$e(length); + that = new Buffer$k(length); } that.length = length; } @@ -1066,9 +1068,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$e (arg, encodingOrOffset, length) { - if (!Buffer$e.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$e)) { - return new Buffer$e(arg, encodingOrOffset, length) + function Buffer$k (arg, encodingOrOffset, length) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { + return new Buffer$k(arg, encodingOrOffset, length) } // Common case. @@ -1083,11 +1085,11 @@ return from(this, arg, encodingOrOffset, length) } - Buffer$e.poolSize = 8192; // not used by this implementation + Buffer$k.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$e._augment = function (arr) { - arr.__proto__ = Buffer$e.prototype; + Buffer$k._augment = function (arr) { + arr.__proto__ = Buffer$k.prototype; return arr }; @@ -1115,13 +1117,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$e.from = function (value, encodingOrOffset, length) { + Buffer$k.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) }; - if (Buffer$e.TYPED_ARRAY_SUPPORT) { - Buffer$e.prototype.__proto__ = Uint8Array.prototype; - Buffer$e.__proto__ = Uint8Array; + if (Buffer$k.TYPED_ARRAY_SUPPORT) { + Buffer$k.prototype.__proto__ = Uint8Array.prototype; + Buffer$k.__proto__ = Uint8Array; } function assertSize (size) { @@ -1152,14 +1154,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$e.alloc = function (size, fill, encoding) { + Buffer$k.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$e.TYPED_ARRAY_SUPPORT) { + if (!Buffer$k.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1170,13 +1172,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$e.allocUnsafe = function (size) { + Buffer$k.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$e.allocUnsafeSlow = function (size) { + Buffer$k.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1185,7 +1187,7 @@ encoding = 'utf8'; } - if (!Buffer$e.isEncoding(encoding)) { + if (!Buffer$k.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1232,10 +1234,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$e.prototype; + that.__proto__ = Buffer$k.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1265,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$3(obj.data)) { + if (obj.type === 'Buffer' && isArray$4(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1282,12 +1284,12 @@ } return length | 0 } - Buffer$e.isBuffer = isBuffer; + Buffer$k.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$e.compare = function compare (a, b) { + Buffer$k.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1310,7 +1312,7 @@ return 0 }; - Buffer$e.isEncoding = function isEncoding (encoding) { + Buffer$k.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1329,13 +1331,13 @@ } }; - Buffer$e.concat = function concat (list, length) { - if (!isArray$3(list)) { + Buffer$k.concat = function concat (list, length) { + if (!isArray$4(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$e.alloc(0) + return Buffer$k.alloc(0) } var i; @@ -1346,7 +1348,7 @@ } } - var buffer = Buffer$e.allocUnsafe(length); + var buffer = Buffer$k.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1402,7 +1404,7 @@ } } } - Buffer$e.byteLength = byteLength$1; + Buffer$k.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1476,7 +1478,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$e.prototype._isBuffer = true; + Buffer$k.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1484,7 +1486,7 @@ b[m] = i; } - Buffer$e.prototype.swap16 = function swap16 () { + Buffer$k.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1495,7 +1497,7 @@ return this }; - Buffer$e.prototype.swap32 = function swap32 () { + Buffer$k.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1507,7 +1509,7 @@ return this }; - Buffer$e.prototype.swap64 = function swap64 () { + Buffer$k.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1521,20 +1523,20 @@ return this }; - Buffer$e.prototype.toString = function toString () { + Buffer$k.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$e.prototype.equals = function equals (b) { + Buffer$k.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$e.compare(this, b) === 0 + return Buffer$k.compare(this, b) === 0 }; - Buffer$e.prototype.inspect = function inspect () { + Buffer$k.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1544,7 +1546,7 @@ return '' }; - Buffer$e.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1643,7 +1645,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$e.from(val, encoding); + val = Buffer$k.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1655,7 +1657,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$e.TYPED_ARRAY_SUPPORT && + if (Buffer$k.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1725,15 +1727,15 @@ return -1 } - Buffer$e.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$e.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$e.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1784,7 +1786,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$e.prototype.write = function write (string, offset, length, encoding) { + Buffer$k.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1856,7 +1858,7 @@ } }; - Buffer$e.prototype.toJSON = function toJSON () { + Buffer$k.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -1995,7 +1997,7 @@ var out = ''; for (var i = start; i < end; ++i) { - out += toHex(buf[i]); + out += toHex$1(buf[i]); } return out } @@ -2009,7 +2011,7 @@ return res } - Buffer$e.prototype.slice = function slice (start, end) { + Buffer$k.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2031,12 +2033,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$e.prototype; + newBuf.__proto__ = Buffer$k.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$e(sliceLen, undefined); + newBuf = new Buffer$k(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2053,7 +2055,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$e.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2068,7 +2070,7 @@ return val }; - Buffer$e.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2084,22 +2086,22 @@ return val }; - Buffer$e.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$e.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$e.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$e.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2108,7 +2110,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$e.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2117,7 +2119,7 @@ this[offset + 3]) }; - Buffer$e.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2135,7 +2137,7 @@ return val }; - Buffer$e.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2153,25 +2155,25 @@ return val }; - Buffer$e.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$e.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$e.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$e.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2180,7 +2182,7 @@ (this[offset + 3] << 24) }; - Buffer$e.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2189,22 +2191,22 @@ (this[offset + 3]) }; - Buffer$e.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$e.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$e.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$e.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2215,7 +2217,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$e.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2234,7 +2236,7 @@ return offset + byteLength }; - Buffer$e.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2253,11 +2255,11 @@ return offset + byteLength }; - Buffer$e.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$e.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2270,11 +2272,11 @@ } } - Buffer$e.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2283,11 +2285,11 @@ return offset + 2 }; - Buffer$e.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2303,11 +2305,11 @@ } } - Buffer$e.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2318,11 +2320,11 @@ return offset + 4 }; - Buffer$e.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2333,7 +2335,7 @@ return offset + 4 }; - Buffer$e.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2356,7 +2358,7 @@ return offset + byteLength }; - Buffer$e.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2379,21 +2381,21 @@ return offset + byteLength }; - Buffer$e.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$e.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$e.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2402,11 +2404,11 @@ return offset + 2 }; - Buffer$e.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2415,11 +2417,11 @@ return offset + 2 }; - Buffer$e.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2430,12 +2432,12 @@ return offset + 4 }; - Buffer$e.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$k.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; - if (Buffer$e.TYPED_ARRAY_SUPPORT) { + if (Buffer$k.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2459,11 +2461,11 @@ return offset + 4 } - Buffer$e.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$e.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2475,16 +2477,16 @@ return offset + 8 } - Buffer$e.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$e.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$e.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2516,7 +2518,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$e.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2536,7 +2538,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$e.prototype.fill = function fill (val, start, end, encoding) { + Buffer$k.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2556,7 +2558,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$e.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2585,7 +2587,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$e(val, encoding).toString()); + : utf8ToBytes(new Buffer$k(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -2617,7 +2619,7 @@ return str.replace(/^\s+|\s+$/g, '') } - function toHex (n) { + function toHex$1 (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } @@ -2858,1657 +2860,963 @@ var bip32Path = BIPPath; - // flow - var MAX_SCRIPT_BLOCK = 50; - var DEFAULT_VERSION = 1; - var DEFAULT_LOCKTIME = 0; - var DEFAULT_SEQUENCE = 0xffffffff; - var SIGHASH_ALL = 1; - var OP_DUP = 0x76; - var OP_HASH160 = 0xa9; - var HASH_SIZE = 0x14; - var OP_EQUALVERIFY = 0x88; - var OP_CHECKSIG = 0xac; + var inherits_browser = {exports: {}}; - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.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 + } + }); } - }; - function signMessage(transport, _a) { - var path = _a.path, messageHex = _a.messageHex; - return __awaiter$a(this, void 0, void 0, function () { - var paths, message, offset, _loop_1, res, v, r, s; - return __generator$a(this, function (_b) { - switch (_b.label) { - case 0: - paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$e.from(messageHex, "hex"); - offset = 0; - _loop_1 = function () { - var maxChunkSize, chunkSize, buffer; - return __generator$a(this, function (_c) { - switch (_c.label) { - case 0: - maxChunkSize = offset === 0 - ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 - : MAX_SCRIPT_BLOCK; - chunkSize = offset + maxChunkSize > message.length - ? message.length - offset - : maxChunkSize; - buffer = Buffer$e.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); - if (offset === 0) { - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); - message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); - } - else { - message.copy(buffer, 0, offset, offset + chunkSize); - } - return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; - case 1: - _c.sent(); - offset += chunkSize; - return [2 /*return*/]; - } - }); - }; - _b.label = 1; - case 1: - if (!(offset !== message.length)) return [3 /*break*/, 3]; - return [5 /*yield**/, _loop_1()]; - case 2: - _b.sent(); - return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$e.from([0x00]))]; - case 4: - res = _b.sent(); - v = res[0] - 0x30; - r = res.slice(4, 4 + res[3]); - if (r[0] === 0) { - r = r.slice(1); - } - r = r.toString("hex"); - offset = 4 + res[3] + 2; - s = res.slice(offset, offset + res[offset - 1]); - if (s[0] === 0) { - s = s.slice(1); - } - s = s.toString("hex"); - return [2 /*return*/, { - v: v, - r: r, - s: s - }]; - } - }); - }); + }; + } else { + // old school shim for old browsers + inherits_browser.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; + } + }; } - function bip32asBuffer(path) { - var paths = !path ? [] : bip32Path.fromString(path).toPathArray(); - var buffer = Buffer$e.alloc(1 + paths.length * 4); - buffer[0] = paths.length; - paths.forEach(function (element, index) { - buffer.writeUInt32BE(element, 1 + 4 * index); - }); - return buffer; - } + var safeBuffer = {exports: {}}; - var __assign$4 = (undefined && undefined.__assign) || function () { - __assign$4 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$4.apply(this, arguments); - }; - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var addressFormatMap = { - legacy: 0, - p2sh: 1, - bech32: 2, - cashaddr: 3 - }; - function getWalletPublicKey(transport, options) { - return __awaiter$9(this, void 0, void 0, function () { - var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$9(this, function (_b) { - switch (_b.label) { - case 0: - _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; - if (!(format in addressFormatMap)) { - throw new Error("btc.getWalletPublicKey invalid format=" + format); - } - buffer = bip32asBuffer(path); - p1 = verify ? 1 : 0; - p2 = addressFormatMap[format]; - return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; - case 1: - response = _b.sent(); - publicKeyLength = response[0]; - addressLength = response[1 + publicKeyLength]; - publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); - bitcoinAddress = response - .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) - .toString("ascii"); - chainCode = response - .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) - .toString("hex"); - return [2 /*return*/, { - publicKey: publicKey, - bitcoinAddress: bitcoinAddress, - chainCode: chainCode - }]; - } - }); - }); + var buffer = {}; + + var base64Js = {}; + + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + + var code$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i$1 = 0, len = code$1.length; i$1 < len; ++i$1) { + lookup[i$1] = code$1[i$1]; + revLookup[code$1.charCodeAt(i$1)] = i$1; } - var id$1 = 0; - var subscribers = []; - /** - * log something - * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) - * @param message a clear message of the log associated to the type - */ - var log = function (type, message, data) { - var obj = { - type: type, - id: String(++id$1), - date: new Date() - }; - if (message) - obj.message = message; - if (data) - obj.data = data; - dispatch(obj); - }; - /** - * listen to logs. - * @param cb that is called for each future log() with the Log object - * @return a function that can be called to unsubscribe the listener - */ - var listen = function (cb) { - subscribers.push(cb); - return function () { - var i = subscribers.indexOf(cb); - if (i !== -1) { - // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 - subscribers[i] = subscribers[subscribers.length - 1]; - subscribers.pop(); - } - }; - }; - function dispatch(log) { - for (var i = 0; i < subscribers.length; i++) { - try { - subscribers[i](log); - } - catch (e) { - console.error(e); - } - } + // 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] } - if (typeof window !== "undefined") { - window.__ledgerLogsListen = listen; + + // 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 } - var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - log: log, - listen: listen - }); + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } - function getVarint(data, offset) { - if (data[offset] < 0xfd) { - return [data[offset], 1]; - } - if (data[offset] === 0xfd) { - return [(data[offset + 2] << 8) + data[offset + 1], 3]; - } - if (data[offset] === 0xfe) { - return [ - (data[offset + 4] << 24) + - (data[offset + 3] << 16) + - (data[offset + 2] << 8) + - data[offset + 1], - 5, - ]; - } - throw new Error("getVarint called with unexpected parameters"); + 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 createVarint(value) { - if (value < 0xfd) { - var buffer_1 = Buffer$e.alloc(1); - buffer_1[0] = value; - return buffer_1; - } - if (value <= 0xffff) { - var buffer_2 = Buffer$e.alloc(3); - buffer_2[0] = 0xfd; - buffer_2[1] = value & 0xff; - buffer_2[2] = (value >> 8) & 0xff; - return buffer_2; - } - var buffer = Buffer$e.alloc(5); - buffer[0] = 0xfe; - buffer[1] = value & 0xff; - buffer[2] = (value >> 8) & 0xff; - buffer[3] = (value >> 16) & 0xff; - buffer[4] = (value >> 24) & 0xff; - return buffer; + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] } - function formatTransactionDebug(transaction) { - var str = "TX"; - str += " version " + transaction.version.toString("hex"); - if (transaction.locktime) { - str += " locktime " + transaction.locktime.toString("hex"); - } - if (transaction.witness) { - str += " witness " + transaction.witness.toString("hex"); - } - if (transaction.timestamp) { - str += " timestamp " + transaction.timestamp.toString("hex"); - } - if (transaction.nVersionGroupId) { - str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); - } - if (transaction.nExpiryHeight) { - str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); - } - if (transaction.extraData) { - str += " extraData " + transaction.extraData.toString("hex"); - } - transaction.inputs.forEach(function (_a, i) { - var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; - str += "\ninput ".concat(i, ":"); - str += " prevout ".concat(prevout.toString("hex")); - str += " script ".concat(script.toString("hex")); - str += " sequence ".concat(sequence.toString("hex")); - }); - (transaction.outputs || []).forEach(function (_a, i) { - var amount = _a.amount, script = _a.script; - str += "\noutput ".concat(i, ":"); - str += " amount ".concat(amount.toString("hex")); - str += " script ".concat(script.toString("hex")); - }); - return str; + 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 splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { - if (isSegwitSupported === void 0) { isSegwitSupported = false; } - if (hasTimestamp === void 0) { hasTimestamp = false; } - if (hasExtraData === void 0) { hasExtraData = false; } - if (additionals === void 0) { additionals = []; } - var inputs = []; - var outputs = []; - var witness = false; - var offset = 0; - var timestamp = Buffer$e.alloc(0); - var nExpiryHeight = Buffer$e.alloc(0); - var nVersionGroupId = Buffer$e.alloc(0); - var extraData = Buffer$e.alloc(0); - var isDecred = additionals.includes("decred"); - var transaction = Buffer$e.from(transactionHex, "hex"); - var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$e.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$e.from([0x04, 0x00, 0x00, 0x80])); - offset += 4; - if (!hasTimestamp && - isSegwitSupported && - transaction[offset] === 0 && - transaction[offset + 1] !== 0) { - offset += 2; - witness = true; - } - if (hasTimestamp) { - timestamp = transaction.slice(offset, 4 + offset); - offset += 4; - } - if (overwinter) { - nVersionGroupId = transaction.slice(offset, 4 + offset); - offset += 4; - } - var varint = getVarint(transaction, offset); - var numberInputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberInputs; i++) { - var prevout = transaction.slice(offset, offset + 36); - offset += 36; - var script = Buffer$e.alloc(0); - var tree = Buffer$e.alloc(0); - //No script for decred, it has a witness - if (!isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - } - else { - //Tree field - tree = transaction.slice(offset, offset + 1); - offset += 1; - } - var sequence = transaction.slice(offset, offset + 4); - offset += 4; - inputs.push({ - prevout: prevout, - script: script, - sequence: sequence, - tree: tree - }); - } - varint = getVarint(transaction, offset); - var numberOutputs = varint[0]; - offset += varint[1]; - for (var i = 0; i < numberOutputs; i++) { - var amount = transaction.slice(offset, offset + 8); - offset += 8; - if (isDecred) { - //Script version - offset += 2; - } - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - outputs.push({ - amount: amount, - script: script - }); - } - var witnessScript, locktime; - if (witness) { - witnessScript = transaction.slice(offset, -4); - locktime = transaction.slice(transaction.length - 4); - } - else { - locktime = transaction.slice(offset, offset + 4); - } - offset += 4; - if (overwinter || isDecred) { - nExpiryHeight = transaction.slice(offset, offset + 4); - offset += 4; - } - if (hasExtraData) { - extraData = transaction.slice(offset); - } - //Get witnesses for Decred - if (isDecred) { - varint = getVarint(transaction, offset); - offset += varint[1]; - if (varint[0] !== numberInputs) { - throw new Error("splitTransaction: incoherent number of witnesses"); - } - for (var i = 0; i < numberInputs; i++) { - //amount - offset += 8; - //block height - offset += 4; - //block index - offset += 4; - //Script size - varint = getVarint(transaction, offset); - offset += varint[1]; - var script = transaction.slice(offset, offset + varint[0]); - offset += varint[0]; - inputs[i].script = script; - } - } - var t = { - version: version, - inputs: inputs, - outputs: outputs, - locktime: locktime, - witness: witnessScript, - timestamp: timestamp, - nVersionGroupId: nVersionGroupId, - nExpiryHeight: nExpiryHeight, - extraData: extraData - }; - log("btc", "splitTransaction ".concat(transactionHex, ":\n").concat(formatTransactionDebug(t))); - return t; - } + 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 - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + // 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))); + } - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; + // 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('') } - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + var ieee754 = {}; + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + ieee754.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) {} - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; + 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) + }; + + ieee754.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; } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); + if (e + eBias >= 1) { + value += rt / c; } else { - queueIndex = -1; + value += rt * Math.pow(2, 1 - eBias); } - if (queue.length) { - drainQueue(); + if (value * c >= 2) { + e++; + c /= 2; } - } - function drainQueue() { - if (draining) { - return; + 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; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + } - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); + 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; }; - var title = 'browser'; - var platform = 'browser'; - var browser$3 = true; - var env = {}; - var argv = []; - var version = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - function noop() {} + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ - var on = noop; - var addListener = noop; - var once$1 = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; + (function (exports) { - function binding(name) { - throw new Error('process.binding is not supported'); - } + var base64 = base64Js; + var ieee754$1 = ieee754; + var 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; - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } + exports.Buffer = Buffer; + exports.SlowBuffer = SlowBuffer; + exports.INSPECT_MAX_BYTES = 50; - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; + var K_MAX_LENGTH = 0x7fffffff; + exports.kMaxLength = K_MAX_LENGTH; - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] + /** + * 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.' + ); } - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1); + var proto = { foo: function () { return 42 } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42 + } catch (e) { + return false + } } - var process = { - nextTick: nextTick, - title: title, - browser: browser$3, - env: env, - argv: argv, - version: version, - versions: versions, - on: on, - addListener: addListener, - once: once$1, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; + 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 + var buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf + } /** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. + * 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 invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. + * The `Uint8Array` prototype remains unmodified. */ - var invariant = function(condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument'); + 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) + } - if (!condition) { - var error; - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ); - } else { - var args = [a, b, c, d, e, f]; - var argIndex = 0; - error = new Error( - format.replace(/%s/g, function() { return args[argIndex++]; }) - ); - error.name = 'Invariant Violation'; - } + Buffer.poolSize = 8192; // not used by this implementation - error.framesToPop = 1; // we don't care about invariant's own frame - throw error; + function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) } - }; - var browser$2 = invariant; + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$5 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$8(this, void 0, void 0, function () { - var data, firstRound, prefix, trustedInput, res; - return __generator$8(this, function (_a) { - switch (_a.label) { - case 0: - firstRound = false; - if (typeof indexLookup === "number") { - firstRound = true; - prefix = Buffer$e.alloc(4); - prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$e.concat([prefix, transactionData], transactionData.length + 4); - } - else { - data = transactionData; - } - return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; - case 1: - trustedInput = _a.sent(); - res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); - return [2 /*return*/, res]; - } - }); - }); - } - function getTrustedInput(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$8(this, void 0, void 0, function () { - var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; - var e_1, _a, e_2, _b; - var _this = this; - return __generator$8(this, function (_c) { - switch (_c.label) { - case 0: - version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; - if (!outputs || !locktime) { - throw new Error("getTrustedInput: locktime & outputs is expected"); - } - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$8(_this, void 0, void 0, function () { - var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; - var e_3, _a; - return __generator$8(this, function (_b) { - switch (_b.label) { - case 0: - seq = sequence || Buffer$e.alloc(0); - scriptBlocks = []; - offset = 0; - while (offset !== script.length) { - blockSize = script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : script.length - offset; - if (offset + blockSize !== script.length) { - scriptBlocks.push(script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$e.concat([script.slice(offset, offset + blockSize), seq])); - } - offset += blockSize; - } - // Handle case when no script length: we still want to pass the sequence - // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 - if (script.length === 0) { - scriptBlocks.push(seq); - } - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - scriptBlocks_1 = __values$5(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); - _b.label = 2; - case 2: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; - case 3: - res = _b.sent(); - _b.label = 4; - case 4: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_3_1 = _b.sent(); - e_3 = { error: e_3_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); - } - finally { if (e_3) throw e_3.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, res]; - } - }); - }); }; - processWholeScriptBlock = function (block) { - return getTrustedInputRaw(transport, block); - }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$e.concat([ - transaction.version, - transaction.timestamp || Buffer$e.alloc(0), - transaction.nVersionGroupId || Buffer$e.alloc(0), - createVarint(inputs.length), - ]), indexLookup)]; - case 1: - _c.sent(); - _c.label = 2; - case 2: - _c.trys.push([2, 8, 9, 10]); - inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 3; - case 3: - if (!!inputs_1_1.done) return [3 /*break*/, 7]; - input = inputs_1_1.value; - isXSTV2 = isXST && - Buffer$e.compare(version, Buffer$e.from([0x02, 0x00, 0x00, 0x00])) === 0; - treeField = isDecred - ? input.tree || Buffer$e.from([0x00]) - : Buffer$e.alloc(0); - data = Buffer$e.concat([ - input.prevout, - treeField, - isXSTV2 ? Buffer$e.from([0x00]) : createVarint(input.script.length), - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 4: - _c.sent(); - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$e.concat([input.script, input.sequence])) - : isXSTV2 - ? processWholeScriptBlock(input.sequence) - : processScriptBlocks(input.script, input.sequence))]; - case 5: - // iteration (eachSeries) ended - // TODO notify progress - // deferred.notify("input"); - // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 - _c.sent(); - _c.label = 6; - case 6: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 3]; - case 7: return [3 /*break*/, 10]; - case 8: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 10]; - case 9: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - _c.trys.push([12, 17, 18, 19]); - outputs_1 = __values$5(outputs), outputs_1_1 = outputs_1.next(); - _c.label = 13; - case 13: - if (!!outputs_1_1.done) return [3 /*break*/, 16]; - output = outputs_1_1.value; - data = Buffer$e.concat([ - output.amount, - isDecred ? Buffer$e.from([0x00, 0x00]) : Buffer$e.alloc(0), - createVarint(output.script.length), - output.script, - ]); - return [4 /*yield*/, getTrustedInputRaw(transport, data)]; - case 14: - _c.sent(); - _c.label = 15; - case 15: - outputs_1_1 = outputs_1.next(); - return [3 /*break*/, 13]; - case 16: return [3 /*break*/, 19]; - case 17: - e_2_1 = _c.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 19]; - case 18: - try { - if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 19: - endData = []; - if (nExpiryHeight && nExpiryHeight.length > 0) { - endData.push(nExpiryHeight); - } - if (extraData && extraData.length > 0) { - endData.push(extraData); - } - if (endData.length) { - data = Buffer$e.concat(endData); - extraPart = isDecred - ? data - : Buffer$e.concat([createVarint(data.length), data]); - } - return [4 /*yield*/, processScriptBlocks(Buffer$e.concat([locktime, extraPart || Buffer$e.alloc(0)]))]; - case 20: - res = _c.sent(); - browser$2(res, "missing result in processScriptBlocks"); - return [2 /*return*/, res]; - } - }); - }); - } + 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) + ) + } - var sha_js = {exports: {}}; + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - var inherits_browser = {exports: {}}; + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - inherits_browser.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 - inherits_browser.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; - } - }; - } + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } - var safeBuffer = {exports: {}}; - - var buffer = {}; - - var base64Js = {}; + var valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - base64Js.byteLength = byteLength; - base64Js.toByteArray = toByteArray; - base64Js.fromByteArray = fromByteArray; + var b = fromObject(value); + if (b) return b - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i$1 = 0, len = code.length; i$1 < len; ++i$1) { - lookup[i$1] = code[i$1]; - revLookup[code.charCodeAt(i$1)] = i$1; + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) } - // 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; + /** + * 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) + }; - function getLens (b64) { - var len = b64.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); - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') + 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"') } - - // 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 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) } - 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)); + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + }; - var curByte = 0; + function allocUnsafe (size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen; + /** + * 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) + }; - 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; + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; } - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[curByte++] = tmp & 0xFF; + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) } - 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; + var length = byteLength(string, encoding) | 0; + var buf = createBuffer(length); + + var 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 arr + return buf } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] + function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + var buf = createBuffer(length); + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf } - 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)); + function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + var copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) } - return output.join('') + return fromArrayLike(arrayView) } - 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 + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - // 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))); + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') } - // 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] + - '=' - ); + var 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 parts.join('') + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); + + return buf } - var ieee754 = {}; + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0; + var buf = createBuffer(len); - /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + if (buf.length === 0) { + return buf + } - ieee754.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]; + obj.copy(buf, 0, 0, len); + return buf + } - 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) - }; - - ieee754.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; + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) } + return fromArrayLike(obj) } - 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; - }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - (function (exports) { - - var base64 = base64Js; - var ieee754$1 = ieee754; - var 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; - - var 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.' - ); + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } } - function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1); - var proto = { foo: function () { return 42 } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42 - } catch (e) { - return false + 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 } - Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; } - }); + return Buffer.alloc(+length) + } - Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } - }); + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false + }; - function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') + 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' + ) } - // Return an augmented `Uint8Array` instance - var 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. - */ + if (a === b) return 0 - 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' - ) + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break } - return allocUnsafe(arg) } - return from(arg, encodingOrOffset, length) - } - Buffer.poolSize = 8192; // not used by this implementation + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; - function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) + 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 } + }; - if (ArrayBuffer.isView(value)) { - return fromArrayView(value) + Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - 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 (list.length === 0) { + return Buffer.alloc(0) } - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - if (typeof SharedArrayBuffer !== 'undefined' && - (isInstance(value, SharedArrayBuffer) || - (value && isInstance(value.buffer, SharedArrayBuffer)))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + Buffer.from(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 + }; - if (typeof value === 'number') { + 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 "value" argument must not be of type number. Received type number' + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string ) } - var valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value); - if (b) return b + var len = string.length; + var mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) + // Use a for loop to avoid recursion + var 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; + } } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) } + Buffer.byteLength = byteLength; - /** - * 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) - }; + function slowToString (encoding, start, end) { + var loweredCase = false; - // 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); + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - 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"') + // 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 '' } - } - function alloc (size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size) + if (end === undefined || end > this.length) { + end = this.length; } - 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) + + if (end <= 0) { + return '' } - return createBuffer(size) - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) - }; + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - function allocUnsafe (size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0) - } + if (end <= start) { + return '' + } - /** - * 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) - }; + if (!encoding) encoding = 'utf8'; - function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - var length = byteLength(string, encoding) | 0; - var buf = createBuffer(length); + case 'ascii': + return asciiSlice(this, start, end) - var actual = buf.write(string, encoding); + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - 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); - } + case 'base64': + return base64Slice(this, start, end) - return buf - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - var buf = createBuffer(length); - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } } - return buf } - function fromArrayView (arrayView) { - if (isInstance(arrayView, Uint8Array)) { - var copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) - } - return fromArrayLike(arrayView) - } + // 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 fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') } - - var 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); + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); } + return this + }; - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype); + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; - return buf - } + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var 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 + }; - function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0; - var buf = createBuffer(len); + Buffer.prototype.toString = function toString () { + var length = this.length; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; - if (buf.length === 0) { - return buf - } + Buffer.prototype.toLocaleString = Buffer.prototype.toString; - obj.copy(buf, 0, 0, len); - return buf - } + 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 + }; - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) + Buffer.prototype.inspect = function inspect () { + var str = ''; + var 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 (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; } - } - 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') + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - return length | 0 - } - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0; + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - 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 - }; + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - 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 (this === target) return 0 - if (a === b) return 0 + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - var x = a.length; - var y = b.length; + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; break } } @@ -4518,5442 +3826,5430 @@ 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 - } - }; + // 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 - Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') + // 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); } - if (list.length === 0) { - return Buffer.alloc(0) + // 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 } - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); } - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - Buffer.from(buf).copy(buffer, pos); + // 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 { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } - } 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 arrayIndexOf(buffer, [val], byteOffset, encoding, dir) } - 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 - ) - } + throw new TypeError('val must be string, number or Buffer') + } - var len = string.length; - var mustMatch = (arguments.length > 2 && arguments[2] === true); - if (!mustMatch && len === 0) return 0 + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - // Use a for loop to avoid recursion - var 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 + 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) + } + } + + var i; + if (dir) { + var 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--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break } - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; + } + if (found) return i } } + + return -1 } - Buffer.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; - // 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 '' + 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; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } } - if (end === undefined || end > this.length) { - end = this.length; + var strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed; } + return i + } - if (end <= 0) { - return '' + 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' + ) } - // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if (end <= start) { - return '' + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8'; - while (true) { + var loweredCase = false; + for (;;) { switch (encoding) { case 'hex': - return hexSlice(this, start, end) + return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': - return utf8Slice(this, start, end) + return utf8Write(this, string, offset, length) case 'ascii': - return asciiSlice(this, start, end) - case 'latin1': case 'binary': - return latin1Slice(this, start, end) + return asciiWrite(this, string, offset, length) case 'base64': - return base64Slice(this, start, end) + // 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 utf16leSlice(this, start, end) + return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); + 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) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this }; - Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } - return this }; - Buffer.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var 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); + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) } - return this - }; + } - Buffer.prototype.toString = function toString () { - var length = this.length; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; - Buffer.prototype.toLocaleString = Buffer.prototype.toString; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1; - 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 - }; + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - Buffer.prototype.inspect = function inspect () { - var str = ''; - var 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; - } + 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; + } + } + } + } - 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 (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; } - if (start === undefined) { - start = 0; + 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 + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - if (end === undefined) { - end = target ? target.length : 0; + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); } - if (thisStart === undefined) { - thisStart = 0; + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); } - if (thisEnd === undefined) { - thisEnd = this.length; + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); } + return ret + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; } + return out + } - if (thisStart >= thisEnd && start >= end) { - return 0 + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (var i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); } - if (thisStart >= thisEnd) { - return -1 + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var 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 (start >= end) { - return 1 + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + if (end < start) end = start; - if (this === target) return 0 + var newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + return newBuf + }; - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + /* + * 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') + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } + Buffer.prototype.readUintLE = + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } - if (x < y) return -1 - if (y < x) return 1 - return 0 + return val }; - // 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 + Buffer.prototype.readUintBE = + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } - // 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); + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - // 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 - } + return val + }; - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } + Buffer.prototype.readUint8 = + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; - // 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) - } + 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) + }; - throw new TypeError('val must be string, number or Buffer') - } + 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] + }; - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + Buffer.prototype.readUint32LE = + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.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; - } - } + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } + 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.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } + mul *= 0x80; - var i; - if (dir) { - var 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--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } + 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); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; } + mul *= 0x80; - return -1 - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 + return val }; - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + 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.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val }; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; - var strLen = string.length; + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i - } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, true, 23, 4) + }; - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, false, 23, 4) + }; - 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' - ) - } + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, true, 52, 8) + }; - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, false, 52, 8) + }; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + 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') + } - if (!encoding) encoding = 'utf8'; + Buffer.prototype.writeUintLE = + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + return offset + byteLength + }; - case 'ascii': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length) + Buffer.prototype.writeUintBE = + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + return offset + byteLength + }; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + 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.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } + 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 }; - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } + 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 + }; - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; + 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 + }; - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) - ? 4 - : (firstByte > 0xDF) - ? 3 - : (firstByte > 0xBF) - ? 2 - : 1; + 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 + }; - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - 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; - } - } - } - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - 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; + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; } - - res.push(codePoint); - i += bytesPerSequence; + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } - return decodeCodePointsArray(res) - } + return offset + byteLength + }; - // 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 - var MAX_ARGUMENTS_LENGTH = 0x1000; + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1); - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - for (var 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) { - var 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; - - var 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); - - var val = this[offset]; + var i = byteLength - 1; var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + var 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 val + return offset + byteLength }; - Buffer.prototype.readUintBE = - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val + 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.readUint8 = - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + return offset + 2 }; - Buffer.prototype.readUint16LE = - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + return offset + 2 }; - Buffer.prototype.readUint16BE = - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] + 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.readUint32LE = - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; 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) + 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.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]) - }; + 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') + } - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value; offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); } - mul *= 0x80; + ieee754$1.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; - return val + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) }; - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value; offset = offset >>> 0; - byteLength = byteLength >>> 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; + ieee754$1.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } - 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.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) }; - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) }; - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - var 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) - }; + // 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; - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; + // 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') - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, true, 23, 4) - }; + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, false, 23, 4) - }; + var len = end - start; - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.read(this, offset, true, 52, 8) - }; + 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 + ); + } - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.read(this, offset, false, 52, 8) + return len }; - 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) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); + // 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) { + var 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); } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + // 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') } - 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) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); + if (end <= start) { + return this } - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; - return offset + byteLength - }; + if (!val) val = 0; - 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 - }; + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding); + var 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]; + } + } - 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 + return this }; - 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 - }; + // HELPER FUNCTIONS + // ================ - 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 - }; + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - 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 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 + } - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1); + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); - var i = 0; - var mul = 1; - var 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; - } + // 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 + } - return offset + byteLength - }; + // valid lead + leadSurrogate = codePoint; - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1); + continue + } - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; + // 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); } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - return offset + byteLength - }; + leadSurrogate = null; - 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 - }; + // 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') + } + } - 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 - }; + return bytes + } - 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 - }; + function asciiToBytes (str) { + var byteArray = []; + for (var 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 + } - 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 - }; + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - 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 - }; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - 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') + return byteArray } - function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - ieee754$1.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) } - 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); + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; } - ieee754$1.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 + return i } - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; + // 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 + } - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; + // Create lookup table for `toString('hex')` + // See: https://github.com/feross/buffer/issues/219 + var hexSliceLookupTable = (function () { + var alphabet = '0123456789abcdef'; + var table = new Array(256); + for (var i = 0; i < 16; ++i) { + var i16 = i * 16; + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table + })(); + }(buffer)); - // 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; + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer$1 = buffer; + var Buffer = buffer$1.Buffer; - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') + // alternative to using Object.keys for old browsers + function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key]; } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer$1; + } else { + // Copy properties from require('buffer') + copyProps(buffer$1, exports); + exports.Buffer = SafeBuffer; + } - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } - var len = end - start; + SafeBuffer.prototype = Object.create(Buffer.prototype); - 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 - ); - } + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); - return len + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) }; - // 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) { - var 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; - } + 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 if (typeof val === 'number') { - val = val & 255; - } else if (typeof val === 'boolean') { - val = Number(val); + } else { + buf.fill(0); } + return buf + }; - // 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') + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) + }; - if (end <= start) { - return this + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return buffer$1.SlowBuffer(size) + }; + }(safeBuffer, safeBuffer.exports)); - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - if (!val) val = 0; + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding); - var len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - var 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; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var 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 + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } + } - // 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 - } + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; - // 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); + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - - 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 - ); + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); } else { - throw new Error('Invalid code point') + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } - } - - return bytes } - function asciiToBytes (str) { - var byteArray = []; - for (var 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 drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$5 = true; + var env = {}; + var argv = []; + var version$1 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config$1 = {}; - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + function noop() {} - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } + var on = noop; + var addListener = noop; + var once$1 = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; - return byteArray + function binding(name) { + throw new Error('process.binding is not supported'); } - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } } - return i + return [seconds,nanoseconds] } - // 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 + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; } - // Create lookup table for `toString('hex')` - // See: https://github.com/feross/buffer/issues/219 - var hexSliceLookupTable = (function () { - var alphabet = '0123456789abcdef'; - var table = new Array(256); - for (var i = 0; i < 16; ++i) { - var i16 = i * 16; - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - return table - })(); - }(buffer)); + var process = { + nextTick: nextTick, + title: title, + browser: browser$5, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once$1, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config$1, + uptime: uptime + }; - /*! safe-buffer. MIT License. Feross Aboukhadijeh */ + var readable = {exports: {}}; - (function (module, exports) { - /* eslint-disable node/no-deprecated-api */ - var buffer$1 = buffer; - var Buffer = buffer$1.Buffer; + var events = {exports: {}}; - // 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$1; + 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 { - // Copy properties from require('buffer') - copyProps(buffer$1, exports); - exports.Buffer = SafeBuffer; + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; } - function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); } - SafeBuffer.prototype = Object.create(Buffer.prototype); + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; + }; - // Copy static methods from Buffer - copyProps(Buffer, SafeBuffer); + function EventEmitter() { + EventEmitter.init.call(this); + } + events.exports = EventEmitter; + events.exports.once = once; - SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + // 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); } - return Buffer(arg, encodingOrOffset, length) - }; + } - SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + 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; } - 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') + EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; } - return Buffer(size) + + this._maxListeners = this._maxListeners || undefined; }; - SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + // 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 + '.'); } - return buffer$1.SlowBuffer(size) + this._maxListeners = n; + return this; }; - }(safeBuffer, safeBuffer.exports)); - var Buffer$d = safeBuffer.exports.Buffer; - - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; + function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; } - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); - } + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; + EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; + // 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 + } - accum += remainder; - offset += remainder; + var handler = events[type]; - if ((accum % blockSize) === 0) { - this._update(block); - } + 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); } - this._len += length; - return this + return true; }; - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; - this._block[rem] = 0x80; + checkListener(listener); - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + 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); - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); + // 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]; } - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); - - // uint64 + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + 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); + } - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); + // 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); + } } - this._update(this._block); - var hash = this._hash(); + return target; + } - return enc ? hash.toString(enc) : hash + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); }; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + EventEmitter.prototype.on = EventEmitter.prototype.addListener; - var hash = Hash$7; + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + 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); + } + } - var inherits$c = inherits_browser.exports; - var Hash$6 = hash; - var Buffer$c = safeBuffer.exports.Buffer; + 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; + } - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; - var W$5 = new Array(80); + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; - function Sha () { - this.init(); - this._w = W$5; + // 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; - Hash$6.call(this, 64, 56); - } + checkListener(listener); - inherits$c(Sha, Hash$6); + events = this._events; + if (events === undefined) + return this; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + list = events[type]; + if (list === undefined) + return this; - 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; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } + if (position < 0) + return this; - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } - Sha.prototype._update = function (M) { - var W = this._w; + if (list.length === 1) + events[type] = list[0]; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + return this; + }; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$3[s]) | 0; + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + events = this._events; + if (events === undefined) + return this; - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + // 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; + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // 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; + } - return H - }; + listeners = events[type]; - var sha$2 = Sha; + 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]); + } + } - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + return this; + }; - var inherits$b = inherits_browser.exports; - var Hash$5 = hash; - var Buffer$b = safeBuffer.exports.Buffer; + function _listeners(target, type, unwrap) { + var events = target._events; - var K$2 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + if (events === undefined) + return []; - var W$4 = new Array(80); + var evlistener = events[type]; + if (evlistener === undefined) + return []; - function Sha1 () { - this.init(); - this._w = W$4; + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - Hash$5.call(this, 64, 56); + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } - inherits$b(Sha1, Hash$5); + EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; - return this + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } }; - function rotl1 (num) { - return (num << 1) | (num >>> 31) - } + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; - function rotl5 (num) { - return (num << 5) | (num >>> 27) - } + if (events !== undefined) { + var evlistener = events[type]; - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + return 0; } - Sha1.prototype._update = function (M) { - var W = this._w; - - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; + } - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$2[s]) | 0; + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; + 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; + } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + 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 }); + } + }); + } - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } + } - return H - }; + 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); + } + } - var sha1 = Sha1; + var EventEmitter$1 = events.exports; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + var inherits$h; + if (typeof Object.create === 'function'){ + inherits$h = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$h = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$i = inherits$h; - var inherits$a = inherits_browser.exports; - var Hash$4 = hash; - var Buffer$a = safeBuffer.exports.Buffer; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } - var K$1 = [ - 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 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$1(x) || !isObject$2(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } - var W$3 = new Array(64); + // 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined$1(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } - function Sha256$1 () { - this.init(); + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - this._w = W$3; // new Array(64) + return deprecated; + } - Hash$4.call(this, 64, 56); + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined$1(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; } - inherits$a(Sha256$1, Hash$4); + /** + * 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$1(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined$1(ctx.depth)) ctx.depth = 2; + if (isUndefined$1(ctx.colors)) ctx.colors = false; + if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + // 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] + }; - return this + // 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 ch (x, y, z) { - return z ^ (x & (y ^ z)) - } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) - } + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } } - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) - } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + function stylizeNoColor(str, styleType) { + return str; } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) - } - Sha256$1.prototype._update = function (M) { - var W = this._w; + function arrayToHash(array) { + var hash = {}; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + array.forEach(function(val, idx) { + hash[val] = true; + }); - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + return hash; + } - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$1[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + 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$2(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== 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$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; - }; - - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); - - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - return H - }; + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - var sha256 = Sha256$1; + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError$1(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - var inherits$9 = inherits_browser.exports; - var Sha256 = sha256; - var Hash$3 = hash; - var Buffer$9 = safeBuffer.exports.Buffer; + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$2(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate$1(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError$1(value)) { + return formatError(value); + } + } - var W$2 = new Array(64); + var base = '', array = false, braces = ['{', '}']; - function Sha224 () { - this.init(); + // Make Array say that they are Array + if (isArray$3(value)) { + array = true; + braces = ['[', ']']; + } - this._w = W$2; // new Array(64) + // Make functions say that they are functions + if (isFunction$2(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - Hash$3.call(this, 64, 56); - } + // Make RegExps say that they are RegExps + if (isRegExp$1(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - inherits$9(Sha224, Sha256); + // Make dates with properties first say the date + if (isDate$1(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + // Make error with message first say the error + if (isError$1(value)) { + base = ' ' + formatError(value); + } - return this - }; + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + if (recurseTimes < 0) { + if (isRegExp$1(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + ctx.seen.push(value); - return H - }; + 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); + }); + } - var sha224 = Sha224; + ctx.seen.pop(); - var inherits$8 = inherits_browser.exports; - var Hash$2 = hash; - var Buffer$8 = safeBuffer.exports.Buffer; + return reduceToSingleString(output, base, braces); + } - 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 W$1 = new Array(160); + function formatPrimitive(ctx, value) { + if (isUndefined$1(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber$1(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean$1(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull$1(value)) + return ctx.stylize('null', 'null'); + } - function Sha512 () { - this.init(); - this._w = W$1; - Hash$2.call(this, 128, 112); + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } - inherits$8(Sha512, Hash$2); - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + 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; + } - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; - return this - }; + 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$1(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$1(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'); + } + } - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) + return name + ': ' + str; } - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) - } + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$3(ar) { + return Array.isArray(ar); } - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + function isBoolean$1(arg) { + return typeof arg === 'boolean'; } - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + function isNull$1(arg) { + return arg === null; } - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + function isNumber$1(arg) { + return typeof arg === 'number'; } - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + function isString$1(arg) { + return typeof arg === 'string'; } - Sha512.prototype._update = function (M) { - var W = this._w; + function isUndefined$1(arg) { + return arg === void 0; + } - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + function isRegExp$1(re) { + return isObject$2(re) && objectToString$1(re) === '[object RegExp]'; + } - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + function isObject$2(arg) { + return typeof arg === 'object' && arg !== null; + } - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + function isDate$1(d) { + return isObject$2(d) && objectToString$1(d) === '[object Date]'; + } - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + function isError$1(e) { + return isObject$2(e) && + (objectToString$1(e) === '[object Error]' || e instanceof Error); + } - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + function isFunction$2(arg) { + return typeof arg === 'function'; + } - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + function objectToString$1(o) { + return Object.prototype.toString.call(o); + } - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$2(add)) return origin; - W[i] = Wih; - W[i + 1] = Wil; + 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); + } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; - - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); - - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j]; - var Kil = K[j + 1]; + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; - } - - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; }; - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; } - - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H + return ret; }; - var sha512 = Sha512; + var string_decoder = {}; - var inherits$7 = inherits_browser.exports; - var SHA512 = sha512; - var Hash$1 = hash; - var Buffer$7 = safeBuffer.exports.Buffer; + var StringDecoder_1; + // 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 W = new Array(160); + var Buffer$j = buffer.Buffer; - function Sha384 () { - this.init(); - this._w = W; + var isBufferEncoding = Buffer$j.isEncoding + || function(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; + } + }; - Hash$1.call(this, 128, 112); + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } } - inherits$7(Sha384, SHA512); + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$j(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + }; - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; - return this - }; + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder$2.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); - } + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); - return H - }; + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - var sha384 = Sha384; + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - return new Algorithm() - }; + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } - exports$1.sha = sha$2; - exports$1.sha1 = sha1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + charStr += buffer.toString(this.encoding, 0, end); - var sha$1 = sha_js.exports; + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - /** - @example - const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); - const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); - */ - function serializeTransactionOutputs(_a) { - var outputs = _a.outputs; - var outputBuffer = Buffer$e.alloc(0); - if (typeof outputs !== "undefined") { - outputBuffer = Buffer$e.concat([outputBuffer, createVarint(outputs.length)]); - outputs.forEach(function (output) { - outputBuffer = Buffer$e.concat([ - outputBuffer, - output.amount, - createVarint(output.script.length), - output.script, - ]); - }); - } - return outputBuffer; - } - function serializeTransaction(transaction, skipWitness, timestamp, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$e.alloc(0); - var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; - transaction.inputs.forEach(function (input) { - inputBuffer = - isDecred || isBech32 - ? Buffer$e.concat([ - inputBuffer, - input.prevout, - Buffer$e.from([0x00]), - input.sequence, - ]) - : Buffer$e.concat([ - inputBuffer, - input.prevout, - createVarint(input.script.length), - input.script, - input.sequence, - ]); - }); - var outputBuffer = serializeTransactionOutputs(transaction); - if (typeof transaction.outputs !== "undefined" && - typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$e.concat([ - outputBuffer, - (useWitness && transaction.witness) || Buffer$e.alloc(0), - transaction.locktime, - transaction.nExpiryHeight || Buffer$e.alloc(0), - transaction.extraData || Buffer$e.alloc(0), - ]); - } - return Buffer$e.concat([ - transaction.version, - timestamp ? timestamp : Buffer$e.alloc(0), - transaction.nVersionGroupId || Buffer$e.alloc(0), - useWitness ? Buffer$e.from("0001", "hex") : Buffer$e.alloc(0), - createVarint(transaction.inputs.length), - inputBuffer, - outputBuffer, - ]); - } + // or just emit the charStr + return charStr; + }; - function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { - if (additionals === void 0) { additionals = []; } - if (!transaction) { - throw new Error("getTrustedInputBIP143: missing tx"); - } - var isDecred = additionals.includes("decred"); - if (isDecred) { - throw new Error("Decred does not implement BIP143"); + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; } - var hash = sha$1("sha256") - .update(sha$1("sha256").update(serializeTransaction(transaction, true)).digest()) - .digest(); - var data = Buffer$e.alloc(4); - data.writeUInt32LE(indexLookup, 0); - var outputs = transaction.outputs, locktime = transaction.locktime; - if (!outputs || !locktime) { - throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; } - if (!outputs[indexLookup]) { - throw new Error("getTrustedInputBIP143: wrong index"); + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; } - hash = Buffer$e.concat([hash, data, outputs[indexLookup].amount]); - return hash.toString("hex"); - } + } + this.charReceived = i; + }; - var readable = {exports: {}}; + StringDecoder$2.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - var events = {exports: {}}; + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } - 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); - }; + return res; + }; - 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 passThroughWrite(buffer) { + return buffer.toString(this.encoding); } - function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } - var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; - }; - - function EventEmitter() { - EventEmitter.init.call(this); + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } - events.exports = EventEmitter; - events.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; + Readable$2.ReadableState = ReadableState$1; - // 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; + var debug$4 = debuglog('stream'); + inherits$i(Readable$2, EventEmitter$1); - function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; } } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState$1(options, stream) { - 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() { + options = options || {}; - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - this._maxListeners = this._maxListeners || undefined; - }; + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - // 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; - }; + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; - } + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); - }; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = 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 - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var handler = events[type]; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - if (handler === undefined) - return false; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - 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); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; } + } + function Readable$2(options) { - return true; - }; + if (!(this instanceof Readable$2)) return new Readable$2(options); - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; + this._readableState = new ReadableState$1(options, this); - checkListener(listener); + // legacy + this.readable = true; - 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); + if (options && typeof options.read === 'function') this._read = options.read; - // 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]; - } + EventEmitter$1.call(this); + } - 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); - } + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$2.prototype.push = function (chunk, encoding) { + var state = this._readableState; - // 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); + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$k.from(chunk, encoding); + encoding = ''; } } - return target; - } + return readableAddChunk$1(this, state, chunk, encoding, false); + }; - EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); + // Unshift should *always* be something directly out of read() + Readable$2.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk$1(this, state, chunk, '', true); }; - EventEmitter.prototype.on = EventEmitter.prototype.addListener; + Readable$2.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; - EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; + function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid$1(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } - 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); + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable$1(stream); + } + } + + maybeReadMore$1(stream, state); + } + } else if (!addToFront) { + state.reading = false; } + + return needMoreData$1(state); } - 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; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData$1(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } - EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); + // backwards compatibility. + Readable$2.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; 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; + // Don't raise the hwm > 8MB + var MAX_HWM$1 = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM$1) { + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } - 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; - }; + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + // you can override either this method, or the async _read(n) below. + Readable$2.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; + if (n !== 0) state.emittedReadable = false; - events = this._events; - if (events === undefined) - return this; + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - // 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; - } + n = howMuchToRead$1(n, state); - // 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; - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } - listeners = events[type]; + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - 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]); - } - } + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); - return this; - }; + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } - function _listeners(target, type, unwrap) { - var events = target._events; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } - if (events === undefined) - return []; + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - var evlistener = events[type]; - if (evlistener === undefined) - return []; + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); - } + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable$1(this); + } - EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); - }; + if (ret !== null) this.emit('data', ret); - EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); + return ret; }; - EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount$1.call(emitter, type); + function chunkInvalid$1(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - }; - - EventEmitter.prototype.listenerCount = listenerCount$1; - function listenerCount$1(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; + return er; + } - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; + function onEofChunk$1(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } } + state.ended = true; - return 0; + // emit 'readable' now to make sure it gets picked up. + emitReadable$1(stream); } - 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; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable$1(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); + } } - function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); + function emitReadable_$1(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow$1(stream); } - function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); } - 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 maybeReadMore_$1(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } + state.readingMore = false; } - 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); + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$2.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable$2.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; } - } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var EventEmitter$1 = events.exports; + var doEnd = (!pipeOpts || pipeOpts.end !== false); - var inherits$5; - if (typeof Object.create === 'function'){ - inherits$5 = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$5 = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$6 = inherits$5; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString$1(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); } - 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$1(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } + function onend() { + debug$4('onend'); + dest.end(); } - 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined$1(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; } - warned = true; + src.pause(); } - return fn.apply(this, arguments); } - return deprecated; - } - - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined$1(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); } - 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$1(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - // set default options - if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined$1(ctx.depth)) ctx.depth = 2; - if (isUndefined$1(ctx.colors)) ctx.colors = false; - if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - // 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] - }; + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - // 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' - }; + // tell the dest that it's being piped to + dest.emit('pipe', src); + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + return dest; + }; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } + function pipeOnDrain$1(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow$1(src); + } + }; } + Readable$2.prototype.unpipe = function (dest) { + var state = this._readableState; - function stylizeNoColor(str, styleType) { - return str; - } + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - function arrayToHash(array) { - var hash = {}; + if (!dest) dest = state.pipes; - array.forEach(function(val, idx) { - hash[val] = true; - }); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } - return hash; - } + // slow case. multiple pipe destinations. + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - 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$1(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== 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$1(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + // try to find the right one. + var i = indexOf$1(state.pipes, dest); + if (i === -1) return this; - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + dest.emit('unpipe', this); - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError$1(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + return this; + }; - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction$1(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate$1(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError$1(value)) { - return formatError(value); + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$2.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable$1(this); + } } } - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray$2(value)) { - array = true; - braces = ['[', ']']; - } + return res; + }; + Readable$2.prototype.addListener = Readable$2.prototype.on; - // Make functions say that they are functions - if (isFunction$1(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); + } - // Make RegExps say that they are RegExps - if (isRegExp$1(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$2.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); } + return this; + }; - // Make dates with properties first say the date - if (isDate$1(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); } + } - // Make error with message first say the error - if (isError$1(value)) { - base = ' ' + formatError(value); + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - 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); - }); + Readable$2.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); } + return this; + }; - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); + function flow$1(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} } + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$2.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - function formatPrimitive(ctx, value) { - if (isUndefined$1(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber$1(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean$1(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull$1(value)) - return ctx.stylize('null', 'null'); - } + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + self.push(null); + }); - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - 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)); + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } }); - 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$1(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$1(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'); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } } - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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]; - } - + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$2(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$2(ar) { - return Array.isArray(ar); - } + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - function isBoolean$1(arg) { - return typeof arg === 'boolean'; - } + return self; + }; - function isNull$1(arg) { - return arg === null; - } + // exposed for testing purposes only. + Readable$2._fromList = fromList$1; - function isNumber$1(arg) { - return typeof arg === 'number'; - } + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; - function isString$1(arg) { - return typeof arg === 'string'; - } + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - function isUndefined$1(arg) { - return arg === void 0; + return ret; } - function isRegExp$1(re) { - return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } - function isObject$1(arg) { - return typeof arg === 'object' && arg !== null; + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - function isDate$1(d) { - return isObject$1(d) && objectToString$1(d) === '[object Date]'; + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$k.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; } - function isError$1(e) { - return isObject$1(e) && - (objectToString$1(e) === '[object Error]' || e instanceof Error); - } + function endReadable$1(stream) { + var state = stream._readableState; - function isFunction$1(arg) { - return typeof arg === 'function'; - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - function objectToString$1(o) { - return Object.prototype.toString.call(o); + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + function forEach$2(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); } - return origin; } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; + // A bit simpler than readable streams. + Writable$2.WritableState = WritableState$1; + inherits$i(Writable$2, events.exports.EventEmitter); + + function nop() {} + + function WriteReq$1(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + function WritableState$1(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - var string_decoder = {}; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - var StringDecoder_1; - // 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. + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - var Buffer$6 = buffer.Buffer; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - var isBufferEncoding = Buffer$6.isEncoding - || function(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; - } - }; + // a flag to see when we're in the middle of a write. + this.writing = false; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$6(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite$1(stream, er); + }; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$2.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; + // the amount that is being written when _write is called. + this.writelen = 0; - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + // count buffered requests + this.bufferedRequestCount = 0; - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } + return out; + }; + function Writable$2(options) { - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + this._writableState = new WritableState$1(options, this); - charStr += buffer.toString(this.encoding, 0, end); + // legacy. + this.writable = true; - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; } - // or just emit the charStr - return charStr; + events.exports.EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable$2.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); }; - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + function writeAfterEnd$1(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk$1(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } - // See http://en.wikipedia.org/wiki/UTF-8#Description + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, chunk, encoding, cb); } - this.charReceived = i; + + return ret; }; - StringDecoder$2.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + Writable$2.prototype.cork = function () { + var state = this._writableState; - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); + state.corked++; + }; + + Writable$2.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); } + }; - return res; + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; }; - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; } - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer$1(stream, state, chunk, encoding, cb) { + chunk = decodeChunk$1(state, chunk, encoding); - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - Readable$2.ReadableState = ReadableState$1; + state.length += len; - var debug$4 = debuglog('stream'); - inherits$6(Readable$2, EventEmitter$1); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; + doWrite$1(stream, state, false, len, chunk, encoding, cb); } + + return ret; } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; + + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - function ReadableState$1(options, stream) { - options = options || {}; + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + onwriteStateUpdate$1(state); - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state); - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + if (sync) { + /**/ + nextTick(afterWrite$1, stream, state, finished, cb); + /**/ + } else { + afterWrite$1(stream, state, finished, cb); + } + } + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + // if there's something in the buffer waiting, then process it + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable$2(options) { + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - if (!(this instanceof Readable$2)) return new Readable$2(options); + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); - this._readableState = new ReadableState$1(options, this); + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - // legacy - this.readable = true; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } - if (options && typeof options.read === 'function') this._read = options.read; + if (entry === null) state.lastBufferedRequest = null; + } - EventEmitter$1.call(this); + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$2.prototype.push = function (chunk, encoding) { - var state = this._readableState; + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$e.from(chunk, encoding); - encoding = ''; - } + Writable$2.prototype._writev = null; + + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return readableAddChunk$1(this, state, chunk, encoding, false); - }; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - // Unshift should *always* be something directly out of read() - Readable$2.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk$1(this, state, chunk, '', true); - }; + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - Readable$2.prototype.isPaused = function () { - return this._readableState.flowing === false; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable$1(this, state, cb); }; - function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid$1(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + prefinish(stream, state); + } + } + return need; + } - if (!addToFront) state.reading = false; + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - if (state.needReadable) emitReadable$1(stream); - } - } + this.next = null; + this.entry = null; - maybeReadMore$1(stream, state); + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; } - } else if (!addToFront) { - state.reading = false; - } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } - return needMoreData$1(state); + inherits$i(Duplex$2, Readable$2); + + var keys = Object.keys(Writable$2.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; } + function Duplex$2(options) { + if (!(this instanceof Duplex$2)) return new Duplex$2(options); - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData$1(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + Readable$2.call(this, options); + Writable$2.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend$1); } - // backwards compatibility. - Readable$2.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; - }; + // the no-half-open enforcer + function onend$1() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - // Don't raise the hwm > 8MB - var MAX_HWM$1 = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM$1) { - n = MAX_HWM$1; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; + function onEndNT(self) { + self.end(); } - // you can override either this method, or the async _read(n) below. - Readable$2.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + // a transform stream is a readable/writable stream where you do + inherits$i(Transform$4, Duplex$2); - if (n !== 0) state.emittedReadable = false; + function TransformState$1(stream) { + this.afterTransform = function (er, data) { + return afterTransform$1(stream, er, data); + }; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; - } + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } - n = howMuchToRead$1(n, state); + function afterTransform$1(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; - } + var cb = ts.writecb; - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$4('need readable', doRead); + ts.writechunk = null; + ts.writecb = null; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); - } + if (data !== null && data !== undefined) stream.push(data); - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead$1(nOrig, state); + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } + } + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + Duplex$2.call(this, options); - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + this._transformState = new TransformState$1(this); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + // when the writable side finishes, then flush out anything remaining. + var stream = this; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable$1(this); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - if (ret !== null) this.emit('data', ret); + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - return ret; - }; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - function chunkInvalid$1(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + if (typeof options.flush === 'function') this._flush = options.flush; } - return er; + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done$1(stream, er); + });else done$1(stream); + }); } - function onEofChunk$1(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$2.prototype.push.call(this, chunk, encoding); + }; - // emit 'readable' now to make sure it gets picked up. - emitReadable$1(stream); - } + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$4.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable$1(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } - } + }; - function emitReadable_$1(stream) { - debug$4('emit readable'); - stream.emit('readable'); - flow$1(stream); - } + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } + }; + + function done$1(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); } - function maybeReadMore_$1(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; + inherits$i(PassThrough$1, Transform$4); + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + + Transform$4.call(this, options); } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$2.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; - Readable$2.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + inherits$i(Stream$2, EventEmitter$1); + Stream$2.Readable = Readable$2; + Stream$2.Writable = Writable$2; + Stream$2.Duplex = Duplex$2; + Stream$2.Transform = Transform$4; + Stream$2.PassThrough = PassThrough$1; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + // Backwards-compat with node 0.4.x + Stream$2.Stream = Stream$2; - var doEnd = (!pipeOpts || pipeOpts.end !== false); + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + function Stream$2() { + EventEmitter$1.call(this); + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$4('onunpipe'); - if (readable === src) { - cleanup(); + Stream$2.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } } } - function onend() { - debug$4('onend'); - dest.end(); + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain$1(src); dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug$4('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - cleanedUp = true; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + dest.end(); } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$4('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + if (didOnEnd) return; + didOnEnd = true; - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); + if (typeof dest.destroy === 'function') dest.destroy(); } - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } } - return dest; - }; - - function pipeOnDrain$1(src) { - return function () { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow$1(src); - } - }; - } + source.on('error', onerror); + dest.on('error', onerror); - Readable$2.prototype.unpipe = function (dest) { - var state = this._readableState; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + source.removeListener('end', onend); + source.removeListener('close', onclose); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - if (!dest) dest = state.pipes; + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; + dest.removeListener('close', cleanup); } - // slow case. multiple pipe destinations. + source.on('end', cleanup); + source.on('close', cleanup); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + dest.on('close', cleanup); - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; - } + dest.emit('pipe', source); - // try to find the right one. - var i = indexOf$1(state.pipes, dest); - if (i === -1) return this; + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream$2, + Readable: Readable$2, + Writable: Writable$2, + Duplex: Duplex$2, + Transform: Transform$4, + PassThrough: PassThrough$1, + Stream: Stream$2 + }); - dest.emit('unpipe', this); + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); - return this; + var isarray = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$2.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + var util$5 = {}; - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable$1(this); - } - } + // 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. + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + + function isArray$2(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; + } + util$5.isArray = isArray$2; - return res; - }; - Readable$2.prototype.addListener = Readable$2.prototype.on; + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + util$5.isBoolean = isBoolean; - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); + function isNull(arg) { + return arg === null; } + util$5.isNull = isNull; - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$2.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$4('resume'); - state.flowing = true; - resume(this, state); - } - return this; - }; + function isNullOrUndefined(arg) { + return arg == null; + } + util$5.isNullOrUndefined = isNullOrUndefined; - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); - } + function isNumber(arg) { + return typeof arg === 'number'; } + util$5.isNumber = isNumber; - function resume_(stream, state) { - if (!state.reading) { - debug$4('resume read 0'); - stream.read(0); - } + function isString(arg) { + return typeof arg === 'string'; + } + util$5.isString = isString; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); + function isSymbol(arg) { + return typeof arg === 'symbol'; } + util$5.isSymbol = isSymbol; - Readable$2.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; - }; + function isUndefined(arg) { + return arg === void 0; + } + util$5.isUndefined = isUndefined; - function flow$1(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; } + util$5.isRegExp = isRegExp; - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$2.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; + } + util$5.isObject = isObject$1; - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + util$5.isDate = isDate; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + util$5.isError = isError; - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + function isFunction$1(arg) { + return typeof arg === 'function'; + } + util$5.isFunction = isFunction$1; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$2(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + util$5.isPrimitive = isPrimitive; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$4('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + util$5.isBuffer = buffer.Buffer.isBuffer; - return self; - }; + function objectToString(o) { + return Object.prototype.toString.call(o); + } - // exposed for testing purposes only. - Readable$2._fromList = fromList$1; + // 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. - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; + var _stream_readable = Readable$1; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + /**/ + var isArray$1 = isarray; + /**/ - return ret; - } - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; - } + /**/ + var Buffer$i = buffer.Buffer; + /**/ - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } + Readable$1.ReadableState = ReadableState; - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$e.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; - } + var EE = events.exports.EventEmitter; - function endReadable$1(stream) { - var state = stream._readableState; + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + var Stream$1 = require$$1; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } + /**/ + var util$4 = util$5; + util$4.inherits = inherits_browser.exports; + /**/ - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } + var StringDecoder$1; - function forEach$2(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + util$4.inherits(Readable$1, Stream$1); - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + function ReadableState(options, stream) { + options = options || {}; - // A bit simpler than readable streams. - Writable$2.WritableState = WritableState$1; - inherits$6(Writable$2, events.exports.EventEmitter); + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - function nop() {} + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - function WriteReq$1(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } - - function WritableState$1(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + this.buffer = []; this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any + // or on a later tick. We set this to true at first, becuase any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite$1(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; - // the amount that is being written when _write is called. - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - // count buffered requests - this.bufferedRequestCount = 0; + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } } - WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable$2(options) { + function Readable$1(options) { + if (!(this instanceof Readable$1)) + return new Readable$1(options); - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); + this._readableState = new ReadableState(options, this); - this._writableState = new WritableState$1(options, this); + // legacy + this.readable = true; - // legacy. - this.writable = true; + Stream$1.call(this); + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable$1.prototype.push = function(chunk, encoding) { + var state = this._readableState; - if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer$i(chunk, encoding); + encoding = ''; + } } - events.exports.EventEmitter.call(this); - } - - // Otherwise people can pipe Writable streams, which is just wrong. - Writable$2.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); + return readableAddChunk(this, state, chunk, encoding, false); }; - function writeAfterEnd$1(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } + // Unshift should *always* be something directly out of read() + Readable$1.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk$1(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; - } - - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } - if (typeof cb !== 'function') cb = nop; + if (state.needReadable) + emitReadable(stream); - if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, chunk, encoding, cb); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; } - return ret; - }; + return needMoreData(state); + } - Writable$2.prototype.cork = function () { - var state = this._writableState; - state.corked++; - }; - - Writable$2.prototype.uncork = function () { - var state = this._writableState; - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); + } - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; + // backwards compatibility. + Readable$1.prototype.setEncoding = function(enc) { + if (!StringDecoder$1) + StringDecoder$1 = string_decoder.StringDecoder; + this._readableState.decoder = new StringDecoder$1(enc); + this._readableState.encoding = enc; }; - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); + // Don't raise the hwm > 128MB + var MAX_HWM = 0x800000; + function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; } - return chunk; + return n; } - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer$1(stream, state, chunk, encoding, cb) { - chunk = decodeChunk$1(state, chunk, encoding); - - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + if (state.objectMode) + return n === 0 ? 0 : 1; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; } - return ret; - } + if (n <= 0) + return 0; - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } - stream._writableState.errorEmitted = true; - stream.emit('error', er); + return n; } - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + // you can override either this method, or the async _read(n) below. + Readable$1.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - onwriteStateUpdate$1(state); + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state); + n = howMuchToRead(n, state); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; - if (sync) { - /**/ - nextTick(afterWrite$1, stream, state, finished, cb); - /**/ - } else { - afterWrite$1(stream, state, finished, cb); - } - } - } + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } + if (state.length === 0) + endReadable(this); - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + return ret; } - } - // if there's something in the buffer waiting, then process it - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; - - Writable$2.prototype._writev = null; + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + if (n > 0) + ret = fromList(n, state); + else + ret = null; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if (ret === null) { + state.needReadable = true; + n = 0; } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + state.length -= n; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable$1(this, state, cb); - }; + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + return ret; + }; - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer$i.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } + return er; } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; - } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } state.ended = true; - stream.writable = false; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); } - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; - this.next = null; - this.entry = null; + state.emittedReadable = true; + if (state.sync) + nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; + function emitReadable_(stream) { + stream.emit('readable'); } - inherits$6(Duplex$2, Readable$2); - var keys = Object.keys(Writable$2.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(function() { + maybeReadMore_(stream, state); + }); + } } - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); - Readable$2.call(this, options); - Writable$2.call(this, options); + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; + } - if (options && options.readable === false) this.readable = false; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable$1.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); + }; - if (options && options.writable === false) this.writable = false; + Readable$1.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; - this.once('end', onend$1); - } + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - // the no-half-open enforcer - function onend$1() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + nextTick(endFn); + else + src.once('end', endFn); - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } - function onEndNT(self) { - self.end(); - } + function onend() { + dest.end(); + } - // a transform stream is a readable/writable stream where you do - inherits$6(Transform$4, Duplex$2); - - function TransformState$1(stream) { - this.afterTransform = function (er, data) { - return afterTransform$1(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - function afterTransform$1(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); - var cb = ts.writecb; + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray$1(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; - ts.writechunk = null; - ts.writecb = null; - if (data !== null && data !== undefined) stream.push(data); - cb(er); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + function unpipe() { + src.unpipe(dest); } - } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); - Duplex$2.call(this, options); + // tell the dest that it's being piped to + dest.emit('pipe', src); - this._transformState = new TransformState$1(this); + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); - // when the writable side finishes, then flush out anything remaining. - var stream = this; + state.flowing = true; + nextTick(function() { + flow(src); + }); + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + return dest; + }; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; - if (typeof options.flush === 'function') this._flush = options.flush; + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done$1(stream, er); - });else done$1(stream); - }); - } + while (state.pipesCount && null !== (chunk = src.read())) { - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$2.prototype.push.call(this, chunk, encoding); - }; + if (state.pipesCount === 1) + write(state.pipes); + else + forEach$1(state.pipes, write); - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$4.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + src.emit('data', chunk); - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; } - }; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; } - }; - - function done$1(stream, er) { - if (er) return stream.emit('error', er); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; } - inherits$6(PassThrough$1, Transform$4); - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - - Transform$4.call(this, options); + function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - inherits$6(Stream$2, EventEmitter$1); - Stream$2.Readable = Readable$2; - Stream$2.Writable = Writable$2; - Stream$2.Duplex = Duplex$2; - Stream$2.Transform = Transform$4; - Stream$2.PassThrough = PassThrough$1; + Readable$1.prototype.unpipe = function(dest) { + var state = this._readableState; - // Backwards-compat with node 0.4.x - Stream$2.Stream = Stream$2; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; - function Stream$2() { - EventEmitter$1.call(this); - } + if (!dest) + dest = state.pipes; - Stream$2.prototype.pipe = function(dest, options) { - var source = this; + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + // slow case. multiple pipe destinations. - source.on('data', ondata); + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; } - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - dest.end(); - } + dest.emit('unpipe', this); + return this; + }; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$1.prototype.on = function(ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); - if (typeof dest.destroy === 'function') dest.destroy(); - } + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this); + } } } - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + return res; + }; + Readable$1.prototype.addListener = Readable$1.prototype.on; - source.removeListener('end', onend); - source.removeListener('close', onclose); + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable$1.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); + }; - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + Readable$1.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); + }; - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + function emitDataEvents(stream, startPaused) { + var state = stream._readableState; - dest.removeListener('close', cleanup); + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); } - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + var paused = startPaused || false; + var readable = false; - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream$2, - Readable: Readable$2, - Writable: Writable$2, - Duplex: Duplex$2, - Transform: Transform$4, - PassThrough: PassThrough$1, - Stream: Stream$2 - }); + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream$1.prototype.pipe; + stream.on = stream.addListener = Stream$1.prototype.on; - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + stream.on('readable', function() { + readable = true; - var isarray = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; - }; + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); - var util$5 = {}; + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); - // 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. + stream.pause = function() { + paused = true; + this.emit('pause'); + }; - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. + stream.resume = function() { + paused = false; + if (readable) + nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; - function isArray$1(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; + // now make it start, just in case it hadn't already. + stream.emit('readable'); } - util$5.isArray = isArray$1; - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - util$5.isBoolean = isBoolean; + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable$1.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; - function isNull(arg) { - return arg === null; - } - util$5.isNull = isNull; + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } - function isNullOrUndefined(arg) { - return arg == null; - } - util$5.isNullOrUndefined = isNullOrUndefined; + self.push(null); + }); - function isNumber(arg) { - return typeof arg === 'number'; - } - util$5.isNumber = isNumber; + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); - function isString(arg) { - return typeof arg === 'string'; - } - util$5.isString = isString; + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - util$5.isSymbol = isSymbol; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - function isUndefined(arg) { - return arg === void 0; - } - util$5.isUndefined = isUndefined; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } - function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; - } - util$5.isRegExp = isRegExp; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$1(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - util$5.isObject = isObject; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; - function isDate(d) { - return objectToString(d) === '[object Date]'; - } - util$5.isDate = isDate; + return self; + }; - function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); - } - util$5.isError = isError; - function isFunction(arg) { - return typeof arg === 'function'; + + // exposed for testing purposes only. + Readable$1._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer$i.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer$i(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; } - util$5.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'; + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } } - util$5.isPrimitive = isPrimitive; - util$5.isBuffer = buffer.Buffer.isBuffer; + function forEach$1 (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - function objectToString(o) { - return Object.prototype.toString.call(o); + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } // Copyright Joyent, Inc. and other Node contributors. @@ -9977,63 +9273,166 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. - var _stream_readable = Readable$1; + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. + + var _stream_duplex = Duplex$1; /**/ - var isArray = isarray; + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; /**/ /**/ - var Buffer$5 = buffer.Buffer; + var util$3 = util$5; + util$3.inherits = inherits_browser.exports; /**/ - Readable$1.ReadableState = ReadableState; + var Readable = _stream_readable; + var Writable$1 = _stream_writable; - var EE = events.exports.EventEmitter; + util$3.inherits(Duplex$1, Readable); + + forEach(objectKeys(Writable$1.prototype), function(method) { + if (!Duplex$1.prototype[method]) + Duplex$1.prototype[method] = Writable$1.prototype[method]; + }); + + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) + return new Duplex$1(options); + + Readable.call(this, options); + Writable$1.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(this.end.bind(this)); + } + + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + // 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. + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. + + var _stream_writable = Writable; /**/ - if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; + var Buffer$h = buffer.Buffer; /**/ - var Stream$1 = require$$1; + Writable.WritableState = WritableState; + /**/ - var util$4 = util$5; - util$4.inherits = inherits_browser.exports; + var util$2 = util$5; + util$2.inherits = inherits_browser.exports; /**/ - var StringDecoder$1; + var Stream = require$$1; - util$4.inherits(Readable$1, Stream$1); + util$2.inherits(Writable, Stream); - function ReadableState(options, stream) { + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } + + function WritableState(options, stream) { options = options || {}; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + // cast to ints. this.highWaterMark = ~~this.highWaterMark; - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned this.ended = false; - this.endEmitted = false; - this.reading = false; + // when 'finish' is emitted + this.finished = false; - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, becuase any @@ -10041,5071 +9440,28812 @@ // not happen before the first write call. this.sync = true; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + // the amount that is being written when _write is called. + this.writelen = 0; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + this.buffer = []; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; } - function Readable$1(options) { - if (!(this instanceof Readable$1)) - return new Readable$1(options); - - this._readableState = new ReadableState(options, this); + function Writable(options) { + var Duplex = _stream_duplex; - // legacy - this.readable = true; + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); - Stream$1.call(this); - } + this._writableState = new WritableState(options, this); - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$1.prototype.push = function(chunk, encoding) { - var state = this._readableState; + // legacy. + this.writable = true; - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer$5(chunk, encoding); - encoding = ''; - } - } + Stream.call(this); + } - return readableAddChunk(this, state, chunk, encoding, false); + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); }; - // Unshift should *always* be something directly out of read() - Readable$1.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + } - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer$h.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; + } - if (state.needReadable) - emitReadable(stream); + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return needMoreData(state); - } - + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + if (typeof cb !== 'function') + cb = function() {}; - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); - } + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); - // backwards compatibility. - Readable$1.prototype.setEncoding = function(enc) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this._readableState.decoder = new StringDecoder$1(enc); - this._readableState.encoding = enc; + return ret; }; - // Don't raise the hwm > 128MB - var MAX_HWM = 0x800000; - function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer$h(chunk, encoding); } - return n; + return chunk; } - function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer$h.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } + state.length += len; - if (n <= 0) - return 0; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } + return ret; + } - return n; + function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - // you can override either this method, or the async _read(n) below. - Readable$1.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; + function onwriteError(stream, state, sync, er, cb) { + if (sync) + nextTick(function() { + cb(er); + }); + else + cb(er); - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - n = howMuchToRead(n, state); + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; + onwriteStateUpdate(state); - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); } + } + } - if (state.length === 0) - endReadable(this); + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); + } - return ret; + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } + } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; + doWrite(stream, state, len, chunk, encoding, cb); - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } } - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - if (n > 0) - ret = fromList(n, state); + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); else - ret = null; + state.buffer.length = 0; + } - if (ret === null) { - state.needReadable = true; - n = 0; - } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); + }; - state.length -= n; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); - return ret; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); }; - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer$5.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; + + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; + } - function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + nextTick(cb); + else + stream.once('finish', cb); } state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; + // 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. - state.emittedReadable = true; - if (state.sync) - nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } - function emitReadable_(stream) { - stream.emit('readable'); - } + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + var _stream_transform = Transform$3; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(function() { - maybeReadMore_(stream, state); - }); - } - } + var Duplex = _stream_duplex; - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; - } + /**/ + var util$1 = util$5; + util$1.inherits = inherits_browser.exports; + /**/ - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$1.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); - }; + util$1.inherits(Transform$3, Duplex); - Readable$1.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + } - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - nextTick(endFn); - else - src.once('end', endFn); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } + var cb = ts.writecb; - function onend() { - dest.end(); - } + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + ts.writechunk = null; + ts.writecb = null; - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); + if (data !== null && data !== undefined) + stream.push(data); - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } + if (cb) + cb(er); - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; + } + function Transform$3(options) { + if (!(this instanceof Transform$3)) + return new Transform$3(options); - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + Duplex.call(this, options); - function unpipe() { - src.unpipe(dest); - } + this._transformState = new TransformState(options, this); - // tell the dest that it's being piped to - dest.emit('pipe', src); + // when the writable side finishes, then flush out anything remaining. + var stream = this; - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - nextTick(function() { - flow(src); - }); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - return dest; - }; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); } - function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes); - else - forEach$1(state.pipes, write); + Transform$3.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - src.emit('data', chunk); + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$3.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); + }; - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; + Transform$3.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); } + }; - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$3.prototype._read = function(n) { + var ts = this._transformState; - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } + }; - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; - } - function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } - } + function done(stream, er) { + if (er) + return stream.emit('error', er); + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + stream._readableState; + var ts = stream._transformState; - Readable$1.prototype.unpipe = function(dest) { - var state = this._readableState; + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; + if (ts.transforming) + throw new Error('calling transform done when still transforming'); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; + return stream.push(null); + } - if (!dest) - dest = state.pipes; + // 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. - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - // slow case. multiple pipe destinations. + var _stream_passthrough = PassThrough; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; + var Transform$2 = _stream_transform; - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } + /**/ + var util = util$5; + util.inherits = inherits_browser.exports; + /**/ - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; + util.inherits(PassThrough, Transform$2); - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); - dest.emit('unpipe', this); + Transform$2.call(this, options); + } - return this; + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$1.prototype.on = function(ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); + (function (module, exports) { + var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify + exports = module.exports = _stream_readable; + exports.Stream = Stream; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + }(readable, readable.exports)); - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$1 = readable.exports.Transform; + var inherits$g = inherits_browser.exports; - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this); - } - } + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } + } - return res; - }; - Readable$1.prototype.addListener = Readable$1.prototype.on; + function HashBase$2 (blockSize) { + Transform$1.call(this); - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$1.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); - }; - - Readable$1.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); - }; - - function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream$1.prototype.pipe; - stream.on = stream.addListener = Stream$1.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; - // now make it start, just in case it hadn't already. - stream.emit('readable'); + this._finalized = false; } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$1.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; + inherits$g(HashBase$2, Transform$1); - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; + } - self.push(null); - }); + callback(error); + }; - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; + } - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; + callback(error); + }; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$1(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } - return self; + return this }; + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - // exposed for testing purposes only. - Readable$1._fromList = fromList; + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + return digest + }; - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer$5.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer$5(n); + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); + var hashBase = HashBase$2; - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); + var inherits$f = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + var ARRAY16$1 = new Array(16); - c += cpy; - } - } - } + function MD5$2 () { + HashBase$1.call(this, 64); - return ret; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; } - function endReadable(stream) { - var state = stream._readableState; + inherits$f(MD5$2, HashBase$1); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - if (!state.endEmitted && state.calledRead) { - state.ended = true; - nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } - } + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - function forEach$1 (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } - - function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - // 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. + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - // a duplex stream is just a stream that is both readable and writable. - // Since JS doesn't have multiple prototypal inheritance, this class - // prototypally inherits from Readable, and then parasitically from - // Writable. + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - var _stream_duplex = Duplex$1; + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - /**/ - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; }; - /**/ - - - /**/ - var util$3 = util$5; - util$3.inherits = inherits_browser.exports; - /**/ - - var Readable = _stream_readable; - var Writable$1 = _stream_writable; - - util$3.inherits(Duplex$1, Readable); - - forEach(objectKeys(Writable$1.prototype), function(method) { - if (!Duplex$1.prototype[method]) - Duplex$1.prototype[method] = Writable$1.prototype[method]; - }); - - function Duplex$1(options) { - if (!(this instanceof Duplex$1)) - return new Duplex$1(options); - Readable.call(this, options); - Writable$1.call(this, options); + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - if (options && options.readable === false) - this.readable = false; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - if (options && options.writable === false) - this.writable = false; + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer + }; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } - this.once('end', onend); + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 } - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(this.end.bind(this)); + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 } - // 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 md5_js = MD5$2; - // A bit simpler than readable streams. - // Implement an async ._write(chunk, cb), and it'll handle all - // the drain event emission and buffering. + var Buffer$e = buffer.Buffer; + var inherits$e = inherits_browser.exports; + var HashBase = hashBase; - var _stream_writable = Writable; + var ARRAY16 = new Array(16); - /**/ - var Buffer$4 = buffer.Buffer; - /**/ + var zl = [ + 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 + ]; - Writable.WritableState = WritableState; + var zr = [ + 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 sl = [ + 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 util$2 = util$5; - util$2.inherits = inherits_browser.exports; - /**/ + var sr = [ + 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 + ]; - var Stream = require$$1; + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - util$2.inherits(Writable, Stream); + function RIPEMD160$3 () { + HashBase.call(this, 64); - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; } - function WritableState(options, stream) { - options = options || {}; + inherits$e(RIPEMD160$3, HashBase); - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); + } - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - // a flag to see when we're in the middle of a write. - this.writing = false; + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - // the amount that is being written when _write is called. - this.writelen = 0; + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } - this.buffer = []; + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } - function Writable(options) { - var Duplex = _stream_duplex; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); + var ripemd160$2 = RIPEMD160$3; - this._writableState = new WritableState(options, this); + var sha_js = {exports: {}}; - // legacy. - this.writable = true; + var Buffer$d = safeBuffer.exports.Buffer; - Stream.call(this); + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; } - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); - }; + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); + } + var block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - } + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer$4.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; - } + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + accum += remainder; + offset += remainder; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if ((accum % blockSize) === 0) { + this._update(block); + } } - if (Buffer$4.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; + this._len += length; + return this + }; - if (typeof cb !== 'function') - cb = function() {}; + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); + this._block[rem] = 0x80; - return ret; - }; + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer$4(chunk, encoding); + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); } - return chunk; - } - - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer$4.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - state.length += len; + var bits = this._len * 8; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - return ret; - } + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } - function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + this._update(this._block); + var hash = this._hash(); - function onwriteError(stream, state, sync, er, cb) { - if (sync) - nextTick(function() { - cb(er); - }); - else - cb(er); + return enc ? hash.toString(enc) : hash + }; - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + var hash$3 = Hash$7; - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - onwriteStateUpdate(state); + var inherits$d = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); + var W$5 = new Array(80); - if (sync) { - nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } + function Sha () { + this.init(); + this._w = W$5; + + Hash$6.call(this, 64, 56); } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); + inherits$d(Sha, Hash$6); + + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this + }; + + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) } + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; + Sha.prototype._update = function (M) { + var W = this._w; - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - doWrite(stream, state, len, chunk, encoding, cb); + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; } - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); + + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); + + return H }; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; + var sha$4 = Sha; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); + var inherits$c = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; + + var W$4 = new Array(80); + + function Sha1 () { + this.init(); + this._w = W$4; + + Hash$5.call(this, 64, 56); + } + + inherits$c(Sha1, Hash$5); + + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + + return this }; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); + function rotl5 (num) { + return (num << 5) | (num >>> 27) } - function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; + function rotl30 (num) { + return (num << 30) | (num >>> 2) } - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } - // 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. + Sha1.prototype._update = function (M) { + var W = this._w; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - var _stream_transform = Transform$3; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - var Duplex = _stream_duplex; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } - /**/ - var util$1 = util$5; - util$1.inherits = inherits_browser.exports; - /**/ + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - util$1.inherits(Transform$3, Duplex); + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; + return H + }; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - } + var sha1$1 = Sha1; - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - var cb = ts.writecb; + var inherits$b = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + var K$2 = [ + 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 + ]; - ts.writechunk = null; - ts.writecb = null; + var W$3 = new Array(64); - if (data !== null && data !== undefined) - stream.push(data); + function Sha256$1 () { + this.init(); - if (cb) - cb(er); + this._w = W$3; // new Array(64) - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } + Hash$4.call(this, 64, 56); } + inherits$b(Sha256$1, Hash$4); - function Transform$3(options) { - if (!(this instanceof Transform$3)) - return new Transform$3(options); + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - Duplex.call(this, options); + return this + }; - this._transformState = new TransformState(options, this); + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - // when the writable side finishes, then flush out anything remaining. - var stream = this; + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } - Transform$3.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$3.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); - }; + Sha256$1.prototype._update = function (M) { + var W = this._w; - Transform$3.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } - }; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$3.prototype._read = function(n) { - var ts = this._transformState; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; }; + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - function done(stream, er) { - if (er) - return stream.emit('error', er); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - stream._readableState; - var ts = stream._transformState; + return H + }; - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); + var sha256$2 = Sha256$1; - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - return stream.push(null); - } + var inherits$a = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - // 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 W$2 = new Array(64); - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. + function Sha224 () { + this.init(); - var _stream_passthrough = PassThrough; + this._w = W$2; // new Array(64) - var Transform$2 = _stream_transform; + Hash$3.call(this, 64, 56); + } - /**/ - var util = util$5; - util.inherits = inherits_browser.exports; - /**/ + inherits$a(Sha224, Sha256); - util.inherits(PassThrough, Transform$2); + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + return this + }; - Transform$2.call(this, options); - } + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + + return H }; - (function (module, exports) { - var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify - exports = module.exports = _stream_readable; - exports.Stream = Stream; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - }(readable, readable.exports)); + var sha224 = Sha224; - var Buffer$3 = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$4 = inherits_browser.exports; + var inherits$9 = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$3.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } - } + var K$1 = [ + 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 HashBase$2 (blockSize) { - Transform$1.call(this); + var W$1 = new Array(160); - this._block = Buffer$3.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + function Sha512 () { + this.init(); + this._w = W$1; - this._finalized = false; + Hash$2.call(this, 128, 112); } - inherits$4(HashBase$2, Transform$1); - - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } + inherits$9(Sha512, Hash$2); - callback(error); - }; + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; - callback(error); + return this }; - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$3.isBuffer(data)) data = Buffer$3.from(data, encoding); + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - return this - }; + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - return digest - }; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') - }; + Sha512.prototype._update = function (M) { + var W = this._w; - var hashBase = HashBase$2; + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - var Buffer$2 = buffer.Buffer; - var inherits$3 = inherits_browser.exports; - var HashBase$1 = hashBase; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; - var ARRAY16$1 = new Array(16); + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); - var zl = [ - 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 - ]; + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - var zr = [ - 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 - ]; + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - var sl = [ - 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 Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - var sr = [ - 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 - ]; + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + W[i] = Wih; + W[i + 1] = Wil; + } - function RIPEMD160$1 () { - HashBase$1.call(this, 64); + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - } + var majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - inherits$3(RIPEMD160$1, HashBase$1); + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - RIPEMD160$1.prototype._update = function () { - var words = ARRAY16$1; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - al = el; - el = dl; - dl = rotl$1(cl, 10); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; cl = bl; - bl = tl; - - ar = er; - er = dr; - dr = rotl$1(cr, 10); - cr = br; - br = tr; - } - - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; - }; - - RIPEMD160$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - // produce result - var buffer = Buffer$2.alloc ? Buffer$2.alloc(20) : new Buffer$2(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) - } + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 - } + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } + return H + }; - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 - } + var sha512 = Sha512; - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl$1((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + var inherits$8 = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; + + var W = new Array(160); + + function Sha384 () { + this.init(); + this._w = W; + + Hash$1.call(this, 128, 112); } - var ripemd160 = RIPEMD160$1; + inherits$8(Sha384, SHA512$2); - function hashPublicKey(buffer) { - return new ripemd160().update(sha$1("sha256").update(buffer).digest()).digest(); + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; + + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; + + return this + }; + + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } + + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + + return H + }; + + var sha384 = Sha384; + + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); + + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() + }; + + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; + + var sha$3 = sha_js.exports; + + var Buffer$6 = safeBuffer.exports.Buffer; + var Transform = require$$1.Transform; + var StringDecoder = string_decoder.StringDecoder; + var inherits$7 = inherits_browser.exports; + + function CipherBase (hashMode) { + Transform.call(this); + this.hashMode = typeof hashMode === 'string'; + if (this.hashMode) { + this[hashMode] = this._finalOrDigest; + } else { + this.final = this._finalOrDigest; + } + if (this._final) { + this.__final = this._final; + this._final = null; + } + this._decoder = null; + this._encoding = null; } + inherits$7(CipherBase, Transform); - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer$6.from(data, inputEnc); + } + + var outData = this._update(data); + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc); + } + + return outData }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + + CipherBase.prototype.setAutoPadding = function () {}; + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + }; + + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + }; + + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + }; + + CipherBase.prototype._transform = function (data, _, next) { + var err; + try { + if (this.hashMode) { + this._update(data); + } else { + this.push(this._update(data)); } + } catch (e) { + err = e; + } finally { + next(err); + } }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + CipherBase.prototype._flush = function (done) { + var err; + try { + this.push(this.__final()); + } catch (e) { + err = e; + } + + done(err); }; - function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - var p2 = additionals.includes("cashaddr") - ? 0x03 - : bip143 - ? additionals.includes("sapling") - ? 0x05 - : overwinter - ? 0x04 - : 0x02 - : 0x00; - return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); - } - function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { - if (bip143 === void 0) { bip143 = false; } - if (overwinter === void 0) { overwinter = false; } - if (additionals === void 0) { additionals = []; } - if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$7(this, void 0, void 0, function () { - var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; - var e_2, _c, e_1, _d; - return __generator$7(this, function (_e) { - switch (_e.label) { - case 0: - data = Buffer$e.concat([ - transaction.version, - transaction.timestamp || Buffer$e.alloc(0), - transaction.nVersionGroupId || Buffer$e.alloc(0), - createVarint(transaction.inputs.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; - case 1: - _e.sent(); - i = 0; - isDecred = additionals.includes("decred"); - _e.label = 2; - case 2: - _e.trys.push([2, 15, 16, 17]); - _a = __values$4(transaction.inputs), _b = _a.next(); - _e.label = 3; - case 3: - if (!!_b.done) return [3 /*break*/, 14]; - input = _b.value; - prefix = void 0; - inputValue = inputs[i].value; - if (bip143) { - if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$e.from([0x01, inputValue.length]); - } - else { - prefix = Buffer$e.from([0x02]); - } - } - else { - if (inputs[i].trustedInput) { - prefix = Buffer$e.from([0x01, inputs[i].value.length]); - } - else { - prefix = Buffer$e.from([0x00]); - } - } - data = Buffer$e.concat([ - prefix, - inputValue, - isDecred ? Buffer$e.from([0x00]) : Buffer$e.alloc(0), - createVarint(input.script.length), - ]); - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; - case 4: - _e.sent(); - scriptBlocks = []; - offset = 0; - if (input.script.length === 0) { - scriptBlocks.push(input.sequence); - } - else { - while (offset !== input.script.length) { - blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK - ? MAX_SCRIPT_BLOCK - : input.script.length - offset; - if (offset + blockSize !== input.script.length) { - scriptBlocks.push(input.script.slice(offset, offset + blockSize)); - } - else { - scriptBlocks.push(Buffer$e.concat([ - input.script.slice(offset, offset + blockSize), - input.sequence, - ])); - } - offset += blockSize; - } - } - _e.label = 5; - case 5: - _e.trys.push([5, 10, 11, 12]); - scriptBlocks_1 = (e_1 = void 0, __values$4(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); - _e.label = 6; - case 6: - if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; - scriptBlock = scriptBlocks_1_1.value; - return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; - case 7: - _e.sent(); - _e.label = 8; - case 8: - scriptBlocks_1_1 = scriptBlocks_1.next(); - return [3 /*break*/, 6]; - case 9: return [3 /*break*/, 12]; - case 10: - e_1_1 = _e.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 12]; - case 11: - try { - if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 12: - i++; - _e.label = 13; - case 13: - _b = _a.next(); - return [3 /*break*/, 3]; - case 14: return [3 /*break*/, 17]; - case 15: - e_2_1 = _e.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 17]; - case 16: - try { - if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 17: return [2 /*return*/]; - } - }); - }); + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer$6.alloc(0); + if (outputEnc) { + outData = this._toString(outData, outputEnc, true); + } + return outData + }; + + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc); + this._encoding = enc; + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value); + if (fin) { + out += this._decoder.end(); + } + + return out + }; + + var cipherBase = CipherBase; + + var inherits$6 = inherits_browser.exports; + var MD5$1 = md5_js; + var RIPEMD160$2 = ripemd160$2; + var sha$2 = sha_js.exports; + var Base$5 = cipherBase; + + function Hash (hash) { + Base$5.call(this, 'digest'); + + this._hash = hash; } - function compressPublicKey(publicKey) { - var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$e.alloc(1); - prefixBuffer[0] = prefix; - return Buffer$e.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); - } + inherits$6(Hash, Base$5); - function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { - if (additionals === void 0) { additionals = []; } - var isDecred = additionals.includes("decred"); - var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$e.alloc(4); - lockTimeBuffer.writeUInt32BE(lockTime, 0); - var buffer = isDecred - ? Buffer$e.concat([ - pathsBuffer, - lockTimeBuffer, - expiryHeight || Buffer$e.from([0x00, 0x00, 0x00, 0x00]), - Buffer$e.from([sigHashType]), - ]) - : Buffer$e.concat([ - pathsBuffer, - Buffer$e.from([0x00]), - lockTimeBuffer, - Buffer$e.from([sigHashType]), - ]); - if (expiryHeight && !isDecred) { - buffer = Buffer$e.concat([buffer, expiryHeight]); - } - return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { - if (result.length > 0) { - result[0] = 0x30; - return result.slice(0, result.length - 2); - } - return result; - }); - } + Hash.prototype._update = function (data) { + this._hash.update(data); + }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + Hash.prototype._final = function () { + return this._hash.digest() }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + + var browser$3 = function createHash (alg) { + alg = alg.toLowerCase(); + if (alg === 'md5') return new MD5$1() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160$2() + + return new Hash(sha$2(alg)) + }; + + var browser$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ + __proto__: null, + 'default': browser$3 + }, [browser$3])); + + // base-x encoding / decoding + // Copyright (c) 2018 base-x contributors + // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) + // Distributed under the MIT software license, see the accompanying + // file LICENSE or http://www.opensource.org/licenses/mit-license.php. + // @ts-ignore + var _Buffer$1 = safeBuffer.exports.Buffer; + function base$2 (ALPHABET) { + if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } + var BASE_MAP = new Uint8Array(256); + for (var j = 0; j < BASE_MAP.length; j++) { + BASE_MAP[j] = 255; + } + for (var i = 0; i < ALPHABET.length; i++) { + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up + var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up + function encode (source) { + if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer$1.from(source); } + if (!_Buffer$1.isBuffer(source)) { throw new TypeError('Expected Buffer') } + if (source.length === 0) { return '' } + // Skip & count leading zeroes. + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while (pbegin !== pend && source[pbegin] === 0) { + pbegin++; + zeroes++; + } + // Allocate enough space in big-endian base58 representation. + var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; + var b58 = new Uint8Array(size); + // Process the bytes. + while (pbegin !== pend) { + var carry = source[pbegin]; + // Apply "b58 = b58 * 256 + ch". + var i = 0; + for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { + carry += (256 * b58[it1]) >>> 0; + b58[it1] = (carry % BASE) >>> 0; + carry = (carry / BASE) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + pbegin++; + } + // Skip leading zeroes in base58 result. + var it2 = size - length; + while (it2 !== size && b58[it2] === 0) { + it2++; + } + // Translate the result into a string. + var str = LEADER.repeat(zeroes); + for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } + return str + } + function decodeUnsafe (source) { + if (typeof source !== 'string') { throw new TypeError('Expected String') } + if (source.length === 0) { return _Buffer$1.alloc(0) } + var psz = 0; + // Skip and count leading '1's. + var zeroes = 0; + var length = 0; + while (source[psz] === LEADER) { + zeroes++; + psz++; + } + // Allocate enough space in big-endian base256 representation. + var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. + var b256 = new Uint8Array(size); + // Process the characters. + while (source[psz]) { + // Decode character + var carry = BASE_MAP[source.charCodeAt(psz)]; + // Invalid character + if (carry === 255) { return } + var i = 0; + for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { + carry += (BASE * b256[it3]) >>> 0; + b256[it3] = (carry % 256) >>> 0; + carry = (carry / 256) >>> 0; + } + if (carry !== 0) { throw new Error('Non-zero carry') } + length = i; + psz++; + } + // Skip leading zeroes in b256. + var it4 = size - length; + while (it4 !== size && b256[it4] === 0) { + it4++; + } + var vch = _Buffer$1.allocUnsafe(zeroes + (size - it4)); + vch.fill(0x00, 0, zeroes); + var j = zeroes; + while (it4 !== size) { + vch[j++] = b256[it4++]; } + return vch + } + function decode (string) { + var buffer = decodeUnsafe(string); + if (buffer) { return buffer } + throw new Error('Non-base' + BASE + ' character') + } + return { + encode: encode, + decodeUnsafe: decodeUnsafe, + decode: decode + } + } + var src$2 = base$2; + + var basex = src$2; + var ALPHABET$1 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + + var bs58 = basex(ALPHABET$1); + + var base58 = bs58; + var Buffer$5 = safeBuffer.exports.Buffer; + + var base$1 = function (checksumFn) { + // Encode a buffer as a base58-check encoded string + function encode (payload) { + var checksum = checksumFn(payload); + + return base58.encode(Buffer$5.concat([ + payload, + checksum + ], payload.length + 4)) + } + + function decodeRaw (buffer) { + var payload = buffer.slice(0, -4); + var checksum = buffer.slice(-4); + var newChecksum = checksumFn(payload); + + if (checksum[0] ^ newChecksum[0] | + checksum[1] ^ newChecksum[1] | + checksum[2] ^ newChecksum[2] | + checksum[3] ^ newChecksum[3]) return + + return payload + } + + // Decode a base58-check encoded string to a buffer, no result if checksum is wrong + function decodeUnsafe (string) { + var buffer = base58.decodeUnsafe(string); + if (!buffer) return + + return decodeRaw(buffer) + } + + function decode (string) { + var buffer = base58.decode(string); + var payload = decodeRaw(buffer); + if (!payload) throw new Error('Invalid checksum') + return payload + } + + return { + encode: encode, + decode: decode, + decodeUnsafe: decodeUnsafe + } }; - function provideOutputFullChangePath(transport, path) { - var buffer = bip32asBuffer(path); - return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + + var createHash$2 = browser$3; + var bs58checkBase = base$1; + + // SHA256(SHA256(buffer)) + function sha256x2 (buffer) { + var tmp = createHash$2('sha256').update(buffer).digest(); + return createHash$2('sha256').update(tmp).digest() } - function hashOutputFull(transport, outputScript, additionals) { - if (additionals === void 0) { additionals = []; } - return __awaiter$6(this, void 0, void 0, function () { - var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$6(this, function (_a) { - switch (_a.label) { - case 0: - offset = 0; - p1 = Number(0x80); - isDecred = additionals.includes("decred"); - ///WARNING: Decred works only with one call (without chunking) - //TODO: test without this for Decred - if (isDecred) { - return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; - } - _a.label = 1; - case 1: - if (!(offset < outputScript.length)) return [3 /*break*/, 3]; - blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length - ? outputScript.length - offset - : MAX_SCRIPT_BLOCK; - p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; - data = outputScript.slice(offset, offset + blockSize); - return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; - case 2: - _a.sent(); - offset += blockSize; - return [3 /*break*/, 1]; - case 3: return [2 /*return*/]; - } - }); + + var bs58check$5 = bs58checkBase(sha256x2); + + function pathElementsToBuffer(paths) { + var buffer = Buffer$k.alloc(1 + paths.length * 4); + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); }); + return buffer; + } + function bip32asBuffer(path) { + var pathElements = !path ? [] : pathStringToArray(path); + return pathElementsToBuffer(pathElements); + } + function pathArrayToString(pathElements) { + // Limitation: bippath can't handle and empty path. It shouldn't affect us + // right now, but might in the future. + // TODO: Fix support for empty path. + return bip32Path.fromPathArray(pathElements).toString(); + } + function pathStringToArray(path) { + return bip32Path.fromString(path).toPathArray(); + } + function pubkeyFromXpub(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return xpubBuf.slice(xpubBuf.length - 33); + } + function getXpubComponents(xpub) { + var xpubBuf = bs58check$5.decode(xpub); + return { + chaincode: xpubBuf.slice(13, 13 + 32), + pubkey: xpubBuf.slice(xpubBuf.length - 33), + version: xpubBuf.readUInt32BE(0) + }; + } + function hardenedPathOf(pathElements) { + for (var i = pathElements.length - 1; i >= 0; i--) { + if (pathElements[i] >= 0x80000000) { + return pathElements.slice(0, i + 1); + } + } + return []; } - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var getAppAndVersion = function (transport) { return __awaiter$5(void 0, void 0, void 0, function () { - var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$5(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; - case 1: - r = _a.sent(); - i = 0; - format = r[i++]; - browser$2(format === 1, "getAppAndVersion: format not supported"); - nameLength = r[i++]; - name = r.slice(i, (i += nameLength)).toString("ascii"); - versionLength = r[i++]; - version = r.slice(i, (i += versionLength)).toString("ascii"); - flagLength = r[i++]; - flags = r.slice(i, (i += flagLength)); - return [2 /*return*/, { - name: name, - version: version, - flags: flags - }]; - } - }); - }); }; + var src$1 = {}; - var re$5 = {exports: {}}; + var src = {}; - // Note: this is the semver.org version of the spec that it implements - // Not necessarily the package version of this code. - const SEMVER_SPEC_VERSION = '2.0.0'; + var bip32$1 = {}; - const MAX_LENGTH$2 = 256; - const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991; + var crypto$5 = {}; - // Max safe segment length for coercion. - const MAX_SAFE_COMPONENT_LENGTH = 16; + var inherits$5 = inherits_browser.exports; + var Buffer$4 = safeBuffer.exports.Buffer; - var constants = { - SEMVER_SPEC_VERSION, - MAX_LENGTH: MAX_LENGTH$2, - MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, - MAX_SAFE_COMPONENT_LENGTH - }; + var Base$4 = cipherBase; - const debug$3 = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) - ) ? (...args) => console.error('SEMVER', ...args) - : () => {}; + var ZEROS$1 = Buffer$4.alloc(128); + var blocksize = 64; - var debug_1 = debug$3; + function Hmac$2 (alg, key) { + Base$4.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$4.from(key); + } - (function (module, exports) { - const { MAX_SAFE_COMPONENT_LENGTH } = constants; - const debug = debug_1; - exports = module.exports = {}; + this._alg = alg; + this._key = key; - // The actual regexps go on exports.re - const re = exports.re = []; - const src = exports.src = []; - const t = exports.t = {}; - let R = 0; + if (key.length > blocksize) { + key = alg(key); + } else if (key.length < blocksize) { + key = Buffer$4.concat([key, ZEROS$1], blocksize); + } - const createToken = (name, value, isGlobal) => { - const index = R++; - debug(index, value); - t[name] = index; - src[index] = value; - re[index] = new RegExp(value, isGlobal ? 'g' : undefined); - }; + var ipad = this._ipad = Buffer$4.allocUnsafe(blocksize); + var opad = this._opad = Buffer$4.allocUnsafe(blocksize); - // The following Regular Expressions can be used for tokenizing, - // validating, and parsing SemVer version strings. + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } - // ## Numeric Identifier - // A single `0`, or a non-zero digit followed by zero or more digits. + this._hash = [ipad]; + } - createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); - createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + inherits$5(Hmac$2, Base$4); - // ## Non-numeric Identifier - // Zero or more digits, followed by a letter or hyphen, and then zero or - // more letters, digits, or hyphens. + Hmac$2.prototype._update = function (data) { + this._hash.push(data); + }; - createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + Hmac$2.prototype._final = function () { + var h = this._alg(Buffer$4.concat(this._hash)); + return this._alg(Buffer$4.concat([this._opad, h])) + }; + var legacy = Hmac$2; - // ## Main Version - // Three dot-separated numeric identifiers. + var MD5 = md5_js; - createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`); + var md5$1 = function (buffer) { + return new MD5().update(buffer).digest() + }; - createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + var inherits$4 = inherits_browser.exports; + var Legacy = legacy; + var Base$3 = cipherBase; + var Buffer$3 = safeBuffer.exports.Buffer; + var md5 = md5$1; + var RIPEMD160$1 = ripemd160$2; - // ## Pre-release Version Identifier - // A numeric identifier, or a non-numeric identifier. + var sha$1 = sha_js.exports; - createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`); + var ZEROS = Buffer$3.alloc(128); - createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`); + function Hmac$1 (alg, key) { + Base$3.call(this, 'digest'); + if (typeof key === 'string') { + key = Buffer$3.from(key); + } - // ## Pre-release Version - // Hyphen, followed by one or more dot-separated pre-release version - // identifiers. + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64; - createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + this._alg = alg; + this._key = key; + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + key = hash.update(key).digest(); + } else if (key.length < blocksize) { + key = Buffer$3.concat([key, ZEROS], blocksize); + } - createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + var ipad = this._ipad = Buffer$3.allocUnsafe(blocksize); + var opad = this._opad = Buffer$3.allocUnsafe(blocksize); - // ## Build Metadata Identifier - // Any combination of digits, letters, or hyphens. + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36; + opad[i] = key[i] ^ 0x5C; + } + this._hash = alg === 'rmd160' ? new RIPEMD160$1() : sha$1(alg); + this._hash.update(ipad); + } - createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + inherits$4(Hmac$1, Base$3); - // ## Build Metadata - // Plus sign, followed by one or more period-separated build metadata - // identifiers. + Hmac$1.prototype._update = function (data) { + this._hash.update(data); + }; - createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + Hmac$1.prototype._final = function () { + var h = this._hash.digest(); + var hash = this._alg === 'rmd160' ? new RIPEMD160$1() : sha$1(this._alg); + return hash.update(this._opad).update(h).digest() + }; - // ## Full Version String - // A main version, followed optionally by a pre-release version and - // build metadata. + var browser$2 = function createHmac (alg, key) { + alg = alg.toLowerCase(); + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac$1('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac$1(alg, key) + }; - // Note that the only major, minor, patch, and pre-release sections of - // the version string are capturing groups. The build metadata is not a - // capturing group, because it should not ever be used in version - // comparison. + Object.defineProperty(crypto$5, "__esModule", { value: true }); + const createHash$1 = browser$3; + const createHmac$1 = browser$2; + function hash160$2(buffer) { + const sha256Hash = createHash$1('sha256') + .update(buffer) + .digest(); + try { + return createHash$1('rmd160') + .update(sha256Hash) + .digest(); + } + catch (err) { + return createHash$1('ripemd160') + .update(sha256Hash) + .digest(); + } + } + crypto$5.hash160 = hash160$2; + function hmacSHA512(key, data) { + return createHmac$1('sha512', key) + .update(data) + .digest(); + } + crypto$5.hmacSHA512 = hmacSHA512; - createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`); + var bn$1 = {exports: {}}; - createToken('FULL', `^${src[t.FULLPLAIN]}$`); + (function (module) { + (function (module, exports) { - // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. - // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty - // common in the npm registry. - createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`); + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + // 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; + } - createToken('GTLT', '((?:<|>)?=?)'); + // BN - // Something like "2.*" or "1.2.x". - // Note that "x.x" is a valid xRange identifer, meaning "any version" - // Only the first item is strictly required. - createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`); + this.negative = 0; + this.words = null; + this.length = 0; - createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`); + // Reduction context + this.red = null; - createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } - // Coercion. - // Extract anything that could conceivably be a part of a valid semver - createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`); - createToken('COERCERTL', src[t.COERCE], true); + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - // Tilde ranges. - // Meaning is "reasonably at or greater than" - createToken('LONETILDE', '(?:~>?)'); + BN.BN = BN; + BN.wordSize = 26; - createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = '$1~'; + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; + } + } catch (e) { + } - createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - // Caret ranges. - // Meaning is "at least and backwards compatible with" - createToken('LONECARET', '(?:\\^)'); + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = '$1^'; + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - // A simple gt/lt/eq thing, or just "" to indicate "any version" - createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - // An expression to strip any whitespace between the gtlt and the thing - // it modifies, so that `> 1.2.3` ==> `>1.2.3` - createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = '$1$2$3'; + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - // Something like `1.2.3 - 1.2.4` - // Note that these all use the loose form, because they'll be - // checked against either the strict or loose comparator form - // later. - createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`); + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`); + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + this.negative = 1; + } - // Star ranges basically just allow anything at all. - createToken('STAR', '(<|>)?=?\\s*\\*'); - // >=0.0.0 is like a star - createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); - createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); - }(re$5, re$5.exports)); + 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); + } + } + } + }; - // parse out just the options we care about so we always get a consistent - // obj with keys in a consistent order. - const opts = ['includePrerelease', 'loose', 'rtl']; - const parseOptions$4 = options => - !options ? {} - : typeof options !== 'object' ? { loose: true } - : opts.filter(k => options[k]).reduce((options, k) => { - options[k] = true; - return options - }, {}); - var parseOptions_1 = parseOptions$4; + 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; + } - const numeric = /^[0-9]+$/; - const compareIdentifiers$1 = (a, b) => { - const anum = numeric.test(a); - const bnum = numeric.test(b); + if (endian !== 'le') return; - if (anum && bnum) { - a = +a; - b = +b; + // 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; + } } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 - }; + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } - const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + 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; + } - var identifiers = { - compareIdentifiers: compareIdentifiers$1, - rcompareIdentifiers - }; + // 24-bits chunks + var off = 0; + var j = 0; - const debug$2 = debug_1; - const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; - const { re: re$4, t: t$4 } = re$5.exports; + 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; + } + } + } - const parseOptions$3 = parseOptions_1; - const { compareIdentifiers } = identifiers; - class SemVer$e { - constructor (version, options) { - options = parseOptions$3(options); + this.strip(); + }; - if (version instanceof SemVer$e) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version + 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 { - version = version.version; + r += c; } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) } + return r; + } - if (version.length > MAX_LENGTH$1) { - throw new TypeError( - `version is longer than ${MAX_LENGTH$1} characters` - ) + 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; - debug$2('SemVer', version, options); - this.options = options; - this.loose = !!options.loose; - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - this.raw = version; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; + for (i = 0; i < mod; i++) { + pow *= base; + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + 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; + }; - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + 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; + }; - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }); + // 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; + }; - this.build = m[5] ? m[5].split('.') : []; - this.format(); - } + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - format () { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}`; + /* + + 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; } - return this.version + groupSizes[base] = groupSize; + groupBases[base] = groupBase; } - toString () { - return this.version - } + */ - compare (other) { - debug$2('SemVer.compare', this.version, this.options, other); - if (!(other instanceof SemVer$e)) { - if (typeof other === 'string' && other === this.version) { - return 0 + 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--; + } } - other = new SemVer$e(other, this.options); + 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; } - if (other.version === this.version) { - return 0 - } + assert(false, 'Base should be between 2 and 36'); + }; - return this.compareMain(other) || this.comparePre(other) - } + 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; + }; - compareMain (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; - comparePre (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); - } + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + 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; + } } - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) + 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; } - } while (++i) + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; } - compareBuild (other) { - if (!(other instanceof SemVer$e)) { - other = new SemVer$e(other, this.options); + 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; + }; - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug$2('prerelease compare', i, a, b); - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } + // 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; + }; - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier); - } - this.inc('pre', identifier); - break + function toBitArray (num) { + var w = new Array(num.bitLength()); - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0); - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0]; - } - } else { - this.prerelease = [identifier, 0]; - } - } - break + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; - default: - throw new Error(`invalid increment argument: ${release}`) + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } - this.format(); - this.raw = this.version; - return this + + return w; } - } - var semver$1 = SemVer$e; + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; - const {MAX_LENGTH} = constants; - const { re: re$3, t: t$3 } = re$5.exports; - const SemVer$d = semver$1; + 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; + }; - const parseOptions$2 = parseOptions_1; - const parse$5 = (version, options) => { - options = parseOptions$2(options); + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; - if (version instanceof SemVer$d) { - return version - } + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - if (typeof version !== 'string') { - return null - } + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - if (version.length > MAX_LENGTH) { - return null - } + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; - const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; - if (!r.test(version)) { - return null - } + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; - try { - return new SemVer$d(version, options) - } catch (er) { - return null - } - }; + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } - var parse_1 = parse$5; + return this; + }; - const parse$4 = parse_1; - const valid$1 = (version, options) => { - const v = parse$4(version, options); - return v ? v.version : null - }; - var valid_1 = valid$1; + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } - const parse$3 = parse_1; - const clean = (version, options) => { - const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); - return s ? s.version : null - }; - var clean_1 = clean; + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } - const SemVer$c = semver$1; + return this.strip(); + }; - const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options; - options = undefined; - } + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; - try { - return new SemVer$c(version, options).inc(release, identifier).version - } catch (er) { - return null - } - }; - var inc_1 = inc; + // 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); + }; - const SemVer$b = semver$1; - const compare$a = (a, b, loose) => - new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - var compare_1 = compare$a; + // 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; + } - const compare$9 = compare_1; - const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; - var eq_1 = eq$2; + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } - const parse$2 = parse_1; - const eq$1 = eq_1; + this.length = b.length; - const diff = (version1, version2) => { - if (eq$1(version1, version2)) { - return null - } else { - const v1 = parse$2(version1); - const v2 = parse$2(version2); - const hasPre = v1.prerelease.length || v2.prerelease.length; - const prefix = hasPre ? 'pre' : ''; - const defaultResult = hasPre ? 'prerelease' : ''; - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } + 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]; } } - return defaultResult // may be undefined - } - }; - var diff_1 = diff; - const SemVer$a = semver$1; - const major = (a, loose) => new SemVer$a(a, loose).major; - var major_1 = major; + this.length = a.length; - const SemVer$9 = semver$1; - const minor = (a, loose) => new SemVer$9(a, loose).minor; - var minor_1 = minor; + return this.strip(); + }; - const SemVer$8 = semver$1; - const patch = (a, loose) => new SemVer$8(a, loose).patch; - var patch_1 = patch; + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; - const parse$1 = parse_1; - const prerelease = (version, options) => { - const parsed = parse$1(version, options); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null - }; - var prerelease_1 = prerelease; + // 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); + }; - const compare$8 = compare_1; - const rcompare = (a, b, loose) => compare$8(b, a, loose); - var rcompare_1 = rcompare; - - const compare$7 = compare_1; - const compareLoose = (a, b) => compare$7(a, b, true); - var compareLoose_1 = compareLoose; + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; - const SemVer$7 = semver$1; - const compareBuild$2 = (a, b, loose) => { - const versionA = new SemVer$7(a, loose); - const versionB = new SemVer$7(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB) - }; - var compareBuild_1 = compareBuild$2; + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); - const compareBuild$1 = compareBuild_1; - const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); - var sort_1 = sort; + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - const compareBuild = compareBuild_1; - const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - var rsort_1 = rsort; + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - const compare$6 = compare_1; - const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; - var gt_1 = gt$3; + if (bitsLeft > 0) { + bytesNeeded--; + } - const compare$5 = compare_1; - const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; - var lt_1 = lt$2; + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - const compare$4 = compare_1; - const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; - var neq_1 = neq$1; + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - const compare$3 = compare_1; - const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; - var gte_1 = gte$2; + // And remove leading zeroes + return this.strip(); + }; - const compare$2 = compare_1; - const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; - var lte_1 = lte$2; + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - const eq = eq_1; - const neq = neq_1; - const gt$2 = gt_1; - const gte$1 = gte_1; - const lt$1 = lt_1; - const lte$1 = lte_1; + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - const cmp$1 = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a === b + var off = (bit / 26) | 0; + var wbit = bit % 26; - case '!==': - if (typeof a === 'object') - a = a.version; - if (typeof b === 'object') - b = b.version; - return a !== b + this._expand(off + 1); - case '': - case '=': - case '==': - return eq(a, b, loose) + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } - case '!=': - return neq(a, b, loose) + return this.strip(); + }; - case '>': - return gt$2(a, b, loose) + // 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]; + } + } - case '>=': - return gte$1(a, b, loose) + return this; + }; - case '<': - return lt$1(a, b, loose) + // 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; + } - case '<=': - return lte$1(a, b, loose) + if (this.length > num.length) return this.clone().iadd(num); - default: - throw new TypeError(`Invalid operator: ${op}`) - } - }; - var cmp_1 = cmp$1; + return num.clone().iadd(this); + }; - const SemVer$6 = semver$1; - const parse = parse_1; - const {re: re$2, t: t$2} = re$5.exports; + // 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; + } - const coerce = (version, options) => { - if (version instanceof SemVer$6) { - return version - } + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - if (typeof version === 'number') { - version = String(version); - } + 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; + } - if (typeof version !== 'string') { - return null - } + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } - options = options || {}; + this.length = Math.max(this.length, i); - let match = null; - if (!options.rtl) { - match = version.match(re$2[t$2.COERCE]); - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next; - while ((next = re$2[t$2.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + if (a !== this) { + this.negative = 1; } - // leave it in a clean state - re$2[t$2.COERCERTL].lastIndex = -1; - } - if (match === null) - return null + return this.strip(); + }; - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) - }; - var coerce_1 = coerce; + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; - var yallist = Yallist$1; + 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; + }; - Yallist$1.Node = Node; - Yallist$1.create = Yallist$1; + // 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--; + } - function Yallist$1 (list) { - var self = this; - if (!(self instanceof Yallist$1)) { - self = new Yallist$1(); + return out.strip(); } - self.tail = null; - self.head = null; - self.length = 0; + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item); - }); - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]); + 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 self - } + return res; + }; - Yallist$1.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; } - var next = node.next; - var prev = node.prev; + 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); + } - if (next) { - next.prev = prev; - } + return t; + }; - if (prev) { - prev.next = next; - } + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; - if (node === this.head) { - this.head = next; - } - if (node === this.tail) { - this.tail = prev; - } + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } - node.list.length--; - node.next = null; - node.prev = null; - node.list = null; + return rb; + }; - return next - }; + // 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]]; + } + }; - Yallist$1.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - if (node.list) { - node.list.removeNode(node); - } + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - var head = this.head; - node.list = this; - node.next = head; - if (head) { - head.prev = node; - } + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - this.head = node; - if (!this.tail) { - this.tail = node; - } - this.length++; - }; + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - Yallist$1.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - if (node.list) { - node.list.removeNode(node); - } + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; - var tail = this.tail; - node.list = this; - node.prev = tail; - if (tail) { - tail.next = node; - } + var rx = rtwdf_ * ro - itwdf_ * io; - this.tail = node; - if (!this.head) { - this.head = node; - } - this.length++; - }; + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; - Yallist$1.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]); - } - return this.length - }; + rtws[p + j] = re + ro; + itws[p + j] = ie + io; - Yallist$1.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]); - } - return this.length - }; + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; - Yallist$1.prototype.pop = function () { - if (!this.tail) { - return undefined - } + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; - var res = this.tail.value; - this.tail = this.tail.prev; - if (this.tail) { - this.tail.next = null; - } else { - this.head = null; - } - this.length--; - return res - }; + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; - Yallist$1.prototype.shift = function () { - if (!this.head) { - return undefined - } + 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++; + } - var res = this.head.value; - this.head = this.head.next; - if (this.head) { - this.head.prev = null; - } else { - this.tail = null; - } - this.length--; - return res - }; + return 1 << i + 1 + odd; + }; - Yallist$1.prototype.forEach = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this); - walker = walker.next; - } - }; + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; - Yallist$1.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this; - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this); - walker = walker.prev; - } - }; + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; - Yallist$1.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next; - } - if (i === n && walker !== null) { - return walker.value - } - }; + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; - Yallist$1.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev; - } - if (i === n && walker !== null) { - return walker.value - } - }; + t = iws[i]; - Yallist$1.prototype.map = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.next; - } - return res - }; + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; - Yallist$1.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this; - var res = new Yallist$1(); - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)); - walker = walker.prev; - } - return res - }; + 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; - Yallist$1.prototype.reduce = function (fn, initial) { - var acc; - var walker = this.head; - if (arguments.length > 1) { - acc = initial; - } else if (this.head) { - walker = this.head.next; - acc = this.head.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } + ws[i] = w & 0x3ffffff; - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i); - walker = walker.next; - } + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } - return acc - }; + return ws; + }; - Yallist$1.prototype.reduceReverse = function (fn, initial) { - var acc; - var walker = this.tail; - if (arguments.length > 1) { - acc = initial; - } else if (this.tail) { - walker = this.tail.prev; - acc = this.tail.value; - } else { - throw new TypeError('Reduce of empty list with no initial value') - } + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i); - walker = walker.prev; - } + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } - return acc - }; + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } - Yallist$1.prototype.toArray = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.next; - } - return arr - }; + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; - Yallist$1.prototype.toArrayReverse = function () { - var arr = new Array(this.length); - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value; - walker = walker.prev; - } - return arr - }; + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } - Yallist$1.prototype.slice = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next; - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value); - } - return ret - }; + return ph; + }; - Yallist$1.prototype.sliceReverse = function (from, to) { - to = to || this.length; - if (to < 0) { - to += this.length; - } - from = from || 0; - if (from < 0) { - from += this.length; - } - var ret = new Yallist$1(); - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0; - } - if (to > this.length) { - to = this.length; - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev; - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value); - } - return ret - }; + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); - Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1; - } - if (start < 0) { - start = this.length + start; - } + var rbt = this.makeRBT(N); - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next; - } + var _ = this.stub(N); - var ret = []; - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value); - walker = this.removeNode(walker); - } - if (walker === null) { - walker = this.tail; - } + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev; - } + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]); - } - return ret; - }; + var rmws = out.words; + rmws.length = N; - Yallist$1.prototype.reverse = function () { - var head = this.head; - var tail = this.tail; - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev; - walker.prev = walker.next; - walker.next = p; - } - this.head = tail; - this.tail = head; - return this - }; + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); - function insert (self, node, value) { - var inserted = node === self.head ? - new Node(value, null, node, self) : - new Node(value, node, node.next, self); + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); - if (inserted.next === null) { - self.tail = inserted; - } - if (inserted.prev === null) { - self.head = inserted; - } + 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; + } - self.length++; + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); - return inserted - } + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; - function push (self, item) { - self.tail = new Node(item, self.tail, null, self); - if (!self.head) { - self.head = self.tail; - } - self.length++; - } + // 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); + }; - function unshift (self, item) { - self.head = new Node(item, null, self.head, self); - if (!self.tail) { - self.tail = self.head; - } - self.length++; - } + // 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); + }; - function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; - this.list = list; - this.value = value; + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); - if (prev) { - prev.next = this; - this.prev = prev; - } else { - this.prev = null; - } + // 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 (next) { - next.prev = this; - this.next = next; - } else { - this.next = null; - } - } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } - try { - // add if support for Symbol.iterator is present - require('./iterator.js')(Yallist$1); - } catch (er) {} + return this; + }; - // A linked list to keep track of recently-used-ness - const Yallist = yallist; + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; - const MAX = Symbol('max'); - const LENGTH = Symbol('length'); - const LENGTH_CALCULATOR = Symbol('lengthCalculator'); - const ALLOW_STALE = Symbol('allowStale'); - const MAX_AGE = Symbol('maxAge'); - const DISPOSE = Symbol('dispose'); - const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); - const LRU_LIST = Symbol('lruList'); - const CACHE = Symbol('cache'); - const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; - const naiveLength = () => 1; + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; - // lruList is a yallist where the head is the youngest - // item, and the tail is the oldest. the list contains the Hit - // objects as the entries. - // Each Hit object has a reference to its Yallist.Node. This - // never changes. - // - // cache is a Map (or PseudoMap) that matches the keys to - // the Yallist.Node object. - class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options }; + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); - if (!options) - options = {}; + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - this[MAX] = options.max || Infinity; + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; - const lc = options.length || naiveLength; - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; - this[ALLOW_STALE] = options.stale || false; - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0; - this[DISPOSE] = options.dispose; - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; - this.reset(); - } + res = res.mul(q); + } + } - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') + return res; + }; - this[MAX] = mL || Infinity; - trim(this); - } - get max () { - return this[MAX] - } + // 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); + } - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale; - } - get allowStale () { - return this[ALLOW_STALE] - } + if (carry) { + this.words[i] = carry; + this.length++; + } + } - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } - this[MAX_AGE] = mA; - trim(this); - } - get maxAge () { - return this[MAX_AGE] - } + for (i = 0; i < s; i++) { + this.words[i] = 0; + } - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength; + this.length += s; + } - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC; - this[LENGTH] = 0; - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); - this[LENGTH] += hit.length; - }); + 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; } - trim(this); - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; - rforEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev; - forEachStep(this, fn, walker, thisp); - walker = prev; + 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; } - } - forEach (fn, thisp) { - thisp = thisp || this; - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next; - forEachStep(this, fn, walker, thisp); - walker = next; + if (s === 0) ; 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; } - } - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } + 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; + } - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; } - this[CACHE] = new Map(); // hash of items by key - this[LRU_LIST] = new Yallist(); // list of items in order of use recency - this[LENGTH] = 0; // length of items in the list - } + return this.strip(); + }; - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; - dumpLru () { - return this[LRU_LIST] - } + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE]; + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; - const now = maxAge ? Date.now() : 0; - const len = this[LENGTH_CALCULATOR](value, key); + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)); - return false - } + // 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; - const node = this[CACHE].get(key); - const item = node.value; + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value); - } + // Check bit and return + var w = this.words[s]; - item.now = now; - item.maxAge = maxAge; - item.value = value; - this[LENGTH] += len - item.length; - item.length = len; - this.get(key); - trim(this); - return true - } + return !!(w & q); + }; - const hit = new Entry(key, value, len, now, maxAge); + // 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; - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value); + assert(this.negative === 0, 'imaskn works only with positive numbers'); - return false + if (this.length <= s) { + return this; } - this[LENGTH] += hit.length; - this[LRU_LIST].unshift(hit); - this[CACHE].set(key, this[LRU_LIST].head); - trim(this); - return true - } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value; - return !isStale(this, hit) - } + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } - get (key) { - return get(this, key, true) - } + return this.strip(); + }; - peek (key) { - return get(this, key, false) - } + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; - pop () { - const node = this[LRU_LIST].tail; - if (!node) - return null + // 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; + } - del(this, node); - return node.value - } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } - del (key) { - del(this, this[CACHE].get(key)); - } + // Add without checks + return this._iaddn(num); + }; - load (arr) { - // reset the cache - this.reset(); + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; - const now = Date.now(); - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l]; - const expiresAt = hit.e || 0; - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v); - else { - const maxAge = expiresAt - now; - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge); - } + // 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); - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)); - } - } + return this; + }; - const get = (self, key, doUse) => { - const node = self[CACHE].get(key); - if (node) { - const hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - return undefined + // 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 { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now(); - self[LRU_LIST].unshiftNode(node); + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; } } - return hit.value - } - }; - const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false + return this.strip(); + }; - const diff = Date.now() - hit.now; - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) - }; + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; - const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev; - del(self, walker); - walker = prev; - } - } - }; + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; - const del = (self, node) => { - if (node) { - const hit = node.value; - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value); + BN.prototype.iabs = function iabs () { + this.negative = 0; - self[LENGTH] -= hit.length; - self[CACHE].delete(hit.key); - self[LRU_LIST].removeNode(node); - } - }; + return this; + }; - class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key; - this.value = value; - this.length = length; - this.now = now; - this.maxAge = maxAge || 0; - } - } + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; - const forEachStep = (self, fn, node, thisp) => { - let hit = node.value; - if (isStale(self, hit)) { - del(self, node); - if (!self[ALLOW_STALE]) - hit = undefined; - } - if (hit) - fn.call(thisp, hit.value, hit.key, self); - }; + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; - var lruCache = LRUCache; + this._expand(len); - // hoisted class for cyclic dependency - class Range$a { - constructor (range, options) { - options = parseOptions$1(options); + 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 (range instanceof Range$a) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range$a(range.raw, options) - } + 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; - if (range instanceof Comparator$3) { - // just put it in the set and return - this.raw = range.value; - this.set = [[range]]; - this.format(); - return this + 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; } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; + // Initialize quotient + var m = a.length - b.length; + var q; - // First, split based on boolean or || - this.raw = range; - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length); + 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; + } + } - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } } - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0]; - this.set = this.set.filter(c => !isNullSet(c[0])); - if (this.set.length === 0) - this.set = [first]; - else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break - } + 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(); - this.format(); - } + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim(); - return this.range - } + return { + div: q || null, + mod: a + }; + }; - toString () { - return this.range - } + // 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) + }; + } - parseRange (range) { - range = range.trim(); + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = Object.keys(this.options).join(','); - const memoKey = `parseRange:${memoOpts}:${range}`; - const cached = cache.get(memoKey); - if (cached) - return cached + if (mode !== 'mod') { + div = res.div.neg(); + } - const loose = this.options.loose; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug$1('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); - debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + return { + div: div, + mod: mod + }; + } - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); - // normalize spaces - range = range.split(/\s+/).join(' '); + if (mode !== 'mod') { + div = res.div.neg(); + } - // At this point, the range is completely trimmed and - // ready to be split into comparators. + return { + div: div, + mod: res.mod + }; + } - const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; - const rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator$3(comp, this.options)); + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - rangeList.length; - const rangeMap = new Map(); - for (const comp of rangeList) { - if (isNullSet(comp)) - return [comp] - rangeMap.set(comp.value, comp); + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; } - if (rangeMap.size > 1 && rangeMap.has('')) - rangeMap.delete(''); - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result - } + // Both numbers are positive at this point - intersects (range, options) { - if (!(range instanceof Range$a)) { - throw new TypeError('a Range is required') + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; } - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer$5(version, this.options); - } catch (er) { - return false + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; } - } - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true + 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 false - } - } - var range = Range$a; - const LRU = lruCache; - const cache = new LRU({ max: 1000 }); + return this._wordDiv(num, mode); + }; - const parseOptions$1 = parseOptions_1; - const Comparator$3 = comparator; - const debug$1 = debug_1; - const SemVer$5 = semver$1; - const { - re: re$1, - t: t$1, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = re$5.exports; + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; - const isNullSet = c => c.value === '<0.0.0-0'; - const isAny = c => c.value === ''; + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; - // take a set of comparators and determine whether there - // exists a version which can satisfy it - const isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }); + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); - testComparator = remainingComparators.pop(); - } + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; - return result - }; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - // comprised of xranges, tildes, stars, and gtlt's at this point. - // already replaced the hyphen ranges - // turn into a set of JUST comparators. - const parseComparator = (comp, options) => { - debug$1('comp', comp, options); - comp = replaceCarets(comp, options); - debug$1('caret', comp); - comp = replaceTildes(comp, options); - debug$1('tildes', comp); - comp = replaceXRanges(comp, options); - debug$1('xrange', comp); - comp = replaceStars(comp, options); - debug$1('stars', comp); - return comp - }; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); - const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - // ~, ~> --> * (any, kinda silly) - // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 - // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 - // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 - // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 - // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 - const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' '); + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; - const replaceTilde = (comp, options) => { - const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('tilde', comp, _, M, m, p, pr); - let ret; + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug$1('replaceTilde pr', pr); - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; + 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 { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0`; + x = x.clone(); } - debug$1('tilde return', ret); - return ret - }) - }; + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); - // ^ --> * (any, kinda silly) - // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 - // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 - // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 - // ^1.2.3 --> >=1.2.3 <2.0.0-0 - // ^1.2.0 --> >=1.2.0 <2.0.0-0 - const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' '); + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); - const replaceCaret = (comp, options) => { - debug$1('caret', comp, options); - const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; - const z = options.includePrerelease ? '-0' : ''; - return comp.replace(r, (_, M, m, p, pr) => { - debug$1('caret', comp, _, M, m, p, pr); - let ret; + var g = 0; - if (isX(M)) { - ret = ''; - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-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); + } } - } else if (pr) { - debug$1('replaceCaret pr', pr); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0`; + + 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 { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0`; + 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 { - debug$1('no pr'); - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; + 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 { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0`; + b.isub(a); + x2.isub(x1); } } - debug$1('caret return', ret); - return ret - }) - }; + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - const replaceXRanges = (comp, options) => { - debug$1('replaceXRanges', comp, options); - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') - }; + if (res.cmpn(0) < 0) { + res.iadd(p); + } - const replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug$1('xRange', comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; + return res; + }; - if (gtlt === '=' && anyX) { - gtlt = ''; - } + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : ''; + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0'; - } else { - // nothing is forbidden - ret = '*'; + // 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); } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0; + while (b.isEven()) { + b.iushrn(1); } - p = 0; - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) { - M = +M + 1; - } else { - m = +m + 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; } - if (gtlt === '<') - pr = '-0'; + a.isub(b); + } while (true); - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0`; + 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; } - debug$1('xRange return', ret); + // 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; + }; - return ret - }) - }; + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; - // Because * is AND-ed with everything else in the comparator, - // and '' means "any version", just remove the *s entirely. - const replaceStars = (comp, options) => { - debug$1('replaceStars', comp, options); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re$1[t$1.STAR], '') - }; + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; - const replaceGTE0 = (comp, options) => { - debug$1('replaceGTE0', comp, options); - return comp.trim() - .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') - }; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; - // This function is passed to string.replace(re[t.HYPHENRANGE]) - // M, m, patch, prerelease, build - // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 - // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do - // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 - const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = ''; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? '-0' : ''}`; - } + this.strip(); - if (isX(tM)) { - to = ''; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } - return (`${from} ${to}`).trim() - }; + assert(num <= 0x3ffffff, 'Number is too big'); - const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; } - } + if (this.negative !== 0) return -res | 0; + return res; + }; - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug$1(set[i].semver); - if (set[i].semver === Comparator$3.ANY) { - continue - } + // 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; + }; - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } + // 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; + }; - // Version has a -pre, but it's not one of the ones we like. - return false - } + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; - return true - }; + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; - const ANY$2 = Symbol('SemVer ANY'); - // hoisted class for cyclic dependency - class Comparator$2 { - static get ANY () { - return ANY$2 + 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(); } - constructor (comp, options) { - options = parseOptions(options); - if (comp instanceof Comparator$2) { - if (comp.loose === !!options.loose) { - return comp + 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 { - comp = comp.value; + // r is BN v5 instance + r._strip(); } } - debug('comparator', comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); + return r; + }; - if (this.semver === ANY$2) { - this.value = ''; - } else { - this.value = this.operator + this.semver.version; - } + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; - debug('comp', this); + 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); - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; } + output.length = outLen; - this.operator = m[1] !== undefined ? m[1] : ''; - if (this.operator === '=') { - this.operator = ''; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY$2; + // 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 { - this.semver = new SemVer$4(m[2], this.options.loose); + 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); - toString () { - return this.value + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } + inherits(P192, MPrime); - test (version) { - debug('Comparator.test', version, this.options.loose); + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); - if (this.semver === ANY$2 || version === ANY$2) { - return true + 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; + }; - if (typeof version === 'string') { - try { - version = new SemVer$4(version, this.options); - } catch (er) { - return false - } + // 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 cmp(version, this.operator, this.semver, this.options) + 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; + } } - intersects (comp, options) { - if (!(comp instanceof Comparator$2)) { - throw new TypeError('a Comparator is required') + 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(); } - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - }; + 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); + }; - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range$9(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range$9(this.value, options).test(comp.semver) + 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; + }; - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - const sameSemVer = this.semver.version === comp.semver.version; - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<'); - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>'); + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) - } - } + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; - var comparator = Comparator$2; + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); - const parseOptions = parseOptions_1; - const {re, t} = re$5.exports; - const cmp = cmp_1; - const debug = debug_1; - const SemVer$4 = semver$1; - const Range$9 = range; + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; - const Range$8 = range; - const satisfies$3 = (version, range, options) => { - try { - range = new Range$8(range, options); - } catch (er) { - return false - } - return range.test(version) - }; - var satisfies_1 = satisfies$3; + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; - const Range$7 = range; + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; - // Mostly just for testing and legacy API reasons - const toComparators = (range, options) => - new Range$7(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; - var toComparators_1 = toComparators; + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; - const SemVer$3 = semver$1; - const Range$6 = range; + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; - const maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range$6(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v; - maxSV = new SemVer$3(max, options); - } + 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); } - }); - return max - }; - var maxSatisfying_1 = maxSatisfying; - const SemVer$2 = semver$1; - const Range$5 = range; - const minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range$5(range, options); - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v; - minSV = new SemVer$2(min, options); + // 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 min - }; - var minSatisfying_1 = minSatisfying; - const SemVer$1 = semver$1; - const Range$4 = range; - const gt$1 = gt_1; + return r; + }; - const minVersion = (range, loose) => { - range = new Range$4(range, loose); + 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); + } + }; - let minver = new SemVer$1('0.0.0'); - if (range.test(minver)) { - return minver - } + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); - minver = new SemVer$1('0.0.0-0'); - if (range.test(minver)) { - return minver - } + 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); + } - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } - let setMin = null; - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer$1(comparator.semver.version); - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt$1(compver, setMin)) { - setMin = compver; - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }); - if (setMin && (!minver || gt$1(minver, setMin))) - minver = setMin; - } + 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 (minver && range.test(minver)) { - return minver - } + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } - return null - }; - var minVersion_1 = minVersion; + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - const Range$3 = range; - const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range$3(range, options).range || '*' - } catch (er) { - return null - } - }; - var valid = validRange; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } - const SemVer = semver$1; - const Comparator$1 = comparator; - const {ANY: ANY$1} = Comparator$1; - const Range$2 = range; - const satisfies$2 = satisfies_1; - const gt = gt_1; - const lt = lt_1; - const lte = lte_1; - const gte = gte_1; + return res; + }; - const outside$2 = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range$2(range, options); + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } + return r === num ? r.clone() : r; + }; - // If it satisfies the range it is not outside - if (satisfies$2(version, range, options)) { - return false - } + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; + // + // Montgomery method engine + // - let high = null; - let low = null; + BN.mont = function mont (num) { + return new Mont(num); + }; - comparators.forEach((comparator) => { - if (comparator.semver === ANY$1) { - comparator = new Comparator$1('>=0.0.0'); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); + function Mont (m) { + Red.call(this, m); - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } + 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); } - return true - }; + inherits(Mont, Red); - var outside_1 = outside$2; + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; - // Determine if version is greater than all the versions possible in the range. - const outside$1 = outside_1; - const gtr = (version, range, options) => outside$1(version, range, '>', options); - var gtr_1 = gtr; + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; - const outside = outside_1; - // Determine if version is less than all the versions possible in the range - const ltr = (version, range, options) => outside(version, range, '<', options); - var ltr_1 = ltr; + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } - const Range$1 = range; - const intersects = (r1, r2, options) => { - r1 = new Range$1(r1, options); - r2 = new Range$1(r2, options); - return r1.intersects(r2) - }; - var intersects_1 = intersects; + 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; - // given a set of versions and a range, create a "simplified" range - // that includes the same versions that the original range does - // If the original range is shorter than the simplified one, return that. - const satisfies$1 = satisfies_1; - const compare$1 = compare_1; - var simplify = (versions, range, options) => { - const set = []; - let min = null; - let prev = null; - const v = versions.sort((a, b) => compare$1(a, b, options)); - for (const version of v) { - const included = satisfies$1(version, range, options); - if (included) { - prev = version; - if (!min) - min = version; - } else { - if (prev) { - set.push([min, prev]); - } - prev = null; - min = null; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); } - } - if (min) - set.push([min, null]); - const ranges = []; - for (const [min, max] of set) { - if (min === max) - ranges.push(min); - else if (!max && min === v[0]) - ranges.push('*'); - else if (!max) - ranges.push(`>=${min}`); - else if (min === v[0]) - ranges.push(`<=${max}`); - else - ranges.push(`${min} - ${max}`); - } - const simplified = ranges.join(' || '); - const original = typeof range.raw === 'string' ? range.raw : String(range); - return simplified.length < original.length ? simplified : range - }; + return res._forceRed(this); + }; - const Range = range; - const Comparator = comparator; - const { ANY } = Comparator; - const satisfies = satisfies_1; - const compare = compare_1; + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: - // - Every simple range `r1, r2, ...` is a null set, OR - // - Every simple range `r1, r2, ...` which is not a null set is a subset of - // some `R1, R2, ...` - // - // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: - // - If c is only the ANY comparator - // - If C is only the ANY comparator, return true - // - Else if in prerelease mode, return false - // - else replace c with `[>=0.0.0]` - // - If C is only the ANY comparator - // - if in prerelease mode, return true - // - else replace C with `[>=0.0.0]` - // - Let EQ be the set of = comparators in c - // - If EQ is more than one, return true (null set) - // - Let GT be the highest > or >= comparator in c - // - Let LT be the lowest < or <= comparator in c - // - If GT and LT, and GT.semver > LT.semver, return true (null set) - // - If any C is a = range, and GT or LT are set, return false - // - If EQ - // - If GT, and EQ does not satisfy GT, return true (null set) - // - If LT, and EQ does not satisfy LT, return true (null set) - // - If EQ satisfies every C, return true - // - Else return false - // - If GT - // - If GT.semver is lower than any > or >= comp in C, return false - // - If GT is >=, and GT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the GT.semver tuple, return false - // - If LT - // - If LT.semver is greater than any < or <= comp in C, return false - // - If LT is <=, and LT.semver does not satisfy every C, return false - // - If GT.semver has a prerelease, and not in prerelease mode - // - If no C has a prerelease and the LT.semver tuple, return false - // - Else return true + 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); + } - const subset = (sub, dom, options = {}) => { - if (sub === dom) - return true + return res._forceRed(this); + }; - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; + 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); + }; + })(module, commonjsGlobal); + }(bn$1)); - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) - continue OUTER - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) - return false - } - return true - }; + var elliptic = {}; - const simpleSubset = (sub, dom, options) => { - if (sub === dom) - return true + var name = "elliptic"; + var version = "6.5.4"; + var description = "EC cryptography"; + var main = "lib/elliptic.js"; + var files = [ + "lib" + ]; + var scripts = { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/" + }; + var repository = { + type: "git", + url: "git@github.com:indutny/elliptic" + }; + var keywords = [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ]; + var author = "Fedor Indutny "; + var license = "MIT"; + var bugs = { + url: "https://github.com/indutny/elliptic/issues" + }; + var homepage = "https://github.com/indutny/elliptic"; + var devDependencies = { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1" + }; + var dependencies = { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }; + var require$$0$1 = { + name: name, + version: version, + description: description, + main: main, + files: files, + scripts: scripts, + repository: repository, + keywords: keywords, + author: author, + license: license, + bugs: bugs, + homepage: homepage, + devDependencies: devDependencies, + dependencies: dependencies + }; + + var utils$n = {}; + + var bn = {exports: {}}; - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) - return true - else if (options.includePrerelease) - sub = [ new Comparator('>=0.0.0-0') ]; - else - sub = [ new Comparator('>=0.0.0') ]; + (function (module) { + (function (module, exports) { + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); } - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) - return true - else - dom = [ new Comparator('>=0.0.0') ]; + // 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; } - const eqSet = new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') - gt = higherGT(gt, c, options); - else if (c.operator === '<' || c.operator === '<=') - lt = lowerLT(lt, c, options); - else - eqSet.add(c.semver); + // 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; } - if (eqSet.size > 1) - return null + BN.BN = BN; + BN.wordSize = 26; - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) - return null - else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) - return null + var Buffer; + try { + if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { + Buffer = window.Buffer; + } else { + Buffer = require('buffer').Buffer; + } + } catch (e) { } - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) - return null + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - if (lt && !satisfies(eq, String(lt), options)) - return null + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - for (const c of dom) { - if (!satisfies(eq, String(c), options)) - return false + 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); } - return true - } + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - let higher, lower; - let hasDomLT, hasDomGT; - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false; - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; + 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); } } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) - return false - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) - return false } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; + }; + + 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++; } } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) - return false - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) - return false } - if (!c.operator && (lt || gt) && gtltComp !== 0) - return false + 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; + } } - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) - return false + function parseHexByte (string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; + } - if (lt && hasDomGT && !gt && gtltComp !== 0) - return false + 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; + } - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) - return false + // 24-bits chunks + var off = 0; + var j = 0; - return true - }; + 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; + } + } + } - // >=1.2.3 is lower than >1.2.3 - const higherGT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a - }; + this.strip(); + }; - // <=1.2.3 is higher than <1.2.3 - const lowerLT = (a, b, options) => { - if (!a) - return b - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a - }; + 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; - var subset_1 = subset; + r *= mul; - // just pre-load all the stuff that index.js lazily exports - const internalRe = re$5.exports; - var semver = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - SemVer: semver$1, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, - parse: parse_1, - valid: valid_1, - clean: clean_1, - inc: inc_1, - diff: diff_1, - major: major_1, - minor: minor_1, - patch: patch_1, - prerelease: prerelease_1, - compare: compare_1, - rcompare: rcompare_1, - compareLoose: compareLoose_1, - compareBuild: compareBuild_1, - sort: sort_1, - rsort: rsort_1, - gt: gt_1, - lt: lt_1, - eq: eq_1, - neq: neq_1, - gte: gte_1, - lte: lte_1, - cmp: cmp_1, - coerce: coerce_1, - Comparator: comparator, - Range: range, - satisfies: satisfies_1, - toComparators: toComparators_1, - maxSatisfying: maxSatisfying_1, - minSatisfying: minSatisfying_1, - minVersion: minVersion_1, - validRange: valid, - outside: outside_1, - gtr: gtr_1, - ltr: ltr_1, - intersects: intersects_1, - simplifyRange: simplify, - subset: subset_1, - }; + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; - function shouldUseTrustedInputForSegwit(_a) { - var version = _a.version, name = _a.name; - if (name === "Decred") - return false; - if (name === "Exchange") - return true; - return semver.gte(version, "1.4.0"); - } + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; - var __assign$3 = (undefined && undefined.__assign) || function () { - __assign$3 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + // '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; } - return t; + 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); }; - return __assign$3.apply(this, arguments); - }; - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + } 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) ; 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); + }; + })(module, commonjsGlobal); + }(bn)); + + var minimalisticAssert = assert$f; + + function assert$f(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); + } + + assert$f.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); + }; + + var utils$m = {}; + + (function (exports) { + + 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; + }; + }(utils$m)); + + (function (exports) { + + var utils = exports; + var BN = bn.exports; + var minAssert = minimalisticAssert; + var minUtils = utils$m; + + 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; + }(utils$n)); + + var brorand = {exports: {}}; + + var r$1; + + brorand.exports = function rand(len) { + if (!r$1) + r$1 = new Rand(null); + + return r$1.generate(len); + }; + + function Rand(rand) { + this.rand = rand; + } + brorand.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$4 = require('crypto'); + if (typeof crypto$4.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto$4.randomBytes(n); + }; + } catch (e) { + } + } + + var curve = {}; + + var BN$8 = bn.exports; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; + + function BaseCurve(type, conf) { + this.type = type; + this.p = new BN$8(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN$8.red(conf.prime) : BN$8.mont(this.p); + + // Useful for many curves + this.zero = new BN$8(0).toRed(this.red); + this.one = new BN$8(1).toRed(this.red); + this.two = new BN$8(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN$8(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); + } + } + var base = 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$e(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$e(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]; + 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$l.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$e(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert$e(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$l.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; + }; + + var utils$k = utils$n; + var BN$7 = bn.exports; + var inherits$3 = inherits_browser.exports; + var Base$2 = base; + + var assert$d = utils$k.assert; + + function ShortCurve(conf) { + Base$2.call(this, 'short', conf); + + this.a = new BN$7(conf.a, 16).toRed(this.red); + this.b = new BN$7(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$3(ShortCurve, Base$2); + var short = 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$7(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$7(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$d(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$7(vec.a, 16), + b: new BN$7(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$7.mont(num); + var tinv = new BN$7(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN$7(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$7(1); + var y1 = new BN$7(0); + var x2 = new BN$7(0); + var y2 = new BN$7(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$7(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$2(curve, x, y, isRed) { + Base$2.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(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$3(Point$2, Base$2.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point$2(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point$2.fromJSON(this, obj, red); + }; + + Point$2.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$2.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$2.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$2.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$2.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point$2.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$2.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$2.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point$2.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point$2.prototype.mul = function mul(k) { + k = new BN$7(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$2.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$2.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$2.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$2.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$2.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$2.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$7(0); + } else { + this.x = new BN$7(x, 16); + this.y = new BN$7(y, 16); + this.z = new BN$7(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$3(JPoint, Base$2.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$7(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; + }; + + var BN$6 = bn.exports; + var inherits$2 = inherits_browser.exports; + var Base$1 = base; + + var utils$j = utils$n; + + function MontCurve(conf) { + Base$1.call(this, 'mont', conf); + + this.a = new BN$6(conf.a, 16).toRed(this.red); + this.b = new BN$6(conf.b, 16).toRed(this.red); + this.i4 = new BN$6(4).toRed(this.red).redInvm(); + this.two = new BN$6(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits$2(MontCurve, Base$1); + var mont = 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$1(curve, x, z) { + Base$1.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$6(x, 16); + this.z = new BN$6(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$2(Point$1, Base$1.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils$j.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point$1(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point$1.fromJSON(this, obj); + }; + + Point$1.prototype.precompute = function precompute() { + // No-op + }; + + Point$1.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point$1.fromJSON = function fromJSON(curve, obj) { + return new Point$1(curve, obj[0], obj[1] || curve.one); + }; + + Point$1.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point$1.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point$1.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$1.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.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$1.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$1.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point$1.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point$1.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point$1.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + var utils$i = utils$n; + var BN$5 = bn.exports; + var inherits$1 = inherits_browser.exports; + var Base = base; + + var assert$c = utils$i.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$5(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN$5(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN$5(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert$c(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; + } + inherits$1(EdwardsCurve, Base); + var edwards = 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$5(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$5(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$5(x, 16); + this.y = new BN$5(y, 16); + this.z = z ? new BN$5(z, 16) : this.curve.one; + this.t = t && new BN$5(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$1(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; + + (function (exports) { + + var curve = exports; + + curve.base = base; + curve.short = short; + curve.mont = mont; + curve.edwards = edwards; + }(curve)); + + var curves$2 = {}; + + var hash$2 = {}; + + var utils$h = {}; + + var assert$b = minimalisticAssert; + var inherits = inherits_browser.exports; + + utils$h.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; + } + utils$h.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils$h.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + utils$h.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; + } + utils$h.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils$h.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; + } + utils$h.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert$b(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; + } + utils$h.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; + } + utils$h.split32 = split32; + + function rotr32$1(w, b) { + return (w >>> b) | (w << (32 - b)); + } + utils$h.rotr32 = rotr32$1; + + function rotl32$2(w, b) { + return (w << b) | (w >>> (32 - b)); + } + utils$h.rotl32 = rotl32$2; + + function sum32$3(a, b) { + return (a + b) >>> 0; + } + utils$h.sum32 = sum32$3; + + function sum32_3$1(a, b, c) { + return (a + b + c) >>> 0; + } + utils$h.sum32_3 = sum32_3$1; + + function sum32_4$2(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + utils$h.sum32_4 = sum32_4$2; + + function sum32_5$2(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + utils$h.sum32_5 = sum32_5$2; + + function sum64$1(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; + } + utils$h.sum64 = sum64$1; + + function sum64_hi$1(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + utils$h.sum64_hi = sum64_hi$1; + + function sum64_lo$1(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + utils$h.sum64_lo = sum64_lo$1; + + function sum64_4_hi$1(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; + } + utils$h.sum64_4_hi = sum64_4_hi$1; + + function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + utils$h.sum64_4_lo = sum64_4_lo$1; + + function sum64_5_hi$1(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; + } + utils$h.sum64_5_hi = sum64_5_hi$1; + + function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + utils$h.sum64_5_lo = sum64_5_lo$1; + + function rotr64_hi$1(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + utils$h.rotr64_hi = rotr64_hi$1; + + function rotr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.rotr64_lo = rotr64_lo$1; + + function shr64_hi$1(ah, al, num) { + return ah >>> num; + } + utils$h.shr64_hi = shr64_hi$1; + + function shr64_lo$1(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + utils$h.shr64_lo = shr64_lo$1; + + var common$5 = {}; + + var utils$g = utils$h; + var assert$a = minimalisticAssert; + + function BlockHash$4() { + 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; + } + common$5.BlockHash = BlockHash$4; + + BlockHash$4.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils$g.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$g.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$4.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert$a(this.pending === null); + + return this._digest(enc); + }; + + BlockHash$4.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; + }; + + var sha = {}; + + var common$4 = {}; + + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; + + function ft_1$1(s, x, y, z) { + if (s === 0) + return ch32$1(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32$1(x, y, z); + } + common$4.ft_1 = ft_1$1; + + function ch32$1(x, y, z) { + return (x & y) ^ ((~x) & z); + } + common$4.ch32 = ch32$1; + + function maj32$1(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + common$4.maj32 = maj32$1; + + function p32(x, y, z) { + return x ^ y ^ z; + } + common$4.p32 = p32; + + function s0_256$1(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + common$4.s0_256 = s0_256$1; + + function s1_256$1(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + common$4.s1_256 = s1_256$1; + + function g0_256$1(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + common$4.g0_256 = g0_256$1; + + function g1_256$1(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + common$4.g1_256 = g1_256$1; + + var utils$e = utils$h; + var common$3 = common$5; + var shaCommon$1 = common$4; + + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; + var ft_1 = shaCommon$1.ft_1; + var BlockHash$3 = common$3.BlockHash; + + var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 + ]; + + function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash$3.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); + } + + utils$e.inherits(SHA1, BlockHash$3); + var _1 = 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$1(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$1(rotl32$1(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$e.toHex32(this.h, 'big'); + else + return utils$e.split32(this.h, 'big'); + }; + + var utils$d = utils$h; + var common$2 = common$5; + var shaCommon = common$4; + var assert$9 = minimalisticAssert; + + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.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$2 = common$2.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$1() { + if (!(this instanceof SHA256$1)) + return new SHA256$1(); + + BlockHash$2.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils$d.inherits(SHA256$1, BlockHash$2); + var _256 = SHA256$1; + + SHA256$1.blockSize = 512; + SHA256$1.outSize = 256; + SHA256$1.hmacStrength = 192; + SHA256$1.padLength = 64; + + SHA256$1.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$1(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$9(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$1(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32$1(d, T1); + d = c; + c = b; + b = a; + a = sum32$1(T1, T2); + } + + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); + this.h[5] = sum32$1(this.h[5], f); + this.h[6] = sum32$1(this.h[6], g); + this.h[7] = sum32$1(this.h[7], h); + }; + + SHA256$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$d.toHex32(this.h, 'big'); + else + return utils$d.split32(this.h, 'big'); + }; + + var utils$c = utils$h; + var SHA256 = _256; + + function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils$c.inherits(SHA224, SHA256); + var _224 = 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$c.toHex32(this.h.slice(0, 7), 'big'); + else + return utils$c.split32(this.h.slice(0, 7), 'big'); + }; + + var utils$b = utils$h; + var common$1 = common$5; + var assert$8 = minimalisticAssert; + + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; + + var BlockHash$1 = common$1.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$1() { + if (!(this instanceof SHA512$1)) + return new SHA512$1(); + + BlockHash$1.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$b.inherits(SHA512$1, BlockHash$1); + var _512 = SHA512$1; + + SHA512$1.blockSize = 1024; + SHA512$1.outSize = 512; + SHA512$1.hmacStrength = 192; + SHA512$1.padLength = 128; + + SHA512$1.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$1.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$8(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); + 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); + 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$1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$b.toHex32(this.h, 'big'); + else + return utils$b.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; + } + + var utils$a = utils$h; + + var SHA512 = _512; + + 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$a.inherits(SHA384, SHA512); + var _384 = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils$a.toHex32(this.h.slice(0, 12), 'big'); + else + return utils$a.split32(this.h.slice(0, 12), 'big'); + }; + + sha.sha1 = _1; + sha.sha224 = _224; + sha.sha256 = _256; + sha.sha384 = _384; + sha.sha512 = _512; + + var ripemd = {}; + + var utils$9 = utils$h; + var common = common$5; + + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.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$9.inherits(RIPEMD160, BlockHash); + ripemd.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$9.toHex32(this.h, 'little'); + else + return utils$9.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 + ]; + + var utils$8 = utils$h; + var assert$7 = minimalisticAssert; + + 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$8.toArray(key, enc)); + } + var hmac = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert$7(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); + }; + + (function (exports) { + var hash = exports; + + hash.utils = utils$h; + hash.common = common$5; + hash.sha = sha; + hash.ripemd = ripemd; + hash.hmac = hmac; + + // 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; + }(hash$2)); + + (function (exports) { + + var curves = exports; + + var hash = hash$2; + var curve$1 = curve; + var utils = utils$n; + + var assert = utils.assert; + + function PresetCurve(options) { + if (options.type === 'short') + this.curve = new curve$1.short(options); + else if (options.type === 'edwards') + this.curve = new curve$1.edwards(options); + else + this.curve = new curve$1.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 = require('./precomputed/secp256k1'); + } 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, + ], + }); + }(curves$2)); + + var hash$1 = hash$2; + var utils$7 = utils$m; + var assert$6 = minimalisticAssert; + + function HmacDRBG$1(options) { + if (!(this instanceof HmacDRBG$1)) + return new HmacDRBG$1(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$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + var hmacDrbg = HmacDRBG$1; + + HmacDRBG$1.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$1.prototype._hmac = function hmac() { + return new hash$1.hmac(this.hash, this.K); + }; + + HmacDRBG$1.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$1.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); + + assert$6(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG$1.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$7.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$7.encode(res, enc); + }; + + var BN$4 = bn.exports; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; + + function KeyPair$4(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); + } + var key$1 = KeyPair$4; + + KeyPair$4.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair$4) + return pub; + + return new KeyPair$4(ec, { + pub: pub, + pubEnc: enc, + }); + }; + + KeyPair$4.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair$4) + return priv; + + return new KeyPair$4(ec, { + priv: priv, + privEnc: enc, + }); + }; + + KeyPair$4.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$4.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$4.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair$4.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN$4(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$4.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$5(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert$5(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$4.prototype.derive = function derive(pub) { + if(!pub.validate()) { + assert$5(pub.validate(), 'public point not validated'); + } + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair$4.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair$4.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair$4.prototype.inspect = function inspect() { + return ''; + }; + + var BN$3 = bn.exports; + + var utils$5 = utils$n; + var assert$4 = utils$5.assert; + + function Signature$3(options, enc) { + if (options instanceof Signature$3) + return options; + + if (this._importDER(options, enc)) + return; + + assert$4(options.r && options.s, 'Signature without r or s'); + this.r = new BN$3(options.r, 16); + this.s = new BN$3(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + var signature$1 = Signature$3; + + 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$3.prototype._importDER = function _importDER(data, enc) { + data = utils$5.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$3(r); + this.s = new BN$3(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$3.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$5.encode(res, enc); + }; + + var BN$2 = bn.exports; + var HmacDRBG = hmacDrbg; + var utils$4 = utils$n; + var curves$1 = curves$2; + var rand = brorand.exports; + var assert$3 = utils$4.assert; + + var KeyPair$3 = key$1; + var Signature$2 = signature$1; + + function EC$1(options) { + if (!(this instanceof EC$1)) + return new EC$1(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert$3(Object.prototype.hasOwnProperty.call(curves$1, options), + 'Unknown curve ' + options); + + options = curves$1[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof curves$1.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; + } + var ec = EC$1; + + EC$1.prototype.keyPair = function keyPair(options) { + return new KeyPair$3(this, options); + }; + + EC$1.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair$3.fromPrivate(this, priv, enc); + }; + + EC$1.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair$3.fromPublic(this, pub, enc); + }; + + EC$1.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(2)); + for (;;) { + var priv = new BN$2(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } + }; + + EC$1.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$1.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$2(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$2(1)); + + for (var iter = 0; ; iter++) { + var k = options.k ? + options.k(iter) : + new BN$2(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$2({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC$1.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN$2(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature$2(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$1.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert$3((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature$2(signature, enc); + + var n = this.n; + var e = new BN$2(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$1.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature$2(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'); + }; + + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.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$2(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes$2(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes$2(params.pub); + } + + KeyPair$2.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair$2) + return pub; + return new KeyPair$2(eddsa, { pub: pub }); + }; + + KeyPair$2.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair$2) + return secret; + return new KeyPair$2(eddsa, { secret: secret }); + }; + + KeyPair$2.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty$1(KeyPair$2, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty$1(KeyPair$2, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty$1(KeyPair$2, '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$1(KeyPair$2, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty$1(KeyPair$2, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty$1(KeyPair$2, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair$2.prototype.sign = function sign(message) { + assert$2(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair$2.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair$2.prototype.getSecret = function getSecret(enc) { + assert$2(this._secret, 'KeyPair is public only'); + return utils$3.encode(this.secret(), enc); + }; + + KeyPair$2.prototype.getPublic = function getPublic(enc) { + return utils$3.encode(this.pubBytes(), enc); + }; + + var key = KeyPair$2; + + var BN$1 = bn.exports; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.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$1(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes$1(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }; + } + + assert$1(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN$1) + 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$1, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature$1, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature$1, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature$1, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature$1.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature$1.prototype.toHex = function toHex() { + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + var signature = Signature$1; + + var hash = hash$2; + var curves = curves$2; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; + var KeyPair$1 = key; + var Signature = signature; + + 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; + } + + var eddsa = 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$1.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair$1.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair$1.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$1.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$1.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$1.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + (function (exports) { + + var elliptic = exports; + + elliptic.version = require$$0$1.version; + elliptic.utils = utils$n; + elliptic.rand = brorand.exports; + elliptic.curve = curve; + elliptic.curves = curves$2; + + // Protocols + elliptic.ec = ec; + elliptic.eddsa = eddsa; + }(elliptic)); + + const createHmac = browser$2; + + const ONE1 = Buffer$k.alloc(1, 1); + const ZERO1 = Buffer$k.alloc(1, 0); + + // https://tools.ietf.org/html/rfc6979#section-3.2 + function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { + // Step A, ignored as hash already provided + // Step B + // Step C + let k = Buffer$k.alloc(32, 0); + let v = Buffer$k.alloc(32, 1); + + // Step D + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step E + v = createHmac('sha256', k).update(v).digest(); + + // Step F + k = createHmac('sha256', k) + .update(v) + .update(ONE1) + .update(x) + .update(hash) + .update(extraEntropy || '') + .digest(); + + // Step G + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, ignored as tlen === qlen (256 bit) + // Step H2b + v = createHmac('sha256', k).update(v).digest(); + + let T = v; + + // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA + while (!isPrivate(T) || !checkSig(T)) { + k = createHmac('sha256', k) + .update(v) + .update(ZERO1) + .digest(); + + v = createHmac('sha256', k).update(v).digest(); + + // Step H1/H2a, again, ignored as tlen === qlen (256 bit) + // Step H2b again + v = createHmac('sha256', k).update(v).digest(); + T = v; + } + + return T + } + + var rfc6979 = deterministicGenerateK$1; + + const BN = bn$1.exports; + const EC = elliptic.ec; + const secp256k1 = new EC('secp256k1'); + const deterministicGenerateK = rfc6979; + + const ZERO32 = Buffer$k.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + + const n = secp256k1.curve.n; + const nDiv2 = n.shrn(1); + const G = secp256k1.curve.g; + + const THROW_BAD_PRIVATE = 'Expected Private'; + const THROW_BAD_POINT = 'Expected Point'; + const THROW_BAD_TWEAK = 'Expected Tweak'; + const THROW_BAD_HASH = 'Expected Hash'; + const THROW_BAD_SIGNATURE = 'Expected Signature'; + const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; + + function isScalar (x) { + return isBuffer(x) && x.length === 32 + } + + function isOrderScalar (x) { + if (!isScalar(x)) return false + return x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isPoint (p) { + if (!isBuffer(p)) return false + if (p.length < 33) return false + + const t = p[0]; + const x = p.slice(1, 33); + if (x.compare(ZERO32) === 0) return false + if (x.compare(EC_P) >= 0) return false + if ((t === 0x02 || t === 0x03) && p.length === 33) { + try { decodeFrom(p); } catch (e) { return false } // TODO: temporary + return true + } + + const y = p.slice(33); + if (y.compare(ZERO32) === 0) return false + if (y.compare(EC_P) >= 0) return false + if (t === 0x04 && p.length === 65) return true + return false + } + + function __isPointCompressed (p) { + return p[0] !== 0x04 + } + + function isPointCompressed (p) { + if (!isPoint(p)) return false + return __isPointCompressed(p) + } + + function isPrivate (x) { + if (!isScalar(x)) return false + return x.compare(ZERO32) > 0 && // > 0 + x.compare(EC_GROUP_ORDER) < 0 // < G + } + + function isSignature (value) { + const r = value.slice(0, 32); + const s = value.slice(32, 64); + return isBuffer(value) && value.length === 64 && + r.compare(EC_GROUP_ORDER) < 0 && + s.compare(EC_GROUP_ORDER) < 0 + } + + function assumeCompression (value, pubkey) { + if (value === undefined && pubkey !== undefined) return __isPointCompressed(pubkey) + if (value === undefined) return true + return value + } + + function fromBuffer$1 (d) { return new BN(d) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } + function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } + function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } + + function pointAdd (pA, pB, __compressed) { + if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) + if (!isPoint(pB)) throw new TypeError(THROW_BAD_POINT) + + const a = decodeFrom(pA); + const b = decodeFrom(pB); + const pp = a.add(b); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed, pA); + return getEncoded(pp, compressed) + } + + function pointAddScalar (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + if (tweak.compare(ZERO32) === 0) return getEncoded(pp, compressed) + + const tt = fromBuffer$1(tweak); + const qq = G.mul(tt); + const uu = pp.add(qq); + if (uu.isInfinity()) return null + + return getEncoded(uu, compressed) + } + + function pointCompress (p, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + + const pp = decodeFrom(p); + if (pp.isInfinity()) throw new TypeError(THROW_BAD_POINT) + + const compressed = assumeCompression(__compressed, p); + + return getEncoded(pp, compressed) + } + + function pointFromScalar (d, __compressed) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + + const dd = fromBuffer$1(d); + const pp = G.mul(dd); + if (pp.isInfinity()) return null + + const compressed = assumeCompression(__compressed); + return getEncoded(pp, compressed) + } + + function pointMultiply (p, tweak, __compressed) { + if (!isPoint(p)) throw new TypeError(THROW_BAD_POINT) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const compressed = assumeCompression(__compressed, p); + const pp = decodeFrom(p); + const tt = fromBuffer$1(tweak); + const qq = pp.mul(tt); + if (qq.isInfinity()) return null + + return getEncoded(qq, compressed) + } + + function privateAdd (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.add(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function privateSub (d, tweak) { + if (!isPrivate(d)) throw new TypeError(THROW_BAD_PRIVATE) + if (!isOrderScalar(tweak)) throw new TypeError(THROW_BAD_TWEAK) + + const dd = fromBuffer$1(d); + const tt = fromBuffer$1(tweak); + const dt = toBuffer$1(dd.sub(tt).umod(n)); + if (!isPrivate(dt)) return null + + return dt + } + + function sign (hash, x) { + return __sign(hash, x) + } + + function signWithEntropy (hash, x, addData) { + return __sign(hash, x, addData) + } + + function __sign (hash, x, addData) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPrivate(x)) throw new TypeError(THROW_BAD_PRIVATE) + if (addData !== undefined && !isScalar(addData)) throw new TypeError(THROW_BAD_EXTRA_DATA) + + const d = fromBuffer$1(x); + const e = fromBuffer$1(hash); + + let r, s; + const checkSig = function (k) { + const kI = fromBuffer$1(k); + const Q = G.mul(kI); + + if (Q.isInfinity()) return false + + r = Q.x.umod(n); + if (r.isZero() === 0) return false + + s = kI + .invm(n) + .mul(e.add(d.mul(r))) + .umod(n); + if (s.isZero() === 0) return false + + return true + }; + + deterministicGenerateK(hash, x, checkSig, isPrivate, addData); + + // enforce low S values, see bip62: 'low s values in signatures' + if (s.cmp(nDiv2) > 0) { + s = n.sub(s); + } + + const buffer = Buffer$k.allocUnsafe(64); + toBuffer$1(r).copy(buffer, 0); + toBuffer$1(s).copy(buffer, 32); + return buffer + } + + function verify (hash, q, signature, strict) { + if (!isScalar(hash)) throw new TypeError(THROW_BAD_HASH) + if (!isPoint(q)) throw new TypeError(THROW_BAD_POINT) + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (1, isSignature enforces '< n - 1') + if (!isSignature(signature)) throw new TypeError(THROW_BAD_SIGNATURE) + + const Q = decodeFrom(q); + const r = fromBuffer$1(signature.slice(0, 32)); + const s = fromBuffer$1(signature.slice(32, 64)); + + if (strict && s.cmp(nDiv2) > 0) { + return false + } + + // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] (2, enforces '> 0') + if (r.gtn(0) <= 0 /* || r.compareTo(n) >= 0 */) return false + if (s.gtn(0) <= 0 /* || s.compareTo(n) >= 0 */) return false + + // 1.4.2 H = Hash(M), already done by the user + // 1.4.3 e = H + const e = fromBuffer$1(hash); + + // Compute s^-1 + const sInv = s.invm(n); + + // 1.4.4 Compute u1 = es^−1 mod n + // u2 = rs^−1 mod n + const u1 = e.mul(sInv).umod(n); + const u2 = r.mul(sInv).umod(n); + + // 1.4.5 Compute R = (xR, yR) + // R = u1G + u2Q + const R = G.mulAdd(u1, Q, u2); + + // 1.4.5 (cont.) Enforce R is not at infinity + if (R.isInfinity()) return false + + // 1.4.6 Convert the field element R.x to an integer + const xR = R.x; + + // 1.4.7 Set v = xR mod n + const v = xR.umod(n); + + // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" + return v.eq(r) + } + + var js = { + isPoint, + isPointCompressed, + isPrivate, + pointAdd, + pointAddScalar, + pointCompress, + pointFromScalar, + pointMultiply, + privateAdd, + privateSub, + sign, + signWithEntropy, + verify + }; + + var types$c = { + Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, + Boolean: function (value) { return typeof value === 'boolean' }, + Function: function (value) { return typeof value === 'function' }, + Nil: function (value) { return value === undefined || value === null }, + Number: function (value) { return typeof value === 'number' }, + Object: function (value) { return typeof value === 'object' }, + String: function (value) { return typeof value === 'string' }, + '': function () { return true } + }; + + // TODO: deprecate + types$c.Null = types$c.Nil; + + for (var typeName$2 in types$c) { + types$c[typeName$2].toJSON = function (t) { + return t + }.bind(null, typeName$2); + } + + var native$1 = types$c; + + var native = native$1; + + function getTypeName (fn) { + return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] + } + + function getValueTypeName$1 (value) { + return native.Nil(value) ? '' : getTypeName(value.constructor) + } + + function getValue (value) { + if (native.Function(value)) return '' + if (native.String(value)) return JSON.stringify(value) + if (value && native.Object(value)) return '' + return value + } + + function captureStackTrace (e, t) { + if (Error.captureStackTrace) { + Error.captureStackTrace(e, t); + } + } + + function tfJSON$1 (type) { + if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) + if (native.Array(type)) return 'Array' + if (type && native.Object(type)) return 'Object' + + return type !== undefined ? type : '' + } + + function tfErrorString (type, value, valueTypeName) { + var valueJson = getValue(value); + + return 'Expected ' + tfJSON$1(type) + ', got' + + (valueTypeName !== '' ? ' ' + valueTypeName : '') + + (valueJson !== '' ? ' ' + valueJson : '') + } + + function TfTypeError$1 (type, value, valueTypeName) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfErrorString(type, value, valueTypeName); + + captureStackTrace(this, TfTypeError$1); + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfTypeError$1.prototype = Object.create(Error.prototype); + TfTypeError$1.prototype.constructor = TfTypeError$1; + + function tfPropertyErrorString (type, label, name, value, valueTypeName) { + var description = '" of type '; + if (label === 'key') description = '" with key type '; + + return tfErrorString('property "' + tfJSON$1(name) + description + tfJSON$1(type), value, valueTypeName) + } + + function TfPropertyTypeError$1 (type, property, label, value, valueTypeName) { + if (type) { + valueTypeName = valueTypeName || getValueTypeName$1(value); + this.message = tfPropertyErrorString(type, label, property, value, valueTypeName); + } else { + this.message = 'Unexpected property "' + property + '"'; + } + + captureStackTrace(this, TfTypeError$1); + this.__label = label; + this.__property = property; + this.__type = type; + this.__value = value; + this.__valueTypeName = valueTypeName; + } + + TfPropertyTypeError$1.prototype = Object.create(Error.prototype); + TfPropertyTypeError$1.prototype.constructor = TfTypeError$1; + + function tfCustomError (expected, actual) { + return new TfTypeError$1(expected, {}, actual) + } + + function tfSubError$1 (e, property, label) { + // sub child? + if (e instanceof TfPropertyTypeError$1) { + property = property + '.' + e.__property; + + e = new TfPropertyTypeError$1( + e.__type, property, e.__label, e.__value, e.__valueTypeName + ); + + // child? + } else if (e instanceof TfTypeError$1) { + e = new TfPropertyTypeError$1( + e.__type, property, label, e.__value, e.__valueTypeName + ); + } + + captureStackTrace(e); + return e + } + + var errors = { + TfTypeError: TfTypeError$1, + TfPropertyTypeError: TfPropertyTypeError$1, + tfCustomError: tfCustomError, + tfSubError: tfSubError$1, + tfJSON: tfJSON$1, + getValueTypeName: getValueTypeName$1 + }; + + var NATIVE$1 = native$1; + var ERRORS$1 = errors; + + function _Buffer (value) { + return isBuffer(value) + } + + function Hex (value) { + return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) + } + + function _LengthN (type, length) { + var name = type.toJSON(); + + function Length (value) { + if (!type(value)) return false + if (value.length === length) return true + + throw ERRORS$1.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') + } + Length.toJSON = function () { return name }; + + return Length + } + + var _ArrayN = _LengthN.bind(null, NATIVE$1.Array); + var _BufferN = _LengthN.bind(null, _Buffer); + var _HexN = _LengthN.bind(null, Hex); + var _StringN = _LengthN.bind(null, NATIVE$1.String); + + function Range$b (a, b, f) { + f = f || NATIVE$1.Number; + function _range (value, strict) { + return f(value, strict) && (value > a) && (value < b) + } + _range.toJSON = function () { + return `${f.toJSON()} between [${a}, ${b}]` + }; + return _range + } + + var INT53_MAX = Math.pow(2, 53) - 1; + + function Finite (value) { + return typeof value === 'number' && isFinite(value) + } + function Int8 (value) { return ((value << 24) >> 24) === value } + function Int16 (value) { return ((value << 16) >> 16) === value } + function Int32 (value) { return (value | 0) === value } + function Int53 (value) { + return typeof value === 'number' && + value >= -INT53_MAX && + value <= INT53_MAX && + Math.floor(value) === value + } + function UInt8 (value) { return (value & 0xff) === value } + function UInt16 (value) { return (value & 0xffff) === value } + function UInt32 (value) { return (value >>> 0) === value } + function UInt53 (value) { + return typeof value === 'number' && + value >= 0 && + value <= INT53_MAX && + Math.floor(value) === value + } + + var types$b = { + ArrayN: _ArrayN, + Buffer: _Buffer, + BufferN: _BufferN, + Finite: Finite, + Hex: Hex, + HexN: _HexN, + Int8: Int8, + Int16: Int16, + Int32: Int32, + Int53: Int53, + Range: Range$b, + StringN: _StringN, + UInt8: UInt8, + UInt16: UInt16, + UInt32: UInt32, + UInt53: UInt53 + }; + + for (var typeName$1 in types$b) { + types$b[typeName$1].toJSON = function (t) { + return t + }.bind(null, typeName$1); + } + + var extra = types$b; + + var ERRORS = errors; + var NATIVE = native$1; + + // short-hand + var tfJSON = ERRORS.tfJSON; + var TfTypeError = ERRORS.TfTypeError; + var TfPropertyTypeError = ERRORS.TfPropertyTypeError; + var tfSubError = ERRORS.tfSubError; + var getValueTypeName = ERRORS.getValueTypeName; + + var TYPES = { + arrayOf: function arrayOf (type, options) { + type = compile(type); + options = options || {}; + + function _arrayOf (array, strict) { + if (!NATIVE.Array(array)) return false + if (NATIVE.Nil(array)) return false + if (options.minLength !== undefined && array.length < options.minLength) return false + if (options.maxLength !== undefined && array.length > options.maxLength) return false + if (options.length !== undefined && array.length !== options.length) return false + + return array.every(function (value, i) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _arrayOf.toJSON = function () { + var str = '[' + tfJSON(type) + ']'; + if (options.length !== undefined) { + str += '{' + options.length + '}'; + } else if (options.minLength !== undefined || options.maxLength !== undefined) { + str += '{' + + (options.minLength === undefined ? 0 : options.minLength) + ',' + + (options.maxLength === undefined ? Infinity : options.maxLength) + '}'; + } + return str + }; + + return _arrayOf + }, + + maybe: function maybe (type) { + type = compile(type); + + function _maybe (value, strict) { + return NATIVE.Nil(value) || type(value, strict, maybe) + } + _maybe.toJSON = function () { return '?' + tfJSON(type) }; + + return _maybe + }, + + map: function map (propertyType, propertyKeyType) { + propertyType = compile(propertyType); + if (propertyKeyType) propertyKeyType = compile(propertyKeyType); + + function _map (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + for (var propertyName in value) { + try { + if (propertyKeyType) { + typeforce$b(propertyKeyType, propertyName, strict); + } + } catch (e) { + throw tfSubError(e, propertyName, 'key') + } + + try { + var propertyValue = value[propertyName]; + typeforce$b(propertyType, propertyValue, strict); + } catch (e) { + throw tfSubError(e, propertyName) + } + } + + return true + } + + if (propertyKeyType) { + _map.toJSON = function () { + return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' + }; + } else { + _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }; + } + + return _map + }, + + object: function object (uncompiled) { + var type = {}; + + for (var typePropertyName in uncompiled) { + type[typePropertyName] = compile(uncompiled[typePropertyName]); + } + + function _object (value, strict) { + if (!NATIVE.Object(value)) return false + if (NATIVE.Nil(value)) return false + + var propertyName; + + try { + for (propertyName in type) { + var propertyType = type[propertyName]; + var propertyValue = value[propertyName]; + + typeforce$b(propertyType, propertyValue, strict); + } + } catch (e) { + throw tfSubError(e, propertyName) + } + + if (strict) { + for (propertyName in value) { + if (type[propertyName]) continue + + throw new TfPropertyTypeError(undefined, propertyName) + } + } + + return true + } + _object.toJSON = function () { return tfJSON(type) }; + + return _object + }, + + anyOf: function anyOf () { + var types = [].slice.call(arguments).map(compile); + + function _anyOf (value, strict) { + return types.some(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _anyOf.toJSON = function () { return types.map(tfJSON).join('|') }; + + return _anyOf + }, + + allOf: function allOf () { + var types = [].slice.call(arguments).map(compile); + + function _allOf (value, strict) { + return types.every(function (type) { + try { + return typeforce$b(type, value, strict) + } catch (e) { + return false + } + }) + } + _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') }; + + return _allOf + }, + + quacksLike: function quacksLike (type) { + function _quacksLike (value) { + return type === getValueTypeName(value) + } + _quacksLike.toJSON = function () { return type }; + + return _quacksLike + }, + + tuple: function tuple () { + var types = [].slice.call(arguments).map(compile); + + function _tuple (values, strict) { + if (NATIVE.Nil(values)) return false + if (NATIVE.Nil(values.length)) return false + if (strict && (values.length !== types.length)) return false + + return types.every(function (type, i) { + try { + return typeforce$b(type, values[i], strict) + } catch (e) { + throw tfSubError(e, i) + } + }) + } + _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }; + + return _tuple + }, + + value: function value (expected) { + function _value (actual) { + return actual === expected + } + _value.toJSON = function () { return expected }; + + return _value + } + }; + + // TODO: deprecate + TYPES.oneOf = TYPES.anyOf; + + function compile (type) { + if (NATIVE.String(type)) { + if (type[0] === '?') return TYPES.maybe(type.slice(1)) + + return NATIVE[type] || TYPES.quacksLike(type) + } else if (type && NATIVE.Object(type)) { + if (NATIVE.Array(type)) { + if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') + return TYPES.arrayOf(type[0]) + } + + return TYPES.object(type) + } else if (NATIVE.Function(type)) { + return type + } + + return TYPES.value(type) + } + + function typeforce$b (type, value, strict, surrogate) { + if (NATIVE.Function(type)) { + if (type(value, strict)) return true + + throw new TfTypeError(surrogate || type, value) + } + + // JIT + return typeforce$b(compile(type), value, strict) + } + + // assign types to typeforce function + for (var typeName in NATIVE) { + typeforce$b[typeName] = NATIVE[typeName]; + } + + for (typeName in TYPES) { + typeforce$b[typeName] = TYPES[typeName]; + } + + var EXTRA = extra; + for (typeName in EXTRA) { + typeforce$b[typeName] = EXTRA[typeName]; + } + + typeforce$b.compile = compile; + typeforce$b.TfTypeError = TfTypeError; + typeforce$b.TfPropertyTypeError = TfPropertyTypeError; + + var typeforce_1 = typeforce$b; + + var bs58check$4 = bs58check$5; + + function decodeRaw (buffer, version) { + // check version only if defined + if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') + + // uncompressed + if (buffer.length === 33) { + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: false + } + } + + // invalid length + if (buffer.length !== 34) throw new Error('Invalid WIF length') + + // invalid compression flag + if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') + + return { + version: buffer[0], + privateKey: buffer.slice(1, 33), + compressed: true + } + } + + function encodeRaw (version, privateKey, compressed) { + var result = new Buffer$k(compressed ? 34 : 33); + + result.writeUInt8(version, 0); + privateKey.copy(result, 1); + + if (compressed) { + result[33] = 0x01; + } + + return result + } + + function decode$g (string, version) { + return decodeRaw(bs58check$4.decode(string), version) + } + + function encode$h (version, privateKey, compressed) { + if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) + + return bs58check$4.encode( + encodeRaw( + version.version, + version.privateKey, + version.compressed + ) + ) + } + + var wif$2 = { + decode: decode$g, + decodeRaw: decodeRaw, + encode: encode$h, + encodeRaw: encodeRaw + }; + + Object.defineProperty(bip32$1, "__esModule", { value: true }); + const crypto$3 = crypto$5; + const bs58check$3 = bs58check$5; + const ecc$6 = js; + const typeforce$a = typeforce_1; + const wif$1 = wif$2; + const UINT256_TYPE = typeforce$a.BufferN(32); + const NETWORK_TYPE = typeforce$a.compile({ + wif: typeforce$a.UInt8, + bip32: { + public: typeforce$a.UInt32, + private: typeforce$a.UInt32, + }, + }); + const BITCOIN = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + const HIGHEST_BIT = 0x80000000; + const UINT31_MAX$1 = Math.pow(2, 31) - 1; + function BIP32Path$1(value) { + return (typeforce$a.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) !== null); + } + function UInt31$1(value) { + return typeforce$a.UInt32(value) && value <= UINT31_MAX$1; + } + class BIP32 { + constructor(__D, __Q, chainCode, network, __DEPTH = 0, __INDEX = 0, __PARENT_FINGERPRINT = 0x00000000) { + this.__D = __D; + this.__Q = __Q; + this.chainCode = chainCode; + this.network = network; + this.__DEPTH = __DEPTH; + this.__INDEX = __INDEX; + this.__PARENT_FINGERPRINT = __PARENT_FINGERPRINT; + typeforce$a(NETWORK_TYPE, network); + this.lowR = false; + } + get depth() { + return this.__DEPTH; + } + get index() { + return this.__INDEX; + } + get parentFingerprint() { + return this.__PARENT_FINGERPRINT; + } + get publicKey() { + if (this.__Q === undefined) + this.__Q = ecc$6.pointFromScalar(this.__D, true); + return this.__Q; + } + get privateKey() { + return this.__D; + } + get identifier() { + return crypto$3.hash160(this.publicKey); + } + get fingerprint() { + return this.identifier.slice(0, 4); + } + get compressed() { + return true; + } + // Private === not neutered + // Public === neutered + isNeutered() { + return this.__D === undefined; + } + neutered() { + return fromPublicKeyLocal(this.publicKey, this.chainCode, this.network, this.depth, this.index, this.parentFingerprint); + } + toBase58() { + const network = this.network; + const version = !this.isNeutered() + ? network.bip32.private + : network.bip32.public; + const buffer = Buffer$k.allocUnsafe(78); + // 4 bytes: version bytes + buffer.writeUInt32BE(version, 0); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... + buffer.writeUInt8(this.depth, 4); + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + buffer.writeUInt32BE(this.parentFingerprint, 5); + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in big endian. (0x00000000 if master key) + buffer.writeUInt32BE(this.index, 9); + // 32 bytes: the chain code + this.chainCode.copy(buffer, 13); + // 33 bytes: the public key or private key data + if (!this.isNeutered()) { + // 0x00 + k for private keys + buffer.writeUInt8(0, 45); + this.privateKey.copy(buffer, 46); + // 33 bytes: the public key + } + else { + // X9.62 encoding for public keys + this.publicKey.copy(buffer, 45); + } + return bs58check$3.encode(buffer); + } + toWIF() { + if (!this.privateKey) + throw new TypeError('Missing private key'); + return wif$1.encode(this.network.wif, this.privateKey, true); + } + // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions + derive(index) { + typeforce$a(typeforce$a.UInt32, index); + const isHardened = index >= HIGHEST_BIT; + const data = Buffer$k.allocUnsafe(37); + // Hardened child + if (isHardened) { + if (this.isNeutered()) + throw new TypeError('Missing private key for hardened child key'); + // data = 0x00 || ser256(kpar) || ser32(index) + data[0] = 0x00; + this.privateKey.copy(data, 1); + data.writeUInt32BE(index, 33); + // Normal child + } + else { + // data = serP(point(kpar)) || ser32(index) + // = serP(Kpar) || ser32(index) + this.publicKey.copy(data, 0); + data.writeUInt32BE(index, 33); + } + const I = crypto$3.hmacSHA512(this.chainCode, data); + const IL = I.slice(0, 32); + const IR = I.slice(32); + // if parse256(IL) >= n, proceed with the next value for i + if (!ecc$6.isPrivate(IL)) + return this.derive(index + 1); + // Private parent key -> private child key + let hd; + if (!this.isNeutered()) { + // ki = parse256(IL) + kpar (mod n) + const ki = ecc$6.privateAdd(this.privateKey, IL); + // In case ki == 0, proceed with the next value for i + if (ki == null) + return this.derive(index + 1); + hd = fromPrivateKeyLocal(ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + // Public parent key -> public child key + } + else { + // Ki = point(parse256(IL)) + Kpar + // = G*IL + Kpar + const Ki = ecc$6.pointAddScalar(this.publicKey, IL, true); + // In case Ki is the point at infinity, proceed with the next value for i + if (Ki === null) + return this.derive(index + 1); + hd = fromPublicKeyLocal(Ki, IR, this.network, this.depth + 1, index, this.fingerprint.readUInt32BE(0)); + } + return hd; + } + deriveHardened(index) { + typeforce$a(UInt31$1, index); + // Only derives hardened private keys by default + return this.derive(index + HIGHEST_BIT); + } + derivePath(path) { + typeforce$a(BIP32Path$1, path); + let splitPath = path.split('/'); + if (splitPath[0] === 'm') { + if (this.parentFingerprint) + throw new TypeError('Expected master, got child'); + splitPath = splitPath.slice(1); + } + return splitPath.reduce((prevHd, indexStr) => { + let index; + if (indexStr.slice(-1) === `'`) { + index = parseInt(indexStr.slice(0, -1), 10); + return prevHd.deriveHardened(index); + } + else { + index = parseInt(indexStr, 10); + return prevHd.derive(index); + } + }, this); + } + sign(hash, lowR) { + if (!this.privateKey) + throw new Error('Missing private key'); + if (lowR === undefined) + lowR = this.lowR; + if (lowR === false) { + return ecc$6.sign(hash, this.privateKey); + } + else { + let sig = ecc$6.sign(hash, this.privateKey); + const extraData = Buffer$k.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc$6.signWithEntropy(hash, this.privateKey, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc$6.verify(hash, this.publicKey, signature); + } + } + function fromBase58(inString, network) { + const buffer = bs58check$3.decode(inString); + if (buffer.length !== 78) + throw new TypeError('Invalid buffer length'); + network = network || BITCOIN; + // 4 bytes: version bytes + const version = buffer.readUInt32BE(0); + if (version !== network.bip32.private && version !== network.bip32.public) + throw new TypeError('Invalid network version'); + // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... + const depth = buffer[4]; + // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) + const parentFingerprint = buffer.readUInt32BE(5); + if (depth === 0) { + if (parentFingerprint !== 0x00000000) + throw new TypeError('Invalid parent fingerprint'); + } + // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. + // This is encoded in MSB order. (0x00000000 if master key) + const index = buffer.readUInt32BE(9); + if (depth === 0 && index !== 0) + throw new TypeError('Invalid index'); + // 32 bytes: the chain code + const chainCode = buffer.slice(13, 45); + let hd; + // 33 bytes: private key data (0x00 + k) + if (version === network.bip32.private) { + if (buffer.readUInt8(45) !== 0x00) + throw new TypeError('Invalid private key'); + const k = buffer.slice(46, 78); + hd = fromPrivateKeyLocal(k, chainCode, network, depth, index, parentFingerprint); + // 33 bytes: public key data (0x02 + X or 0x03 + X) + } + else { + const X = buffer.slice(45, 78); + hd = fromPublicKeyLocal(X, chainCode, network, depth, index, parentFingerprint); + } + return hd; + } + bip32$1.fromBase58 = fromBase58; + function fromPrivateKey$1(privateKey, chainCode, network) { + return fromPrivateKeyLocal(privateKey, chainCode, network); + } + bip32$1.fromPrivateKey = fromPrivateKey$1; + function fromPrivateKeyLocal(privateKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + privateKey: UINT256_TYPE, + chainCode: UINT256_TYPE, + }, { privateKey, chainCode }); + network = network || BITCOIN; + if (!ecc$6.isPrivate(privateKey)) + throw new TypeError('Private key not in range [1, n)'); + return new BIP32(privateKey, undefined, chainCode, network, depth, index, parentFingerprint); + } + function fromPublicKey$1(publicKey, chainCode, network) { + return fromPublicKeyLocal(publicKey, chainCode, network); + } + bip32$1.fromPublicKey = fromPublicKey$1; + function fromPublicKeyLocal(publicKey, chainCode, network, depth, index, parentFingerprint) { + typeforce$a({ + publicKey: typeforce$a.BufferN(33), + chainCode: UINT256_TYPE, + }, { publicKey, chainCode }); + network = network || BITCOIN; + // verify the X coordinate is a point on the curve + if (!ecc$6.isPoint(publicKey)) + throw new TypeError('Point is not on the curve'); + return new BIP32(undefined, publicKey, chainCode, network, depth, index, parentFingerprint); + } + function fromSeed(seed, network) { + typeforce$a(typeforce$a.Buffer, seed); + if (seed.length < 16) + throw new TypeError('Seed should be at least 128 bits'); + if (seed.length > 64) + throw new TypeError('Seed should be at most 512 bits'); + network = network || BITCOIN; + const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); + const IL = I.slice(0, 32); + const IR = I.slice(32); + return fromPrivateKey$1(IL, IR, network); + } + bip32$1.fromSeed = fromSeed; + + Object.defineProperty(src, "__esModule", { value: true }); + var bip32_1 = bip32$1; + src.fromSeed = bip32_1.fromSeed; + src.fromBase58 = bip32_1.fromBase58; + src.fromPublicKey = bip32_1.fromPublicKey; + src.fromPrivateKey = bip32_1.fromPrivateKey; + + var address$1 = {}; + + var networks$3 = {}; + + Object.defineProperty(networks$3, '__esModule', { value: true }); + networks$3.bitcoin = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bc', + bip32: { + public: 0x0488b21e, + private: 0x0488ade4, + }, + pubKeyHash: 0x00, + scriptHash: 0x05, + wif: 0x80, + }; + networks$3.regtest = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'bcrt', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + networks$3.testnet = { + messagePrefix: '\x18Bitcoin Signed Message:\n', + bech32: 'tb', + bip32: { + public: 0x043587cf, + private: 0x04358394, + }, + pubKeyHash: 0x6f, + scriptHash: 0xc4, + wif: 0xef, + }; + + var payments$4 = {}; + + var embed = {}; + + var script$1 = {}; + + var script_number = {}; + + Object.defineProperty(script_number, '__esModule', { value: true }); + function decode$f(buffer, maxLength, minimal) { + maxLength = maxLength || 4; + minimal = minimal === undefined ? true : minimal; + const length = buffer.length; + if (length === 0) return 0; + if (length > maxLength) throw new TypeError('Script number overflow'); + if (minimal) { + if ((buffer[length - 1] & 0x7f) === 0) { + if (length <= 1 || (buffer[length - 2] & 0x80) === 0) + throw new Error('Non-minimally encoded script number'); + } + } + // 40-bit + if (length === 5) { + const a = buffer.readUInt32LE(0); + const b = buffer.readUInt8(4); + if (b & 0x80) return -((b & ~0x80) * 0x100000000 + a); + return b * 0x100000000 + a; + } + // 32-bit / 24-bit / 16-bit / 8-bit + let result = 0; + for (let i = 0; i < length; ++i) { + result |= buffer[i] << (8 * i); + } + if (buffer[length - 1] & 0x80) + return -(result & ~(0x80 << (8 * (length - 1)))); + return result; + } + script_number.decode = decode$f; + function scriptNumSize(i) { + return i > 0x7fffffff + ? 5 + : i > 0x7fffff + ? 4 + : i > 0x7fff + ? 3 + : i > 0x7f + ? 2 + : i > 0x00 + ? 1 + : 0; + } + function encode$g(_number) { + let value = Math.abs(_number); + const size = scriptNumSize(value); + const buffer = Buffer$k.allocUnsafe(size); + const negative = _number < 0; + for (let i = 0; i < size; ++i) { + buffer.writeUInt8(value & 0xff, i); + value >>= 8; + } + if (buffer[size - 1] & 0x80) { + buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1); + } else if (negative) { + buffer[size - 1] |= 0x80; + } + return buffer; + } + script_number.encode = encode$g; + + var script_signature = {}; + + var types$a = {}; + + Object.defineProperty(types$a, '__esModule', { value: true }); + const typeforce$9 = typeforce_1; + const UINT31_MAX = Math.pow(2, 31) - 1; + function UInt31(value) { + return typeforce$9.UInt32(value) && value <= UINT31_MAX; + } + types$a.UInt31 = UInt31; + function BIP32Path(value) { + return typeforce$9.String(value) && !!value.match(/^(m\/)?(\d+'?\/)*\d+'?$/); + } + types$a.BIP32Path = BIP32Path; + BIP32Path.toJSON = () => { + return 'BIP32 derivation path'; + }; + function Signer(obj) { + return ( + (typeforce$9.Buffer(obj.publicKey) || + typeof obj.getPublicKey === 'function') && + typeof obj.sign === 'function' + ); + } + types$a.Signer = Signer; + const SATOSHI_MAX = 21 * 1e14; + function Satoshi(value) { + return typeforce$9.UInt53(value) && value <= SATOSHI_MAX; + } + types$a.Satoshi = Satoshi; + // external dependent types + types$a.ECPoint = typeforce$9.quacksLike('Point'); + // exposed, external API + types$a.Network = typeforce$9.compile({ + messagePrefix: typeforce$9.oneOf(typeforce$9.Buffer, typeforce$9.String), + bip32: { + public: typeforce$9.UInt32, + private: typeforce$9.UInt32, + }, + pubKeyHash: typeforce$9.UInt8, + scriptHash: typeforce$9.UInt8, + wif: typeforce$9.UInt8, + }); + types$a.Buffer256bit = typeforce$9.BufferN(32); + types$a.Hash160bit = typeforce$9.BufferN(20); + types$a.Hash256bit = typeforce$9.BufferN(32); + types$a.Number = typeforce$9.Number; // tslint:disable-line variable-name + types$a.Array = typeforce$9.Array; + types$a.Boolean = typeforce$9.Boolean; // tslint:disable-line variable-name + types$a.String = typeforce$9.String; // tslint:disable-line variable-name + types$a.Buffer = typeforce$9.Buffer; + types$a.Hex = typeforce$9.Hex; + types$a.maybe = typeforce$9.maybe; + types$a.tuple = typeforce$9.tuple; + types$a.UInt8 = typeforce$9.UInt8; + types$a.UInt32 = typeforce$9.UInt32; + types$a.Function = typeforce$9.Function; + types$a.BufferN = typeforce$9.BufferN; + types$a.Null = typeforce$9.Null; + types$a.oneOf = typeforce$9.oneOf; + + // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki + // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + // NOTE: SIGHASH byte ignored AND restricted, truncate before use + + var Buffer$2 = safeBuffer.exports.Buffer; + + function check$m (buffer) { + if (buffer.length < 8) return false + if (buffer.length > 72) return false + if (buffer[0] !== 0x30) return false + if (buffer[1] !== buffer.length - 2) return false + if (buffer[2] !== 0x02) return false + + var lenR = buffer[3]; + if (lenR === 0) return false + if (5 + lenR >= buffer.length) return false + if (buffer[4 + lenR] !== 0x02) return false + + var lenS = buffer[5 + lenR]; + if (lenS === 0) return false + if ((6 + lenR + lenS) !== buffer.length) return false + + if (buffer[4] & 0x80) return false + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false + + if (buffer[lenR + 6] & 0x80) return false + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false + return true + } + + function decode$e (buffer) { + if (buffer.length < 8) throw new Error('DER sequence length is too short') + if (buffer.length > 72) throw new Error('DER sequence length is too long') + if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') + if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') + if (buffer[2] !== 0x02) throw new Error('Expected DER integer') + + var lenR = buffer[3]; + if (lenR === 0) throw new Error('R length is zero') + if (5 + lenR >= buffer.length) throw new Error('R length is too long') + if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') + + var lenS = buffer[5 + lenR]; + if (lenS === 0) throw new Error('S length is zero') + if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') + + if (buffer[4] & 0x80) throw new Error('R value is negative') + if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') + + if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') + if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') + + // non-BIP66 - extract R, S values + return { + r: buffer.slice(4, 4 + lenR), + s: buffer.slice(6 + lenR) + } + } + + /* + * Expects r and s to be positive DER integers. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode$f (r, s) { + var lenR = r.length; + var lenS = s.length; + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer$2.allocUnsafe(6 + lenR + lenS); + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30; + signature[1] = signature.length - 2; + signature[2] = 0x02; + signature[3] = r.length; + r.copy(signature, 4); + signature[4 + lenR] = 0x02; + signature[5 + lenR] = s.length; + s.copy(signature, 6 + lenR); + + return signature + } + + var bip66$1 = { + check: check$m, + decode: decode$e, + encode: encode$f + }; + + Object.defineProperty(script_signature, '__esModule', { value: true }); + const types$9 = types$a; + const bip66 = bip66$1; + const typeforce$8 = typeforce_1; + const ZERO$1 = Buffer$k.alloc(1, 0); + function toDER(x) { + let i = 0; + while (x[i] === 0) ++i; + if (i === x.length) return ZERO$1; + x = x.slice(i); + if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); + return x; + } + function fromDER(x) { + if (x[0] === 0x00) x = x.slice(1); + const buffer = Buffer$k.alloc(32, 0); + const bstart = Math.max(0, 32 - x.length); + x.copy(buffer, bstart); + return buffer; + } + // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) + function decode$d(buffer) { + const hashType = buffer.readUInt8(buffer.length - 1); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const decoded = bip66.decode(buffer.slice(0, -1)); + const r = fromDER(decoded.r); + const s = fromDER(decoded.s); + const signature = Buffer$k.concat([r, s], 64); + return { signature, hashType }; + } + script_signature.decode = decode$d; + function encode$e(signature, hashType) { + typeforce$8( + { + signature: types$9.BufferN(64), + hashType: types$9.UInt8, + }, + { signature, hashType }, + ); + const hashTypeMod = hashType & ~0x80; + if (hashTypeMod <= 0 || hashTypeMod >= 4) + throw new Error('Invalid hashType ' + hashType); + const hashTypeBuffer = Buffer$k.allocUnsafe(1); + hashTypeBuffer.writeUInt8(hashType, 0); + const r = toDER(signature.slice(0, 32)); + const s = toDER(signature.slice(32, 64)); + return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); + } + script_signature.encode = encode$e; + + var OP_FALSE = 0; + var OP_0 = 0; + var OP_PUSHDATA1 = 76; + var OP_PUSHDATA2 = 77; + var OP_PUSHDATA4 = 78; + var OP_1NEGATE = 79; + var OP_RESERVED = 80; + var OP_TRUE = 81; + var OP_1 = 81; + var OP_2 = 82; + var OP_3 = 83; + var OP_4 = 84; + var OP_5 = 85; + var OP_6 = 86; + var OP_7 = 87; + var OP_8 = 88; + var OP_9 = 89; + var OP_10 = 90; + var OP_11 = 91; + var OP_12 = 92; + var OP_13 = 93; + var OP_14 = 94; + var OP_15 = 95; + var OP_16 = 96; + var OP_NOP = 97; + var OP_VER = 98; + var OP_IF = 99; + var OP_NOTIF = 100; + var OP_VERIF = 101; + var OP_VERNOTIF = 102; + var OP_ELSE = 103; + var OP_ENDIF = 104; + var OP_VERIFY = 105; + var OP_RETURN = 106; + var OP_TOALTSTACK = 107; + var OP_FROMALTSTACK = 108; + var OP_2DROP = 109; + var OP_2DUP = 110; + var OP_3DUP = 111; + var OP_2OVER = 112; + var OP_2ROT = 113; + var OP_2SWAP = 114; + var OP_IFDUP = 115; + var OP_DEPTH = 116; + var OP_DROP = 117; + var OP_DUP$1 = 118; + var OP_NIP = 119; + var OP_OVER = 120; + var OP_PICK = 121; + var OP_ROLL = 122; + var OP_ROT = 123; + var OP_SWAP = 124; + var OP_TUCK = 125; + var OP_CAT = 126; + var OP_SUBSTR = 127; + var OP_LEFT = 128; + var OP_RIGHT = 129; + var OP_SIZE = 130; + var OP_INVERT = 131; + var OP_AND = 132; + var OP_OR = 133; + var OP_XOR = 134; + var OP_EQUAL$1 = 135; + var OP_EQUALVERIFY$1 = 136; + var OP_RESERVED1 = 137; + var OP_RESERVED2 = 138; + var OP_1ADD = 139; + var OP_1SUB = 140; + var OP_2MUL = 141; + var OP_2DIV = 142; + var OP_NEGATE = 143; + var OP_ABS = 144; + var OP_NOT = 145; + var OP_0NOTEQUAL = 146; + var OP_ADD = 147; + var OP_SUB = 148; + var OP_MUL = 149; + var OP_DIV = 150; + var OP_MOD = 151; + var OP_LSHIFT = 152; + var OP_RSHIFT = 153; + var OP_BOOLAND = 154; + var OP_BOOLOR = 155; + var OP_NUMEQUAL = 156; + var OP_NUMEQUALVERIFY = 157; + var OP_NUMNOTEQUAL = 158; + var OP_LESSTHAN = 159; + var OP_GREATERTHAN = 160; + var OP_LESSTHANOREQUAL = 161; + var OP_GREATERTHANOREQUAL = 162; + var OP_MIN = 163; + var OP_MAX = 164; + var OP_WITHIN = 165; + var OP_RIPEMD160 = 166; + var OP_SHA1 = 167; + var OP_SHA256 = 168; + var OP_HASH160$1 = 169; + var OP_HASH256 = 170; + var OP_CODESEPARATOR = 171; + var OP_CHECKSIG$1 = 172; + var OP_CHECKSIGVERIFY = 173; + var OP_CHECKMULTISIG = 174; + var OP_CHECKMULTISIGVERIFY = 175; + var OP_NOP1 = 176; + var OP_NOP2 = 177; + var OP_CHECKLOCKTIMEVERIFY = 177; + var OP_NOP3 = 178; + var OP_CHECKSEQUENCEVERIFY = 178; + var OP_NOP4 = 179; + var OP_NOP5 = 180; + var OP_NOP6 = 181; + var OP_NOP7 = 182; + var OP_NOP8 = 183; + var OP_NOP9 = 184; + var OP_NOP10 = 185; + var OP_PUBKEYHASH = 253; + var OP_PUBKEY = 254; + var OP_INVALIDOPCODE = 255; + var require$$7 = { + OP_FALSE: OP_FALSE, + OP_0: OP_0, + OP_PUSHDATA1: OP_PUSHDATA1, + OP_PUSHDATA2: OP_PUSHDATA2, + OP_PUSHDATA4: OP_PUSHDATA4, + OP_1NEGATE: OP_1NEGATE, + OP_RESERVED: OP_RESERVED, + OP_TRUE: OP_TRUE, + OP_1: OP_1, + OP_2: OP_2, + OP_3: OP_3, + OP_4: OP_4, + OP_5: OP_5, + OP_6: OP_6, + OP_7: OP_7, + OP_8: OP_8, + OP_9: OP_9, + OP_10: OP_10, + OP_11: OP_11, + OP_12: OP_12, + OP_13: OP_13, + OP_14: OP_14, + OP_15: OP_15, + OP_16: OP_16, + OP_NOP: OP_NOP, + OP_VER: OP_VER, + OP_IF: OP_IF, + OP_NOTIF: OP_NOTIF, + OP_VERIF: OP_VERIF, + OP_VERNOTIF: OP_VERNOTIF, + OP_ELSE: OP_ELSE, + OP_ENDIF: OP_ENDIF, + OP_VERIFY: OP_VERIFY, + OP_RETURN: OP_RETURN, + OP_TOALTSTACK: OP_TOALTSTACK, + OP_FROMALTSTACK: OP_FROMALTSTACK, + OP_2DROP: OP_2DROP, + OP_2DUP: OP_2DUP, + OP_3DUP: OP_3DUP, + OP_2OVER: OP_2OVER, + OP_2ROT: OP_2ROT, + OP_2SWAP: OP_2SWAP, + OP_IFDUP: OP_IFDUP, + OP_DEPTH: OP_DEPTH, + OP_DROP: OP_DROP, + OP_DUP: OP_DUP$1, + OP_NIP: OP_NIP, + OP_OVER: OP_OVER, + OP_PICK: OP_PICK, + OP_ROLL: OP_ROLL, + OP_ROT: OP_ROT, + OP_SWAP: OP_SWAP, + OP_TUCK: OP_TUCK, + OP_CAT: OP_CAT, + OP_SUBSTR: OP_SUBSTR, + OP_LEFT: OP_LEFT, + OP_RIGHT: OP_RIGHT, + OP_SIZE: OP_SIZE, + OP_INVERT: OP_INVERT, + OP_AND: OP_AND, + OP_OR: OP_OR, + OP_XOR: OP_XOR, + OP_EQUAL: OP_EQUAL$1, + OP_EQUALVERIFY: OP_EQUALVERIFY$1, + OP_RESERVED1: OP_RESERVED1, + OP_RESERVED2: OP_RESERVED2, + OP_1ADD: OP_1ADD, + OP_1SUB: OP_1SUB, + OP_2MUL: OP_2MUL, + OP_2DIV: OP_2DIV, + OP_NEGATE: OP_NEGATE, + OP_ABS: OP_ABS, + OP_NOT: OP_NOT, + OP_0NOTEQUAL: OP_0NOTEQUAL, + OP_ADD: OP_ADD, + OP_SUB: OP_SUB, + OP_MUL: OP_MUL, + OP_DIV: OP_DIV, + OP_MOD: OP_MOD, + OP_LSHIFT: OP_LSHIFT, + OP_RSHIFT: OP_RSHIFT, + OP_BOOLAND: OP_BOOLAND, + OP_BOOLOR: OP_BOOLOR, + OP_NUMEQUAL: OP_NUMEQUAL, + OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY, + OP_NUMNOTEQUAL: OP_NUMNOTEQUAL, + OP_LESSTHAN: OP_LESSTHAN, + OP_GREATERTHAN: OP_GREATERTHAN, + OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL, + OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL, + OP_MIN: OP_MIN, + OP_MAX: OP_MAX, + OP_WITHIN: OP_WITHIN, + OP_RIPEMD160: OP_RIPEMD160, + OP_SHA1: OP_SHA1, + OP_SHA256: OP_SHA256, + OP_HASH160: OP_HASH160$1, + OP_HASH256: OP_HASH256, + OP_CODESEPARATOR: OP_CODESEPARATOR, + OP_CHECKSIG: OP_CHECKSIG$1, + OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY, + OP_CHECKMULTISIG: OP_CHECKMULTISIG, + OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY, + OP_NOP1: OP_NOP1, + OP_NOP2: OP_NOP2, + OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY, + OP_NOP3: OP_NOP3, + OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY, + OP_NOP4: OP_NOP4, + OP_NOP5: OP_NOP5, + OP_NOP6: OP_NOP6, + OP_NOP7: OP_NOP7, + OP_NOP8: OP_NOP8, + OP_NOP9: OP_NOP9, + OP_NOP10: OP_NOP10, + OP_PUBKEYHASH: OP_PUBKEYHASH, + OP_PUBKEY: OP_PUBKEY, + OP_INVALIDOPCODE: OP_INVALIDOPCODE + }; + + var OPS$9 = require$$7; + + function encodingLength$2 (i) { + return i < OPS$9.OP_PUSHDATA1 ? 1 + : i <= 0xff ? 2 + : i <= 0xffff ? 3 + : 5 + } + + function encode$d (buffer, number, offset) { + var size = encodingLength$2(number); + + // ~6 bit + if (size === 1) { + buffer.writeUInt8(number, offset); + + // 8 bit + } else if (size === 2) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA1, offset); + buffer.writeUInt8(number, offset + 1); + + // 16 bit + } else if (size === 3) { + buffer.writeUInt8(OPS$9.OP_PUSHDATA2, offset); + buffer.writeUInt16LE(number, offset + 1); + + // 32 bit + } else { + buffer.writeUInt8(OPS$9.OP_PUSHDATA4, offset); + buffer.writeUInt32LE(number, offset + 1); + } + + return size + } + + function decode$c (buffer, offset) { + var opcode = buffer.readUInt8(offset); + var number, size; + + // ~6 bit + if (opcode < OPS$9.OP_PUSHDATA1) { + number = opcode; + size = 1; + + // 8 bit + } else if (opcode === OPS$9.OP_PUSHDATA1) { + if (offset + 2 > buffer.length) return null + number = buffer.readUInt8(offset + 1); + size = 2; + + // 16 bit + } else if (opcode === OPS$9.OP_PUSHDATA2) { + if (offset + 3 > buffer.length) return null + number = buffer.readUInt16LE(offset + 1); + size = 3; + + // 32 bit + } else { + if (offset + 5 > buffer.length) return null + if (opcode !== OPS$9.OP_PUSHDATA4) throw new Error('Unexpected opcode') + + number = buffer.readUInt32LE(offset + 1); + size = 5; + } + + return { + opcode: opcode, + number: number, + size: size + } + } + + var pushdataBitcoin = { + encodingLength: encodingLength$2, + encode: encode$d, + decode: decode$c + }; + + var OPS$8 = require$$7; + + var map = {}; + for (var op in OPS$8) { + var code = OPS$8[op]; + map[code] = op; + } + + var map_1 = map; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const scriptNumber = script_number; + const scriptSignature = script_signature; + const types = types$a; + const bip66 = bip66$1; + const ecc = js; + const pushdata = pushdataBitcoin; + const typeforce = typeforce_1; + exports.OPS = require$$7; + const REVERSE_OPS = map_1; + const OP_INT_BASE = exports.OPS.OP_RESERVED; // OP_1 - 1 + function isOPInt(value) { + return ( + types.Number(value) && + (value === exports.OPS.OP_0 || + (value >= exports.OPS.OP_1 && value <= exports.OPS.OP_16) || + value === exports.OPS.OP_1NEGATE) + ); + } + function isPushOnlyChunk(value) { + return types.Buffer(value) || isOPInt(value); + } + function isPushOnly(value) { + return types.Array(value) && value.every(isPushOnlyChunk); + } + exports.isPushOnly = isPushOnly; + function asMinimalOP(buffer) { + if (buffer.length === 0) return exports.OPS.OP_0; + if (buffer.length !== 1) return; + if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]; + if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; + } + function chunksIsBuffer(buf) { + return isBuffer(buf); + } + function chunksIsArray(buf) { + return types.Array(buf); + } + function singleChunkIsBuffer(buf) { + return isBuffer(buf); + } + function compile(chunks) { + // TODO: remove me + if (chunksIsBuffer(chunks)) return chunks; + typeforce(types.Array, chunks); + const bufferSize = chunks.reduce((accum, chunk) => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { + return accum + 1; + } + return accum + pushdata.encodingLength(chunk.length) + chunk.length; + } + // opcode + return accum + 1; + }, 0.0); + const buffer = Buffer$k.allocUnsafe(bufferSize); + let offset = 0; + chunks.forEach(chunk => { + // data chunk + if (singleChunkIsBuffer(chunk)) { + // adhere to BIP62.3, minimal push policy + const opcode = asMinimalOP(chunk); + if (opcode !== undefined) { + buffer.writeUInt8(opcode, offset); + offset += 1; + return; + } + offset += pushdata.encode(buffer, chunk.length, offset); + chunk.copy(buffer, offset); + offset += chunk.length; + // opcode + } else { + buffer.writeUInt8(chunk, offset); + offset += 1; + } + }); + if (offset !== buffer.length) throw new Error('Could not decode chunks'); + return buffer; + } + exports.compile = compile; + function decompile(buffer) { + // TODO: remove me + if (chunksIsArray(buffer)) return buffer; + typeforce(types.Buffer, buffer); + const chunks = []; + let i = 0; + while (i < buffer.length) { + const opcode = buffer[i]; + // data chunk + if (opcode > exports.OPS.OP_0 && opcode <= exports.OPS.OP_PUSHDATA4) { + const d = pushdata.decode(buffer, i); + // did reading a pushDataInt fail? + if (d === null) return null; + i += d.size; + // attempt to read too much data? + if (i + d.number > buffer.length) return null; + const data = buffer.slice(i, i + d.number); + i += d.number; + // decompile minimally + const op = asMinimalOP(data); + if (op !== undefined) { + chunks.push(op); + } else { + chunks.push(data); + } + // opcode + } else { + chunks.push(opcode); + i += 1; + } + } + return chunks; + } + exports.decompile = decompile; + function toASM(chunks) { + if (chunksIsBuffer(chunks)) { + chunks = decompile(chunks); + } + return chunks + .map(chunk => { + // data? + if (singleChunkIsBuffer(chunk)) { + const op = asMinimalOP(chunk); + if (op === undefined) return chunk.toString('hex'); + chunk = op; + } + // opcode! + return REVERSE_OPS[chunk]; + }) + .join(' '); + } + exports.toASM = toASM; + function fromASM(asm) { + typeforce(types.String, asm); + return compile( + asm.split(' ').map(chunkStr => { + // opcode? + if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; + typeforce(types.Hex, chunkStr); + // data! + return Buffer$k.from(chunkStr, 'hex'); + }), + ); + } + exports.fromASM = fromASM; + function toStack(chunks) { + chunks = decompile(chunks); + typeforce(isPushOnly, chunks); + return chunks.map(op => { + if (singleChunkIsBuffer(op)) return op; + if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); + return scriptNumber.encode(op - OP_INT_BASE); + }); + } + exports.toStack = toStack; + function isCanonicalPubKey(buffer) { + return ecc.isPoint(buffer); + } + exports.isCanonicalPubKey = isCanonicalPubKey; + function isDefinedHashType(hashType) { + const hashTypeMod = hashType & ~0x80; + // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE + return hashTypeMod > 0x00 && hashTypeMod < 0x04; + } + exports.isDefinedHashType = isDefinedHashType; + function isCanonicalScriptSignature(buffer) { + if (!isBuffer(buffer)) return false; + if (!isDefinedHashType(buffer[buffer.length - 1])) return false; + return bip66.check(buffer.slice(0, -1)); + } + exports.isCanonicalScriptSignature = isCanonicalScriptSignature; + // tslint:disable-next-line variable-name + exports.number = scriptNumber; + exports.signature = scriptSignature; + }(script$1)); + + var lazy$7 = {}; + + Object.defineProperty(lazy$7, '__esModule', { value: true }); + function prop(object, name, f) { + Object.defineProperty(object, name, { + configurable: true, + enumerable: true, + get() { + const _value = f.call(this); + this[name] = _value; + return _value; + }, + set(_value) { + Object.defineProperty(this, name, { + configurable: true, + enumerable: true, + value: _value, + writable: true, + }); + }, + }); + } + lazy$7.prop = prop; + function value(f) { + let _value; + return () => { + if (_value !== undefined) return _value; + _value = f(); + return _value; + }; + } + lazy$7.value = value; + + Object.defineProperty(embed, '__esModule', { value: true }); + const networks_1$7 = networks$3; + const bscript$o = script$1; + const lazy$6 = lazy$7; + const typef$6 = typeforce_1; + const OPS$7 = bscript$o.OPS; + function stacksEqual$3(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // output: OP_RETURN ... + function p2data(a, opts) { + if (!a.data && !a.output) throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$6( + { + network: typef$6.maybe(typef$6.Object), + output: typef$6.maybe(typef$6.Buffer), + data: typef$6.maybe(typef$6.arrayOf(typef$6.Buffer)), + }, + a, + ); + const network = a.network || networks_1$7.bitcoin; + const o = { name: 'embed', network }; + lazy$6.prop(o, 'output', () => { + if (!a.data) return; + return bscript$o.compile([OPS$7.OP_RETURN].concat(a.data)); + }); + lazy$6.prop(o, 'data', () => { + if (!a.output) return; + return bscript$o.decompile(a.output).slice(1); + }); + // extended validation + if (opts.validate) { + if (a.output) { + const chunks = bscript$o.decompile(a.output); + if (chunks[0] !== OPS$7.OP_RETURN) throw new TypeError('Output is invalid'); + if (!chunks.slice(1).every(typef$6.Buffer)) + throw new TypeError('Output is invalid'); + if (a.data && !stacksEqual$3(a.data, o.data)) + throw new TypeError('Data mismatch'); + } + } + return Object.assign(o, a); + } + embed.p2data = p2data; + + var p2ms$3 = {}; + + Object.defineProperty(p2ms$3, '__esModule', { value: true }); + const networks_1$6 = networks$3; + const bscript$n = script$1; + const lazy$5 = lazy$7; + const OPS$6 = bscript$n.OPS; + const typef$5 = typeforce_1; + const ecc$5 = js; + const OP_INT_BASE$1 = OPS$6.OP_RESERVED; // OP_1 - 1 + function stacksEqual$2(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: OP_0 [signatures ...] + // output: m [pubKeys ...] n OP_CHECKMULTISIG + function p2ms$2(a, opts) { + if ( + !a.input && + !a.output && + !(a.pubkeys && a.m !== undefined) && + !a.signatures + ) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + function isAcceptableSignature(x) { + return ( + bscript$n.isCanonicalScriptSignature(x) || + (opts.allowIncomplete && x === OPS$6.OP_0) !== undefined + ); + } + typef$5( + { + network: typef$5.maybe(typef$5.Object), + m: typef$5.maybe(typef$5.Number), + n: typef$5.maybe(typef$5.Number), + output: typef$5.maybe(typef$5.Buffer), + pubkeys: typef$5.maybe(typef$5.arrayOf(ecc$5.isPoint)), + signatures: typef$5.maybe(typef$5.arrayOf(isAcceptableSignature)), + input: typef$5.maybe(typef$5.Buffer), + }, + a, + ); + const network = a.network || networks_1$6.bitcoin; + const o = { network }; + let chunks = []; + let decoded = false; + function decode(output) { + if (decoded) return; + decoded = true; + chunks = bscript$n.decompile(output); + o.m = chunks[0] - OP_INT_BASE$1; + o.n = chunks[chunks.length - 2] - OP_INT_BASE$1; + o.pubkeys = chunks.slice(1, -2); + } + lazy$5.prop(o, 'output', () => { + if (!a.m) return; + if (!o.n) return; + if (!a.pubkeys) return; + return bscript$n.compile( + [].concat( + OP_INT_BASE$1 + a.m, + a.pubkeys, + OP_INT_BASE$1 + o.n, + OPS$6.OP_CHECKMULTISIG, + ), + ); + }); + lazy$5.prop(o, 'm', () => { + if (!o.output) return; + decode(o.output); + return o.m; + }); + lazy$5.prop(o, 'n', () => { + if (!o.pubkeys) return; + return o.pubkeys.length; + }); + lazy$5.prop(o, 'pubkeys', () => { + if (!a.output) return; + decode(a.output); + return o.pubkeys; + }); + lazy$5.prop(o, 'signatures', () => { + if (!a.input) return; + return bscript$n.decompile(a.input).slice(1); + }); + lazy$5.prop(o, 'input', () => { + if (!a.signatures) return; + return bscript$n.compile([OPS$6.OP_0].concat(a.signatures)); + }); + lazy$5.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + lazy$5.prop(o, 'name', () => { + if (!o.m || !o.n) return; + return `p2ms(${o.m} of ${o.n})`; + }); + // extended validation + if (opts.validate) { + if (a.output) { + decode(a.output); + if (!typef$5.Number(chunks[0])) throw new TypeError('Output is invalid'); + if (!typef$5.Number(chunks[chunks.length - 2])) + throw new TypeError('Output is invalid'); + if (chunks[chunks.length - 1] !== OPS$6.OP_CHECKMULTISIG) + throw new TypeError('Output is invalid'); + if (o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) + throw new TypeError('Output is invalid'); + if (!o.pubkeys.every(x => ecc$5.isPoint(x))) + throw new TypeError('Output is invalid'); + if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch'); + if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch'); + if (a.pubkeys && !stacksEqual$2(a.pubkeys, o.pubkeys)) + throw new TypeError('Pubkeys mismatch'); + } + if (a.pubkeys) { + if (a.n !== undefined && a.n !== a.pubkeys.length) + throw new TypeError('Pubkey count mismatch'); + o.n = a.pubkeys.length; + if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m'); + } + if (a.signatures) { + if (a.signatures.length < o.m) + throw new TypeError('Not enough signatures provided'); + if (a.signatures.length > o.m) + throw new TypeError('Too many signatures provided'); + } + if (a.input) { + if (a.input[0] !== OPS$6.OP_0) throw new TypeError('Input is invalid'); + if ( + o.signatures.length === 0 || + !o.signatures.every(isAcceptableSignature) + ) + throw new TypeError('Input has invalid signature(s)'); + if (a.signatures && !stacksEqual$2(a.signatures, o.signatures)) + throw new TypeError('Signature mismatch'); + if (a.m !== undefined && a.m !== a.signatures.length) + throw new TypeError('Signature count mismatch'); + } + } + return Object.assign(o, a); + } + p2ms$3.p2ms = p2ms$2; + + var p2pk$3 = {}; + + Object.defineProperty(p2pk$3, '__esModule', { value: true }); + const networks_1$5 = networks$3; + const bscript$m = script$1; + const lazy$4 = lazy$7; + const typef$4 = typeforce_1; + const OPS$5 = bscript$m.OPS; + const ecc$4 = js; + // input: {signature} + // output: {pubKey} OP_CHECKSIG + function p2pk$2(a, opts) { + if (!a.input && !a.output && !a.pubkey && !a.input && !a.signature) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$4( + { + network: typef$4.maybe(typef$4.Object), + output: typef$4.maybe(typef$4.Buffer), + pubkey: typef$4.maybe(ecc$4.isPoint), + signature: typef$4.maybe(bscript$m.isCanonicalScriptSignature), + input: typef$4.maybe(typef$4.Buffer), + }, + a, + ); + const _chunks = lazy$4.value(() => { + return bscript$m.decompile(a.input); + }); + const network = a.network || networks_1$5.bitcoin; + const o = { name: 'p2pk', network }; + lazy$4.prop(o, 'output', () => { + if (!a.pubkey) return; + return bscript$m.compile([a.pubkey, OPS$5.OP_CHECKSIG]); + }); + lazy$4.prop(o, 'pubkey', () => { + if (!a.output) return; + return a.output.slice(1, -1); + }); + lazy$4.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$4.prop(o, 'input', () => { + if (!a.signature) return; + return bscript$m.compile([a.signature]); + }); + lazy$4.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + if (a.output) { + if (a.output[a.output.length - 1] !== OPS$5.OP_CHECKSIG) + throw new TypeError('Output is invalid'); + if (!ecc$4.isPoint(o.pubkey)) + throw new TypeError('Output pubkey is invalid'); + if (a.pubkey && !a.pubkey.equals(o.pubkey)) + throw new TypeError('Pubkey mismatch'); + } + if (a.signature) { + if (a.input && !a.input.equals(o.input)) + throw new TypeError('Signature mismatch'); + } + if (a.input) { + if (_chunks().length !== 1) throw new TypeError('Input is invalid'); + if (!bscript$m.isCanonicalScriptSignature(o.signature)) + throw new TypeError('Input has invalid signature'); + } + } + return Object.assign(o, a); + } + p2pk$3.p2pk = p2pk$2; + + var p2pkh$4 = {}; + + var crypto$2 = {}; + + Object.defineProperty(crypto$2, '__esModule', { value: true }); + const createHash = browser$3; + function ripemd160$1(buffer) { + try { + return createHash('rmd160') + .update(buffer) + .digest(); + } catch (err) { + return createHash('ripemd160') + .update(buffer) + .digest(); + } + } + crypto$2.ripemd160 = ripemd160$1; + function sha1(buffer) { + return createHash('sha1') + .update(buffer) + .digest(); + } + crypto$2.sha1 = sha1; + function sha256$1(buffer) { + return createHash('sha256') + .update(buffer) + .digest(); + } + crypto$2.sha256 = sha256$1; + function hash160$1(buffer) { + return ripemd160$1(sha256$1(buffer)); + } + crypto$2.hash160 = hash160$1; + function hash256$1(buffer) { + return sha256$1(sha256$1(buffer)); + } + crypto$2.hash256 = hash256$1; + + Object.defineProperty(p2pkh$4, '__esModule', { value: true }); + const bcrypto$6 = crypto$2; + const networks_1$4 = networks$3; + const bscript$l = script$1; + const lazy$3 = lazy$7; + const typef$3 = typeforce_1; + const OPS$4 = bscript$l.OPS; + const ecc$3 = js; + const bs58check$2 = bs58check$5; + // input: {signature} {pubkey} + // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG + function p2pkh$3(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$3( + { + network: typef$3.maybe(typef$3.Object), + address: typef$3.maybe(typef$3.String), + hash: typef$3.maybe(typef$3.BufferN(20)), + output: typef$3.maybe(typef$3.BufferN(25)), + pubkey: typef$3.maybe(ecc$3.isPoint), + signature: typef$3.maybe(bscript$l.isCanonicalScriptSignature), + input: typef$3.maybe(typef$3.Buffer), + }, + a, + ); + const _address = lazy$3.value(() => { + const payload = bs58check$2.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$3.value(() => { + return bscript$l.decompile(a.input); + }); + const network = a.network || networks_1$4.bitcoin; + const o = { name: 'p2pkh', network }; + lazy$3.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(network.pubKeyHash, 0); + o.hash.copy(payload, 1); + return bs58check$2.encode(payload); + }); + lazy$3.prop(o, 'hash', () => { + if (a.output) return a.output.slice(3, 23); + if (a.address) return _address().hash; + if (a.pubkey || o.pubkey) return bcrypto$6.hash160(a.pubkey || o.pubkey); + }); + lazy$3.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$l.compile([ + OPS$4.OP_DUP, + OPS$4.OP_HASH160, + o.hash, + OPS$4.OP_EQUALVERIFY, + OPS$4.OP_CHECKSIG, + ]); + }); + lazy$3.prop(o, 'pubkey', () => { + if (!a.input) return; + return _chunks()[1]; + }); + lazy$3.prop(o, 'signature', () => { + if (!a.input) return; + return _chunks()[0]; + }); + lazy$3.prop(o, 'input', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return bscript$l.compile([a.signature, a.pubkey]); + }); + lazy$3.prop(o, 'witness', () => { + if (!o.input) return; + return []; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().version !== network.pubKeyHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 25 || + a.output[0] !== OPS$4.OP_DUP || + a.output[1] !== OPS$4.OP_HASH160 || + a.output[2] !== 0x14 || + a.output[23] !== OPS$4.OP_EQUALVERIFY || + a.output[24] !== OPS$4.OP_CHECKSIG + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(3, 23); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.pubkey) { + const pkh = bcrypto$6.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + } + if (a.input) { + const chunks = _chunks(); + if (chunks.length !== 2) throw new TypeError('Input is invalid'); + if (!bscript$l.isCanonicalScriptSignature(chunks[0])) + throw new TypeError('Input has invalid signature'); + if (!ecc$3.isPoint(chunks[1])) + throw new TypeError('Input has invalid pubkey'); + if (a.signature && !a.signature.equals(chunks[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(chunks[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$6.hash160(chunks[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2pkh$4.p2pkh = p2pkh$3; + + var p2sh$1 = {}; + + Object.defineProperty(p2sh$1, '__esModule', { value: true }); + const bcrypto$5 = crypto$2; + const networks_1$3 = networks$3; + const bscript$k = script$1; + const lazy$2 = lazy$7; + const typef$2 = typeforce_1; + const OPS$3 = bscript$k.OPS; + const bs58check$1 = bs58check$5; + function stacksEqual$1(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + // input: [redeemScriptSig ...] {redeemScript} + // witness: + // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL + function p2sh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.input) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$2( + { + network: typef$2.maybe(typef$2.Object), + address: typef$2.maybe(typef$2.String), + hash: typef$2.maybe(typef$2.BufferN(20)), + output: typef$2.maybe(typef$2.BufferN(23)), + redeem: typef$2.maybe({ + network: typef$2.maybe(typef$2.Object), + output: typef$2.maybe(typef$2.Buffer), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }), + input: typef$2.maybe(typef$2.Buffer), + witness: typef$2.maybe(typef$2.arrayOf(typef$2.Buffer)), + }, + a, + ); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$3.bitcoin; + } + const o = { network }; + const _address = lazy$2.value(() => { + const payload = bs58check$1.decode(a.address); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + }); + const _chunks = lazy$2.value(() => { + return bscript$k.decompile(a.input); + }); + const _redeem = lazy$2.value(() => { + const chunks = _chunks(); + return { + network, + output: chunks[chunks.length - 1], + input: bscript$k.compile(chunks.slice(0, -1)), + witness: a.witness || [], + }; + }); + // output dependents + lazy$2.prop(o, 'address', () => { + if (!o.hash) return; + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(o.network.scriptHash, 0); + o.hash.copy(payload, 1); + return bs58check$1.encode(payload); + }); + lazy$2.prop(o, 'hash', () => { + // in order of least effort + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().hash; + if (o.redeem && o.redeem.output) return bcrypto$5.hash160(o.redeem.output); + }); + lazy$2.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$k.compile([OPS$3.OP_HASH160, o.hash, OPS$3.OP_EQUAL]); + }); + // input dependents + lazy$2.prop(o, 'redeem', () => { + if (!a.input) return; + return _redeem(); + }); + lazy$2.prop(o, 'input', () => { + if (!a.redeem || !a.redeem.input || !a.redeem.output) return; + return bscript$k.compile( + [].concat(bscript$k.decompile(a.redeem.input), a.redeem.output), + ); + }); + lazy$2.prop(o, 'witness', () => { + if (o.redeem && o.redeem.witness) return o.redeem.witness; + if (o.input) return []; + }); + lazy$2.prop(o, 'name', () => { + const nameParts = ['p2sh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().version !== network.scriptHash) + throw new TypeError('Invalid version or Network mismatch'); + if (_address().hash.length !== 20) throw new TypeError('Invalid address'); + hash = _address().hash; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 23 || + a.output[0] !== OPS$3.OP_HASH160 || + a.output[1] !== 0x14 || + a.output[22] !== OPS$3.OP_EQUAL + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2, 22); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + // inlined to prevent 'no-inner-declarations' failing + const checkRedeem = redeem => { + // is the redeem output empty/invalid? + if (redeem.output) { + const decompile = bscript$k.decompile(redeem.output); + if (!decompile || decompile.length < 1) + throw new TypeError('Redeem.output too short'); + // match hash against other sources + const hash2 = bcrypto$5.hash160(redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (redeem.input) { + const hasInput = redeem.input.length > 0; + const hasWitness = redeem.witness && redeem.witness.length > 0; + if (!hasInput && !hasWitness) throw new TypeError('Empty input'); + if (hasInput && hasWitness) + throw new TypeError('Input and witness provided'); + if (hasInput) { + const richunks = bscript$k.decompile(redeem.input); + if (!bscript$k.isPushOnly(richunks)) + throw new TypeError('Non push-only scriptSig'); + } + } + }; + if (a.input) { + const chunks = _chunks(); + if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); + if (!isBuffer(_redeem().output)) + throw new TypeError('Input is invalid'); + checkRedeem(_redeem()); + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + if (a.input) { + const redeem = _redeem(); + if (a.redeem.output && !a.redeem.output.equals(redeem.output)) + throw new TypeError('Redeem.output mismatch'); + if (a.redeem.input && !a.redeem.input.equals(redeem.input)) + throw new TypeError('Redeem.input mismatch'); + } + checkRedeem(a.redeem); + } + if (a.witness) { + if ( + a.redeem && + a.redeem.witness && + !stacksEqual$1(a.redeem.witness, a.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + } + } + return Object.assign(o, a); + } + p2sh$1.p2sh = p2sh; + + var p2wpkh$2 = {}; + + var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; + + // pre-compute lookup table + var ALPHABET_MAP = {}; + for (var z = 0; z < ALPHABET.length; z++) { + var x = ALPHABET.charAt(z); + + if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') + ALPHABET_MAP[x] = z; + } + + function polymodStep (pre) { + var b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2) ^ + (-((b >> 1) & 1) & 0x26508e6d) ^ + (-((b >> 2) & 1) & 0x1ea119fa) ^ + (-((b >> 3) & 1) & 0x3d4233dd) ^ + (-((b >> 4) & 1) & 0x2a1462b3) + } + + function prefixChk (prefix) { + var chk = 1; + for (var i = 0; i < prefix.length; ++i) { + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')' + + chk = polymodStep(chk) ^ (c >> 5); + } + chk = polymodStep(chk); + + for (i = 0; i < prefix.length; ++i) { + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ (v & 0x1f); + } + return chk + } + + function encode$c (prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') + + prefix = prefix.toLowerCase(); + + // determine chk mod + var chk = prefixChk(prefix); + if (typeof chk === 'string') throw new Error(chk) + + var result = prefix + '1'; + for (var i = 0; i < words.length; ++i) { + var x = words[i]; + if ((x >> 5) !== 0) throw new Error('Non 5-bit word') + + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + + for (i = 0; i < 6; ++i) { + chk = polymodStep(chk); + } + chk ^= 1; + + for (i = 0; i < 6; ++i) { + var v = (chk >> ((5 - i) * 5)) & 0x1f; + result += ALPHABET.charAt(v); + } + + return result + } + + function __decode (str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + ' too short' + if (str.length > LIMIT) return 'Exceeds length limit' + + // don't allow mixed case + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str + str = lowered; + + var split = str.lastIndexOf('1'); + if (split === -1) return 'No separator character for ' + str + if (split === 0) return 'Missing prefix for ' + str + + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return 'Data too short' + + var chk = prefixChk(prefix); + if (typeof chk === 'string') return chk + + var words = []; + for (var i = 0; i < wordChars.length; ++i) { + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === undefined) return 'Unknown character ' + c + chk = polymodStep(chk) ^ v; + + // not in the checksum? + if (i + 6 >= wordChars.length) continue + words.push(v); + } + + if (chk !== 1) return 'Invalid checksum for ' + str + return { prefix: prefix, words: words } + } + + function decodeUnsafe () { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + } + + function decode$b (str) { + var res = __decode.apply(null, arguments); + if (typeof res === 'object') return res + + throw new Error(res) + } + + function convert$2 (data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + + var result = []; + for (var i = 0; i < data.length; ++i) { + value = (value << inBits) | data[i]; + bits += inBits; + + while (bits >= outBits) { + bits -= outBits; + result.push((value >> bits) & maxV); + } + } + + if (pad) { + if (bits > 0) { + result.push((value << (outBits - bits)) & maxV); + } + } else { + if (bits >= inBits) return 'Excess padding' + if ((value << (outBits - bits)) & maxV) return 'Non-zero padding' + } + + return result + } + + function toWordsUnsafe (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + } + + function toWords (bytes) { + var res = convert$2(bytes, 8, 5, true); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + function fromWordsUnsafe (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + } + + function fromWords (words) { + var res = convert$2(words, 5, 8, false); + if (Array.isArray(res)) return res + + throw new Error(res) + } + + var bech32$3 = { + decodeUnsafe: decodeUnsafe, + decode: decode$b, + encode: encode$c, + toWordsUnsafe: toWordsUnsafe, + toWords: toWords, + fromWordsUnsafe: fromWordsUnsafe, + fromWords: fromWords + }; + + Object.defineProperty(p2wpkh$2, '__esModule', { value: true }); + const bcrypto$4 = crypto$2; + const networks_1$2 = networks$3; + const bscript$j = script$1; + const lazy$1 = lazy$7; + const typef$1 = typeforce_1; + const OPS$2 = bscript$j.OPS; + const ecc$2 = js; + const bech32$2 = bech32$3; + const EMPTY_BUFFER$1 = Buffer$k.alloc(0); + // witness: {signature} {pubKey} + // input: <> + // output: OP_0 {pubKeyHash} + function p2wpkh$1(a, opts) { + if (!a.address && !a.hash && !a.output && !a.pubkey && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef$1( + { + address: typef$1.maybe(typef$1.String), + hash: typef$1.maybe(typef$1.BufferN(20)), + input: typef$1.maybe(typef$1.BufferN(0)), + network: typef$1.maybe(typef$1.Object), + output: typef$1.maybe(typef$1.BufferN(22)), + pubkey: typef$1.maybe(ecc$2.isPoint), + signature: typef$1.maybe(bscript$j.isCanonicalScriptSignature), + witness: typef$1.maybe(typef$1.arrayOf(typef$1.Buffer)), + }, + a, + ); + const _address = lazy$1.value(() => { + const result = bech32$2.decode(a.address); + const version = result.words.shift(); + const data = bech32$2.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$k.from(data), + }; + }); + const network = a.network || networks_1$2.bitcoin; + const o = { name: 'p2wpkh', network }; + lazy$1.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$2.toWords(o.hash); + words.unshift(0x00); + return bech32$2.encode(network.bech32, words); + }); + lazy$1.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2, 22); + if (a.address) return _address().data; + if (a.pubkey || o.pubkey) return bcrypto$4.hash160(a.pubkey || o.pubkey); + }); + lazy$1.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$j.compile([OPS$2.OP_0, o.hash]); + }); + lazy$1.prop(o, 'pubkey', () => { + if (a.pubkey) return a.pubkey; + if (!a.witness) return; + return a.witness[1]; + }); + lazy$1.prop(o, 'signature', () => { + if (!a.witness) return; + return a.witness[0]; + }); + lazy$1.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER$1; + }); + lazy$1.prop(o, 'witness', () => { + if (!a.pubkey) return; + if (!a.signature) return; + return [a.signature, a.pubkey]; + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (network && network.bech32 !== _address().prefix) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 20) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 22 || + a.output[0] !== OPS$2.OP_0 || + a.output[1] !== 0x14 + ) + throw new TypeError('Output is invalid'); + if (hash.length > 0 && !hash.equals(a.output.slice(2))) + throw new TypeError('Hash mismatch'); + else hash = a.output.slice(2); + } + if (a.pubkey) { + const pkh = bcrypto$4.hash160(a.pubkey); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + else hash = pkh; + if (!ecc$2.isPoint(a.pubkey) || a.pubkey.length !== 33) + throw new TypeError('Invalid pubkey for p2wpkh'); + } + if (a.witness) { + if (a.witness.length !== 2) throw new TypeError('Witness is invalid'); + if (!bscript$j.isCanonicalScriptSignature(a.witness[0])) + throw new TypeError('Witness has invalid signature'); + if (!ecc$2.isPoint(a.witness[1]) || a.witness[1].length !== 33) + throw new TypeError('Witness has invalid pubkey'); + if (a.signature && !a.signature.equals(a.witness[0])) + throw new TypeError('Signature mismatch'); + if (a.pubkey && !a.pubkey.equals(a.witness[1])) + throw new TypeError('Pubkey mismatch'); + const pkh = bcrypto$4.hash160(a.witness[1]); + if (hash.length > 0 && !hash.equals(pkh)) + throw new TypeError('Hash mismatch'); + } + } + return Object.assign(o, a); + } + p2wpkh$2.p2wpkh = p2wpkh$1; + + var p2wsh$1 = {}; + + Object.defineProperty(p2wsh$1, '__esModule', { value: true }); + const bcrypto$3 = crypto$2; + const networks_1$1 = networks$3; + const bscript$i = script$1; + const lazy = lazy$7; + const typef = typeforce_1; + const OPS$1 = bscript$i.OPS; + const ecc$1 = js; + const bech32$1 = bech32$3; + const EMPTY_BUFFER = Buffer$k.alloc(0); + function stacksEqual(a, b) { + if (a.length !== b.length) return false; + return a.every((x, i) => { + return x.equals(b[i]); + }); + } + function chunkHasUncompressedPubkey(chunk) { + if ( + isBuffer(chunk) && + chunk.length === 65 && + chunk[0] === 0x04 && + ecc$1.isPoint(chunk) + ) { + return true; + } else { + return false; + } + } + // input: <> + // witness: [redeemScriptSig ...] {redeemScript} + // output: OP_0 {sha256(redeemScript)} + function p2wsh(a, opts) { + if (!a.address && !a.hash && !a.output && !a.redeem && !a.witness) + throw new TypeError('Not enough data'); + opts = Object.assign({ validate: true }, opts || {}); + typef( + { + network: typef.maybe(typef.Object), + address: typef.maybe(typef.String), + hash: typef.maybe(typef.BufferN(32)), + output: typef.maybe(typef.BufferN(34)), + redeem: typef.maybe({ + input: typef.maybe(typef.Buffer), + network: typef.maybe(typef.Object), + output: typef.maybe(typef.Buffer), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }), + input: typef.maybe(typef.BufferN(0)), + witness: typef.maybe(typef.arrayOf(typef.Buffer)), + }, + a, + ); + const _address = lazy.value(() => { + const result = bech32$1.decode(a.address); + const version = result.words.shift(); + const data = bech32$1.fromWords(result.words); + return { + version, + prefix: result.prefix, + data: Buffer$k.from(data), + }; + }); + const _rchunks = lazy.value(() => { + return bscript$i.decompile(a.redeem.input); + }); + let network = a.network; + if (!network) { + network = (a.redeem && a.redeem.network) || networks_1$1.bitcoin; + } + const o = { network }; + lazy.prop(o, 'address', () => { + if (!o.hash) return; + const words = bech32$1.toWords(o.hash); + words.unshift(0x00); + return bech32$1.encode(network.bech32, words); + }); + lazy.prop(o, 'hash', () => { + if (a.output) return a.output.slice(2); + if (a.address) return _address().data; + if (o.redeem && o.redeem.output) return bcrypto$3.sha256(o.redeem.output); + }); + lazy.prop(o, 'output', () => { + if (!o.hash) return; + return bscript$i.compile([OPS$1.OP_0, o.hash]); + }); + lazy.prop(o, 'redeem', () => { + if (!a.witness) return; + return { + output: a.witness[a.witness.length - 1], + input: EMPTY_BUFFER, + witness: a.witness.slice(0, -1), + }; + }); + lazy.prop(o, 'input', () => { + if (!o.witness) return; + return EMPTY_BUFFER; + }); + lazy.prop(o, 'witness', () => { + // transform redeem input to witness stack? + if ( + a.redeem && + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.output && + a.redeem.output.length > 0 + ) { + const stack = bscript$i.toStack(_rchunks()); + // assign, and blank the existing input + o.redeem = Object.assign({ witness: stack }, a.redeem); + o.redeem.input = EMPTY_BUFFER; + return [].concat(stack, a.redeem.output); + } + if (!a.redeem) return; + if (!a.redeem.output) return; + if (!a.redeem.witness) return; + return [].concat(a.redeem.witness, a.redeem.output); + }); + lazy.prop(o, 'name', () => { + const nameParts = ['p2wsh']; + if (o.redeem !== undefined) nameParts.push(o.redeem.name); + return nameParts.join('-'); + }); + // extended validation + if (opts.validate) { + let hash = Buffer$k.from([]); + if (a.address) { + if (_address().prefix !== network.bech32) + throw new TypeError('Invalid prefix or Network mismatch'); + if (_address().version !== 0x00) + throw new TypeError('Invalid address version'); + if (_address().data.length !== 32) + throw new TypeError('Invalid address data'); + hash = _address().data; + } + if (a.hash) { + if (hash.length > 0 && !hash.equals(a.hash)) + throw new TypeError('Hash mismatch'); + else hash = a.hash; + } + if (a.output) { + if ( + a.output.length !== 34 || + a.output[0] !== OPS$1.OP_0 || + a.output[1] !== 0x20 + ) + throw new TypeError('Output is invalid'); + const hash2 = a.output.slice(2); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem) { + if (a.redeem.network && a.redeem.network !== network) + throw new TypeError('Network mismatch'); + // is there two redeem sources? + if ( + a.redeem.input && + a.redeem.input.length > 0 && + a.redeem.witness && + a.redeem.witness.length > 0 + ) + throw new TypeError('Ambiguous witness source'); + // is the redeem output non-empty? + if (a.redeem.output) { + if (bscript$i.decompile(a.redeem.output).length === 0) + throw new TypeError('Redeem.output is invalid'); + // match hash against other sources + const hash2 = bcrypto$3.sha256(a.redeem.output); + if (hash.length > 0 && !hash.equals(hash2)) + throw new TypeError('Hash mismatch'); + else hash = hash2; + } + if (a.redeem.input && !bscript$i.isPushOnly(_rchunks())) + throw new TypeError('Non push-only scriptSig'); + if ( + a.witness && + a.redeem.witness && + !stacksEqual(a.witness, a.redeem.witness) + ) + throw new TypeError('Witness and redeem.witness mismatch'); + if ( + (a.redeem.input && _rchunks().some(chunkHasUncompressedPubkey)) || + (a.redeem.output && + (bscript$i.decompile(a.redeem.output) || []).some( + chunkHasUncompressedPubkey, + )) + ) { + throw new TypeError( + 'redeem.input or redeem.output contains uncompressed pubkey', + ); + } + } + if (a.witness && a.witness.length > 0) { + const wScript = a.witness[a.witness.length - 1]; + if (a.redeem && a.redeem.output && !a.redeem.output.equals(wScript)) + throw new TypeError('Witness and redeem.output mismatch'); + if ( + a.witness.some(chunkHasUncompressedPubkey) || + (bscript$i.decompile(wScript) || []).some(chunkHasUncompressedPubkey) + ) + throw new TypeError('Witness contains uncompressed pubkey'); + } + } + return Object.assign(o, a); + } + p2wsh$1.p2wsh = p2wsh; + + Object.defineProperty(payments$4, '__esModule', { value: true }); + const embed_1 = embed; + payments$4.embed = embed_1.p2data; + const p2ms_1 = p2ms$3; + payments$4.p2ms = p2ms_1.p2ms; + const p2pk_1 = p2pk$3; + payments$4.p2pk = p2pk_1.p2pk; + const p2pkh_1 = p2pkh$4; + payments$4.p2pkh = p2pkh_1.p2pkh; + const p2sh_1 = p2sh$1; + payments$4.p2sh = p2sh_1.p2sh; + const p2wpkh_1 = p2wpkh$2; + payments$4.p2wpkh = p2wpkh_1.p2wpkh; + const p2wsh_1 = p2wsh$1; + payments$4.p2wsh = p2wsh_1.p2wsh; + + Object.defineProperty(address$1, '__esModule', { value: true }); + const networks$2 = networks$3; + const payments$3 = payments$4; + const bscript$h = script$1; + const types$8 = types$a; + const bech32 = bech32$3; + const bs58check = bs58check$5; + const typeforce$7 = typeforce_1; + function fromBase58Check(address) { + const payload = bs58check.decode(address); + // TODO: 4.0.0, move to "toOutputScript" + if (payload.length < 21) throw new TypeError(address + ' is too short'); + if (payload.length > 21) throw new TypeError(address + ' is too long'); + const version = payload.readUInt8(0); + const hash = payload.slice(1); + return { version, hash }; + } + address$1.fromBase58Check = fromBase58Check; + function fromBech32(address) { + const result = bech32.decode(address); + const data = bech32.fromWords(result.words.slice(1)); + return { + version: result.words[0], + prefix: result.prefix, + data: Buffer$k.from(data), + }; + } + address$1.fromBech32 = fromBech32; + function toBase58Check(hash, version) { + typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); + const payload = Buffer$k.allocUnsafe(21); + payload.writeUInt8(version, 0); + hash.copy(payload, 1); + return bs58check.encode(payload); + } + address$1.toBase58Check = toBase58Check; + function toBech32(data, version, prefix) { + const words = bech32.toWords(data); + words.unshift(version); + return bech32.encode(prefix, words); + } + address$1.toBech32 = toBech32; + function fromOutputScript(output, network) { + // TODO: Network + network = network || networks$2.bitcoin; + try { + return payments$3.p2pkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2sh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wpkh({ output, network }).address; + } catch (e) {} + try { + return payments$3.p2wsh({ output, network }).address; + } catch (e) {} + throw new Error(bscript$h.toASM(output) + ' has no matching Address'); + } + address$1.fromOutputScript = fromOutputScript; + function toOutputScript(address, network) { + network = network || networks$2.bitcoin; + let decodeBase58; + let decodeBech32; + try { + decodeBase58 = fromBase58Check(address); + } catch (e) {} + if (decodeBase58) { + if (decodeBase58.version === network.pubKeyHash) + return payments$3.p2pkh({ hash: decodeBase58.hash }).output; + if (decodeBase58.version === network.scriptHash) + return payments$3.p2sh({ hash: decodeBase58.hash }).output; + } else { + try { + decodeBech32 = fromBech32(address); + } catch (e) {} + if (decodeBech32) { + if (decodeBech32.prefix !== network.bech32) + throw new Error(address + ' has an invalid prefix'); + if (decodeBech32.version === 0) { + if (decodeBech32.data.length === 20) + return payments$3.p2wpkh({ hash: decodeBech32.data }).output; + if (decodeBech32.data.length === 32) + return payments$3.p2wsh({ hash: decodeBech32.data }).output; + } + } + } + throw new Error(address + ' has no matching Script'); + } + address$1.toOutputScript = toOutputScript; + + var ecpair = {}; + + var browser$1 = {exports: {}}; + + // limit of Crypto.getRandomValues() + // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues + var MAX_BYTES = 65536; + + // Node supports requesting up to this number of bytes + // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 + var MAX_UINT32 = 4294967295; + + function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') + } + + var Buffer$1 = safeBuffer.exports.Buffer; + var crypto$1 = commonjsGlobal.crypto || commonjsGlobal.msCrypto; + + if (crypto$1 && crypto$1.getRandomValues) { + browser$1.exports = randomBytes$1; + } else { + browser$1.exports = oldBrowser; + } + + function randomBytes$1 (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer$1.allocUnsafe(size); + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto$1.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)); + } + } else { + crypto$1.getRandomValues(bytes); + } + } + + if (typeof cb === 'function') { + return nextTick(function () { + cb(null, bytes); + }) + } + + return bytes + } + + Object.defineProperty(ecpair, '__esModule', { value: true }); + const NETWORKS = networks$3; + const types$7 = types$a; + const ecc = js; + const randomBytes = browser$1.exports; + const typeforce$6 = typeforce_1; + const wif = wif$2; + const isOptions = typeforce$6.maybe( + typeforce$6.compile({ + compressed: types$7.maybe(types$7.Boolean), + network: types$7.maybe(types$7.Network), + }), + ); + class ECPair$2 { + constructor(__D, __Q, options) { + this.__D = __D; + this.__Q = __Q; + this.lowR = false; + if (options === undefined) options = {}; + this.compressed = + options.compressed === undefined ? true : options.compressed; + this.network = options.network || NETWORKS.bitcoin; + if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed); + } + get privateKey() { + return this.__D; + } + get publicKey() { + if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__D, this.compressed); + return this.__Q; + } + toWIF() { + if (!this.__D) throw new Error('Missing private key'); + return wif.encode(this.network.wif, this.__D, this.compressed); + } + sign(hash, lowR) { + if (!this.__D) throw new Error('Missing private key'); + if (lowR === undefined) lowR = this.lowR; + if (lowR === false) { + return ecc.sign(hash, this.__D); + } else { + let sig = ecc.sign(hash, this.__D); + const extraData = Buffer$k.alloc(32, 0); + let counter = 0; + // if first try is lowR, skip the loop + // for second try and on, add extra entropy counting up + while (sig[0] > 0x7f) { + counter++; + extraData.writeUIntLE(counter, 0, 6); + sig = ecc.signWithEntropy(hash, this.__D, extraData); + } + return sig; + } + } + verify(hash, signature) { + return ecc.verify(hash, this.publicKey, signature); + } + } + function fromPrivateKey(buffer, options) { + typeforce$6(types$7.Buffer256bit, buffer); + if (!ecc.isPrivate(buffer)) + throw new TypeError('Private key not in range [1, n)'); + typeforce$6(isOptions, options); + return new ECPair$2(buffer, undefined, options); + } + ecpair.fromPrivateKey = fromPrivateKey; + function fromPublicKey(buffer, options) { + typeforce$6(ecc.isPoint, buffer); + typeforce$6(isOptions, options); + return new ECPair$2(undefined, buffer, options); + } + ecpair.fromPublicKey = fromPublicKey; + function fromWIF(wifString, network) { + const decoded = wif.decode(wifString); + const version = decoded.version; + // list of networks? + if (types$7.Array(network)) { + network = network + .filter(x => { + return version === x.wif; + }) + .pop(); + if (!network) throw new Error('Unknown network version'); + // otherwise, assume a network object (or default to bitcoin) + } else { + network = network || NETWORKS.bitcoin; + if (version !== network.wif) throw new Error('Invalid network version'); + } + return fromPrivateKey(decoded.privateKey, { + compressed: decoded.compressed, + network: network, + }); + } + ecpair.fromWIF = fromWIF; + function makeRandom(options) { + typeforce$6(isOptions, options); + if (options === undefined) options = {}; + const rng = options.rng || randomBytes; + let d; + do { + d = rng(32); + typeforce$6(types$7.Buffer256bit, d); + } while (!ecc.isPrivate(d)); + return fromPrivateKey(d, options); + } + ecpair.makeRandom = makeRandom; + + var block = {}; + + var bufferutils = {}; + + var Buffer = safeBuffer.exports.Buffer; + + // Number.MAX_SAFE_INTEGER + var MAX_SAFE_INTEGER$3 = 9007199254740991; + + function checkUInt53$1 (n) { + if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') + } + + function encode$b (number, buffer, offset) { + checkUInt53$1(number); + + if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + // 8 bit + if (number < 0xfd) { + buffer.writeUInt8(number, offset); + encode$b.bytes = 1; + + // 16 bit + } else if (number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(number, offset + 1); + encode$b.bytes = 3; + + // 32 bit + } else if (number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(number, offset + 1); + encode$b.bytes = 5; + + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(number >>> 0, offset + 1); + buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); + encode$b.bytes = 9; + } + + return buffer + } + + function decode$a (buffer, offset) { + if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') + if (!offset) offset = 0; + + var first = buffer.readUInt8(offset); + + // 8 bit + if (first < 0xfd) { + decode$a.bytes = 1; + return first + + // 16 bit + } else if (first === 0xfd) { + decode$a.bytes = 3; + return buffer.readUInt16LE(offset + 1) + + // 32 bit + } else if (first === 0xfe) { + decode$a.bytes = 5; + return buffer.readUInt32LE(offset + 1) + + // 64 bit + } else { + decode$a.bytes = 9; + var lo = buffer.readUInt32LE(offset + 1); + var hi = buffer.readUInt32LE(offset + 5); + var number = hi * 0x0100000000 + lo; + checkUInt53$1(number); + + return number + } + } + + function encodingLength$1 (number) { + checkUInt53$1(number); + + return ( + number < 0xfd ? 1 + : number <= 0xffff ? 3 + : number <= 0xffffffff ? 5 + : 9 + ) + } + + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + + Object.defineProperty(bufferutils, '__esModule', { value: true }); + const types$6 = types$a; + const typeforce$5 = typeforce_1; + const varuint$6 = varuintBitcoin; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint$1(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE$1(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint$1(b + a, 0x001fffffffffffff); + return b + a; + } + bufferutils.readUInt64LE = readUInt64LE$1; + function writeUInt64LE$1(buffer, value, offset) { + verifuint$1(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + bufferutils.writeUInt64LE = writeUInt64LE$1; + function reverseBuffer$1(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + bufferutils.reverseBuffer = reverseBuffer$1; + function cloneBuffer(buffer) { + const clone = Buffer$k.allocUnsafe(buffer.length); + buffer.copy(clone); + return clone; + } + bufferutils.cloneBuffer = cloneBuffer; + /** + * Helper class for serialization of bitcoin data types into a pre-allocated buffer. + */ + class BufferWriter$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + writeUInt8(i) { + this.offset = this.buffer.writeUInt8(i, this.offset); + } + writeInt32(i) { + this.offset = this.buffer.writeInt32LE(i, this.offset); + } + writeUInt32(i) { + this.offset = this.buffer.writeUInt32LE(i, this.offset); + } + writeUInt64(i) { + this.offset = writeUInt64LE$1(this.buffer, i, this.offset); + } + writeVarInt(i) { + varuint$6.encode(i, this.buffer, this.offset); + this.offset += varuint$6.encode.bytes; + } + writeSlice(slice) { + if (this.buffer.length < this.offset + slice.length) { + throw new Error('Cannot write slice out of bounds'); + } + this.offset += slice.copy(this.buffer, this.offset); + } + writeVarSlice(slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + } + writeVector(vector) { + this.writeVarInt(vector.length); + vector.forEach(buf => this.writeVarSlice(buf)); + } + } + bufferutils.BufferWriter = BufferWriter$1; + /** + * Helper class for reading of bitcoin data types from a buffer. + */ + class BufferReader$1 { + constructor(buffer, offset = 0) { + this.buffer = buffer; + this.offset = offset; + typeforce$5(types$6.tuple(types$6.Buffer, types$6.UInt32), [buffer, offset]); + } + readUInt8() { + const result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + } + readInt32() { + const result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt32() { + const result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + } + readUInt64() { + const result = readUInt64LE$1(this.buffer, this.offset); + this.offset += 8; + return result; + } + readVarInt() { + const vi = varuint$6.decode(this.buffer, this.offset); + this.offset += varuint$6.decode.bytes; + return vi; + } + readSlice(n) { + if (this.buffer.length < this.offset + n) { + throw new Error('Cannot read slice out of bounds'); + } + const result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + } + readVarSlice() { + return this.readSlice(this.readVarInt()); + } + readVector() { + const count = this.readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(this.readVarSlice()); + return vector; + } + } + bufferutils.BufferReader = BufferReader$1; + + var transaction = {}; + + Object.defineProperty(transaction, '__esModule', { value: true }); + const bufferutils_1$3 = bufferutils; + const bcrypto$2 = crypto$2; + const bscript$g = script$1; + const script_1$b = script$1; + const types$5 = types$a; + const typeforce$4 = typeforce_1; + const varuint$5 = varuintBitcoin; + function varSliceSize(someScript) { + const length = someScript.length; + return varuint$5.encodingLength(length) + length; + } + function vectorSize(someVector) { + const length = someVector.length; + return ( + varuint$5.encodingLength(length) + + someVector.reduce((sum, witness) => { + return sum + varSliceSize(witness); + }, 0) + ); + } + const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); + const EMPTY_WITNESS = []; + const ZERO = Buffer$k.from( + '0000000000000000000000000000000000000000000000000000000000000000', + 'hex', + ); + const ONE = Buffer$k.from( + '0000000000000000000000000000000000000000000000000000000000000001', + 'hex', + ); + const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); + const BLANK_OUTPUT = { + script: EMPTY_SCRIPT, + valueBuffer: VALUE_UINT64_MAX, + }; + function isOutput(out) { + return out.value !== undefined; + } + class Transaction { + constructor() { + this.version = 1; + this.locktime = 0; + this.ins = []; + this.outs = []; + } + static fromBuffer(buffer, _NO_STRICT) { + const bufferReader = new bufferutils_1$3.BufferReader(buffer); + const tx = new Transaction(); + tx.version = bufferReader.readInt32(); + const marker = bufferReader.readUInt8(); + const flag = bufferReader.readUInt8(); + let hasWitnesses = false; + if ( + marker === Transaction.ADVANCED_TRANSACTION_MARKER && + flag === Transaction.ADVANCED_TRANSACTION_FLAG + ) { + hasWitnesses = true; + } else { + bufferReader.offset -= 2; + } + const vinLen = bufferReader.readVarInt(); + for (let i = 0; i < vinLen; ++i) { + tx.ins.push({ + hash: bufferReader.readSlice(32), + index: bufferReader.readUInt32(), + script: bufferReader.readVarSlice(), + sequence: bufferReader.readUInt32(), + witness: EMPTY_WITNESS, + }); + } + const voutLen = bufferReader.readVarInt(); + for (let i = 0; i < voutLen; ++i) { + tx.outs.push({ + value: bufferReader.readUInt64(), + script: bufferReader.readVarSlice(), + }); + } + if (hasWitnesses) { + for (let i = 0; i < vinLen; ++i) { + tx.ins[i].witness = bufferReader.readVector(); + } + // was this pointless? + if (!tx.hasWitnesses()) + throw new Error('Transaction has superfluous witness data'); + } + tx.locktime = bufferReader.readUInt32(); + if (_NO_STRICT) return tx; + if (bufferReader.offset !== buffer.length) + throw new Error('Transaction has unexpected data'); + return tx; + } + static fromHex(hex) { + return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); + } + static isCoinbaseHash(buffer) { + typeforce$4(types$5.Hash256bit, buffer); + for (let i = 0; i < 32; ++i) { + if (buffer[i] !== 0) return false; + } + return true; + } + isCoinbase() { + return ( + this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) + ); + } + addInput(hash, index, sequence, scriptSig) { + typeforce$4( + types$5.tuple( + types$5.Hash256bit, + types$5.UInt32, + types$5.maybe(types$5.UInt32), + types$5.maybe(types$5.Buffer), + ), + arguments, + ); + if (types$5.Null(sequence)) { + sequence = Transaction.DEFAULT_SEQUENCE; + } + // Add the input and return the input's index + return ( + this.ins.push({ + hash, + index, + script: scriptSig || EMPTY_SCRIPT, + sequence: sequence, + witness: EMPTY_WITNESS, + }) - 1 + ); + } + addOutput(scriptPubKey, value) { + typeforce$4(types$5.tuple(types$5.Buffer, types$5.Satoshi), arguments); + // Add the output and return the output's index + return ( + this.outs.push({ + script: scriptPubKey, + value, + }) - 1 + ); + } + hasWitnesses() { + return this.ins.some(x => { + return x.witness.length !== 0; + }); + } + weight() { + const base = this.byteLength(false); + const total = this.byteLength(true); + return base * 3 + total; + } + virtualSize() { + return Math.ceil(this.weight() / 4); + } + byteLength(_ALLOW_WITNESS = true) { + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + return ( + (hasWitnesses ? 10 : 8) + + varuint$5.encodingLength(this.ins.length) + + varuint$5.encodingLength(this.outs.length) + + this.ins.reduce((sum, input) => { + return sum + 40 + varSliceSize(input.script); + }, 0) + + this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0) + + (hasWitnesses + ? this.ins.reduce((sum, input) => { + return sum + vectorSize(input.witness); + }, 0) + : 0) + ); + } + clone() { + const newTx = new Transaction(); + newTx.version = this.version; + newTx.locktime = this.locktime; + newTx.ins = this.ins.map(txIn => { + return { + hash: txIn.hash, + index: txIn.index, + script: txIn.script, + sequence: txIn.sequence, + witness: txIn.witness, + }; + }); + newTx.outs = this.outs.map(txOut => { + return { + script: txOut.script, + value: txOut.value, + }; + }); + return newTx; + } + /** + * Hash transaction for signing a specific input. + * + * Bitcoin uses a different hash for each signed transaction input. + * This method copies the transaction, makes the necessary changes based on the + * hashType, and then hashes the result. + * This hash can then be used to sign the provided transaction input. + */ + hashForSignature(inIndex, prevOutScript, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, /* types.UInt8 */ types$5.Number), + arguments, + ); + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 + if (inIndex >= this.ins.length) return ONE; + // ignore OP_CODESEPARATOR + const ourScript = bscript$g.compile( + bscript$g.decompile(prevOutScript).filter(x => { + return x !== script_1$b.OPS.OP_CODESEPARATOR; + }), + ); + const txTmp = this.clone(); + // SIGHASH_NONE: ignore all outputs? (wildcard payee) + if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { + txTmp.outs = []; + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, i) => { + if (i === inIndex) return; + input.sequence = 0; + }); + // SIGHASH_SINGLE: ignore all outputs, except at the same index? + } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { + // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 + if (inIndex >= this.outs.length) return ONE; + // truncate outputs after + txTmp.outs.length = inIndex + 1; + // "blank" outputs before + for (let i = 0; i < inIndex; i++) { + txTmp.outs[i] = BLANK_OUTPUT; + } + // ignore sequence numbers (except at inIndex) + txTmp.ins.forEach((input, y) => { + if (y === inIndex) return; + input.sequence = 0; + }); + } + // SIGHASH_ANYONECANPAY: ignore inputs entirely? + if (hashType & Transaction.SIGHASH_ANYONECANPAY) { + txTmp.ins = [txTmp.ins[inIndex]]; + txTmp.ins[0].script = ourScript; + // SIGHASH_ALL: only ignore input scripts + } else { + // "blank" others input scripts + txTmp.ins.forEach(input => { + input.script = EMPTY_SCRIPT; + }); + txTmp.ins[inIndex].script = ourScript; + } + // serialize and hash + const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); + buffer.writeInt32LE(hashType, buffer.length - 4); + txTmp.__toBuffer(buffer, 0, false); + return bcrypto$2.hash256(buffer); + } + hashForWitnessV0(inIndex, prevOutScript, value, hashType) { + typeforce$4( + types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), + arguments, + ); + let tbuffer = Buffer$k.from([]); + let bufferWriter; + let hashOutputs = ZERO; + let hashPrevouts = ZERO; + let hashSequence = ZERO; + if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { + tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + }); + hashPrevouts = bcrypto$2.hash256(tbuffer); + } + if ( + !(hashType & Transaction.SIGHASH_ANYONECANPAY) && + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.ins.forEach(txIn => { + bufferWriter.writeUInt32(txIn.sequence); + }); + hashSequence = bcrypto$2.hash256(tbuffer); + } + if ( + (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && + (hashType & 0x1f) !== Transaction.SIGHASH_NONE + ) { + const txOutsSize = this.outs.reduce((sum, output) => { + return sum + 8 + varSliceSize(output.script); + }, 0); + tbuffer = Buffer$k.allocUnsafe(txOutsSize); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + this.outs.forEach(out => { + bufferWriter.writeUInt64(out.value); + bufferWriter.writeVarSlice(out.script); + }); + hashOutputs = bcrypto$2.hash256(tbuffer); + } else if ( + (hashType & 0x1f) === Transaction.SIGHASH_SINGLE && + inIndex < this.outs.length + ) { + const output = this.outs[inIndex]; + tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + bufferWriter.writeUInt64(output.value); + bufferWriter.writeVarSlice(output.script); + hashOutputs = bcrypto$2.hash256(tbuffer); + } + tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); + bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); + const input = this.ins[inIndex]; + bufferWriter.writeUInt32(this.version); + bufferWriter.writeSlice(hashPrevouts); + bufferWriter.writeSlice(hashSequence); + bufferWriter.writeSlice(input.hash); + bufferWriter.writeUInt32(input.index); + bufferWriter.writeVarSlice(prevOutScript); + bufferWriter.writeUInt64(value); + bufferWriter.writeUInt32(input.sequence); + bufferWriter.writeSlice(hashOutputs); + bufferWriter.writeUInt32(this.locktime); + bufferWriter.writeUInt32(hashType); + return bcrypto$2.hash256(tbuffer); + } + getHash(forWitness) { + // wtxid for coinbase is always 32 bytes of 0x00 + if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); + return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); + } + getId() { + // transaction hash's are displayed in reverse order + return bufferutils_1$3.reverseBuffer(this.getHash(false)).toString('hex'); + } + toBuffer(buffer, initialOffset) { + return this.__toBuffer(buffer, initialOffset, true); + } + toHex() { + return this.toBuffer(undefined, undefined).toString('hex'); + } + setInputScript(index, scriptSig) { + typeforce$4(types$5.tuple(types$5.Number, types$5.Buffer), arguments); + this.ins[index].script = scriptSig; + } + setWitness(index, witness) { + typeforce$4(types$5.tuple(types$5.Number, [types$5.Buffer]), arguments); + this.ins[index].witness = witness; + } + __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { + if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + const bufferWriter = new bufferutils_1$3.BufferWriter( + buffer, + initialOffset || 0, + ); + bufferWriter.writeInt32(this.version); + const hasWitnesses = _ALLOW_WITNESS && this.hasWitnesses(); + if (hasWitnesses) { + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER); + bufferWriter.writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG); + } + bufferWriter.writeVarInt(this.ins.length); + this.ins.forEach(txIn => { + bufferWriter.writeSlice(txIn.hash); + bufferWriter.writeUInt32(txIn.index); + bufferWriter.writeVarSlice(txIn.script); + bufferWriter.writeUInt32(txIn.sequence); + }); + bufferWriter.writeVarInt(this.outs.length); + this.outs.forEach(txOut => { + if (isOutput(txOut)) { + bufferWriter.writeUInt64(txOut.value); + } else { + bufferWriter.writeSlice(txOut.valueBuffer); + } + bufferWriter.writeVarSlice(txOut.script); + }); + if (hasWitnesses) { + this.ins.forEach(input => { + bufferWriter.writeVector(input.witness); + }); + } + bufferWriter.writeUInt32(this.locktime); + // avoid slicing unless necessary + if (initialOffset !== undefined) + return buffer.slice(initialOffset, bufferWriter.offset); + return buffer; + } + } + Transaction.DEFAULT_SEQUENCE = 0xffffffff; + Transaction.SIGHASH_ALL = 0x01; + Transaction.SIGHASH_NONE = 0x02; + Transaction.SIGHASH_SINGLE = 0x03; + Transaction.SIGHASH_ANYONECANPAY = 0x80; + Transaction.ADVANCED_TRANSACTION_MARKER = 0x00; + Transaction.ADVANCED_TRANSACTION_FLAG = 0x01; + transaction.Transaction = Transaction; + + // constant-space merkle root calculation algorithm + var fastRoot = function fastRoot (values, digestFn) { + if (!Array.isArray(values)) throw TypeError('Expected values Array') + if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') + + var length = values.length; + var results = values.concat(); + + while (length > 1) { + var j = 0; + + for (var i = 0; i < length; i += 2, ++j) { + var left = results[i]; + var right = i + 1 === length ? left : results[i + 1]; + var data = Buffer$k.concat([left, right]); + + results[j] = digestFn(data); + } + + length = j; + } + + return results[0] + }; + + Object.defineProperty(block, '__esModule', { value: true }); + const bufferutils_1$2 = bufferutils; + const bcrypto$1 = crypto$2; + const transaction_1$3 = transaction; + const types$4 = types$a; + const fastMerkleRoot = fastRoot; + const typeforce$3 = typeforce_1; + const varuint$4 = varuintBitcoin; + const errorMerkleNoTxes = new TypeError( + 'Cannot compute merkle root for zero transactions', + ); + const errorWitnessNotSegwit = new TypeError( + 'Cannot compute witness commit for non-segwit block', + ); + class Block { + constructor() { + this.version = 1; + this.prevHash = undefined; + this.merkleRoot = undefined; + this.timestamp = 0; + this.witnessCommit = undefined; + this.bits = 0; + this.nonce = 0; + this.transactions = undefined; + } + static fromBuffer(buffer) { + if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)'); + const bufferReader = new bufferutils_1$2.BufferReader(buffer); + const block = new Block(); + block.version = bufferReader.readInt32(); + block.prevHash = bufferReader.readSlice(32); + block.merkleRoot = bufferReader.readSlice(32); + block.timestamp = bufferReader.readUInt32(); + block.bits = bufferReader.readUInt32(); + block.nonce = bufferReader.readUInt32(); + if (buffer.length === 80) return block; + const readTransaction = () => { + const tx = transaction_1$3.Transaction.fromBuffer( + bufferReader.buffer.slice(bufferReader.offset), + true, + ); + bufferReader.offset += tx.byteLength(); + return tx; + }; + const nTransactions = bufferReader.readVarInt(); + block.transactions = []; + for (let i = 0; i < nTransactions; ++i) { + const tx = readTransaction(); + block.transactions.push(tx); + } + const witnessCommit = block.getWitnessCommit(); + // This Block contains a witness commit + if (witnessCommit) block.witnessCommit = witnessCommit; + return block; + } + static fromHex(hex) { + return Block.fromBuffer(Buffer$k.from(hex, 'hex')); + } + static calculateTarget(bits) { + const exponent = ((bits & 0xff000000) >> 24) - 3; + const mantissa = bits & 0x007fffff; + const target = Buffer$k.alloc(32, 0); + target.writeUIntBE(mantissa, 29 - exponent, 3); + return target; + } + static calculateMerkleRoot(transactions, forWitness) { + typeforce$3([{ getHash: types$4.Function }], transactions); + if (transactions.length === 0) throw errorMerkleNoTxes; + if (forWitness && !txesHaveWitnessCommit(transactions)) + throw errorWitnessNotSegwit; + const hashes = transactions.map(transaction => + transaction.getHash(forWitness), + ); + const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); + return forWitness + ? bcrypto$1.hash256( + Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), + ) + : rootHash; + } + getWitnessCommit() { + if (!txesHaveWitnessCommit(this.transactions)) return null; + // The merkle root for the witness data is in an OP_RETURN output. + // There is no rule for the index of the output, so use filter to find it. + // The root is prepended with 0xaa21a9ed so check for 0x6a24aa21a9ed + // If multiple commits are found, the output with highest index is assumed. + const witnessCommits = this.transactions[0].outs + .filter(out => + out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), + ) + .map(out => out.script.slice(6, 38)); + if (witnessCommits.length === 0) return null; + // Use the commit with the highest output (should only be one though) + const result = witnessCommits[witnessCommits.length - 1]; + if (!(result instanceof Buffer$k && result.length === 32)) return null; + return result; + } + hasWitnessCommit() { + if ( + this.witnessCommit instanceof Buffer$k && + this.witnessCommit.length === 32 + ) + return true; + if (this.getWitnessCommit() !== null) return true; + return false; + } + hasWitness() { + return anyTxHasWitness(this.transactions); + } + weight() { + const base = this.byteLength(false, false); + const total = this.byteLength(false, true); + return base * 3 + total; + } + byteLength(headersOnly, allowWitness = true) { + if (headersOnly || !this.transactions) return 80; + return ( + 80 + + varuint$4.encodingLength(this.transactions.length) + + this.transactions.reduce((a, x) => a + x.byteLength(allowWitness), 0) + ); + } + getHash() { + return bcrypto$1.hash256(this.toBuffer(true)); + } + getId() { + return bufferutils_1$2.reverseBuffer(this.getHash()).toString('hex'); + } + getUTCDate() { + const date = new Date(0); // epoch + date.setUTCSeconds(this.timestamp); + return date; + } + // TODO: buffer, offset compatibility + toBuffer(headersOnly) { + const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); + const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); + bufferWriter.writeInt32(this.version); + bufferWriter.writeSlice(this.prevHash); + bufferWriter.writeSlice(this.merkleRoot); + bufferWriter.writeUInt32(this.timestamp); + bufferWriter.writeUInt32(this.bits); + bufferWriter.writeUInt32(this.nonce); + if (headersOnly || !this.transactions) return buffer; + varuint$4.encode(this.transactions.length, buffer, bufferWriter.offset); + bufferWriter.offset += varuint$4.encode.bytes; + this.transactions.forEach(tx => { + const txSize = tx.byteLength(); // TODO: extract from toBuffer? + tx.toBuffer(buffer, bufferWriter.offset); + bufferWriter.offset += txSize; + }); + return buffer; + } + toHex(headersOnly) { + return this.toBuffer(headersOnly).toString('hex'); + } + checkTxRoots() { + // If the Block has segwit transactions but no witness commit, + // there's no way it can be valid, so fail the check. + const hasWitnessCommit = this.hasWitnessCommit(); + if (!hasWitnessCommit && this.hasWitness()) return false; + return ( + this.__checkMerkleRoot() && + (hasWitnessCommit ? this.__checkWitnessCommit() : true) + ); + } + checkProofOfWork() { + const hash = bufferutils_1$2.reverseBuffer(this.getHash()); + const target = Block.calculateTarget(this.bits); + return hash.compare(target) <= 0; + } + __checkMerkleRoot() { + if (!this.transactions) throw errorMerkleNoTxes; + const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions); + return this.merkleRoot.compare(actualMerkleRoot) === 0; + } + __checkWitnessCommit() { + if (!this.transactions) throw errorMerkleNoTxes; + if (!this.hasWitnessCommit()) throw errorWitnessNotSegwit; + const actualWitnessCommit = Block.calculateMerkleRoot( + this.transactions, + true, + ); + return this.witnessCommit.compare(actualWitnessCommit) === 0; + } + } + block.Block = Block; + function txesHaveWitnessCommit(transactions) { + return ( + transactions instanceof Array && + transactions[0] && + transactions[0].ins && + transactions[0].ins instanceof Array && + transactions[0].ins[0] && + transactions[0].ins[0].witness && + transactions[0].ins[0].witness instanceof Array && + transactions[0].ins[0].witness.length > 0 + ); + } + function anyTxHasWitness(transactions) { + return ( + transactions instanceof Array && + transactions.some( + tx => + typeof tx === 'object' && + tx.ins instanceof Array && + tx.ins.some( + input => + typeof input === 'object' && + input.witness instanceof Array && + input.witness.length > 0, + ), + ) + ); + } + + var psbt$1 = {}; + + var psbt = {}; + + var combiner = {}; + + var parser = {}; + + var fromBuffer = {}; + + var converter = {}; + + var typeFields = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + (function(GlobalTypes) { + GlobalTypes[(GlobalTypes['UNSIGNED_TX'] = 0)] = 'UNSIGNED_TX'; + GlobalTypes[(GlobalTypes['GLOBAL_XPUB'] = 1)] = 'GLOBAL_XPUB'; + })((exports.GlobalTypes || (exports.GlobalTypes = {}))); + exports.GLOBAL_TYPE_NAMES = ['unsignedTx', 'globalXpub']; + (function(InputTypes) { + InputTypes[(InputTypes['NON_WITNESS_UTXO'] = 0)] = 'NON_WITNESS_UTXO'; + InputTypes[(InputTypes['WITNESS_UTXO'] = 1)] = 'WITNESS_UTXO'; + InputTypes[(InputTypes['PARTIAL_SIG'] = 2)] = 'PARTIAL_SIG'; + InputTypes[(InputTypes['SIGHASH_TYPE'] = 3)] = 'SIGHASH_TYPE'; + InputTypes[(InputTypes['REDEEM_SCRIPT'] = 4)] = 'REDEEM_SCRIPT'; + InputTypes[(InputTypes['WITNESS_SCRIPT'] = 5)] = 'WITNESS_SCRIPT'; + InputTypes[(InputTypes['BIP32_DERIVATION'] = 6)] = 'BIP32_DERIVATION'; + InputTypes[(InputTypes['FINAL_SCRIPTSIG'] = 7)] = 'FINAL_SCRIPTSIG'; + InputTypes[(InputTypes['FINAL_SCRIPTWITNESS'] = 8)] = 'FINAL_SCRIPTWITNESS'; + InputTypes[(InputTypes['POR_COMMITMENT'] = 9)] = 'POR_COMMITMENT'; + })((exports.InputTypes || (exports.InputTypes = {}))); + exports.INPUT_TYPE_NAMES = [ + 'nonWitnessUtxo', + 'witnessUtxo', + 'partialSig', + 'sighashType', + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + 'finalScriptSig', + 'finalScriptWitness', + 'porCommitment', + ]; + (function(OutputTypes) { + OutputTypes[(OutputTypes['REDEEM_SCRIPT'] = 0)] = 'REDEEM_SCRIPT'; + OutputTypes[(OutputTypes['WITNESS_SCRIPT'] = 1)] = 'WITNESS_SCRIPT'; + OutputTypes[(OutputTypes['BIP32_DERIVATION'] = 2)] = 'BIP32_DERIVATION'; + })((exports.OutputTypes || (exports.OutputTypes = {}))); + exports.OUTPUT_TYPE_NAMES = [ + 'redeemScript', + 'witnessScript', + 'bip32Derivation', + ]; + }(typeFields)); + + var globalXpub$1 = {}; + + Object.defineProperty(globalXpub$1, '__esModule', { value: true }); + const typeFields_1$b = typeFields; + const range$3 = n => [...Array(n).keys()]; + function decode$9(keyVal) { + if (keyVal.key[0] !== typeFields_1$b.GlobalTypes.GLOBAL_XPUB) { + throw new Error( + 'Decode Error: could not decode globalXpub with key 0x' + + keyVal.key.toString('hex'), + ); + } + if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) { + throw new Error( + 'Decode Error: globalXpub has invalid extended pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4', + ); + } + const extendedPubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + extendedPubkey, + path: 'm', + }; + for (const i of range$3(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + globalXpub$1.decode = decode$9; + function encode$a(data) { + const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$k.concat([head, data.extendedPubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + globalXpub$1.encode = encode$a; + globalXpub$1.expected = + '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; + function check$l(data) { + const epk = data.extendedPubkey; + const mfp = data.masterFingerprint; + const p = data.path; + return ( + isBuffer(epk) && + epk.length === 78 && + [2, 3].indexOf(epk[45]) > -1 && + isBuffer(mfp) && + mfp.length === 4 && + typeof p === 'string' && + !!p.match(/^m(\/\d+'?)+$/) + ); + } + globalXpub$1.check = check$l; + function canAddToArray$1(array, item, dupeSet) { + const dupeString = item.extendedPubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return ( + array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0 + ); + } + globalXpub$1.canAddToArray = canAddToArray$1; + + var unsignedTx$1 = {}; + + Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); + const typeFields_1$a = typeFields; + function encode$9(data) { + return { + key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + value: data.toBuffer(), + }; + } + unsignedTx$1.encode = encode$9; + + var finalScriptSig$1 = {}; + + Object.defineProperty(finalScriptSig$1, '__esModule', { value: true }); + const typeFields_1$9 = typeFields; + function decode$8(keyVal) { + if (keyVal.key[0] !== typeFields_1$9.InputTypes.FINAL_SCRIPTSIG) { + throw new Error( + 'Decode Error: could not decode finalScriptSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptSig$1.decode = decode$8; + function encode$8(data) { + const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + return { + key, + value: data, + }; + } + finalScriptSig$1.encode = encode$8; + finalScriptSig$1.expected = 'Buffer'; + function check$k(data) { + return isBuffer(data); + } + finalScriptSig$1.check = check$k; + function canAdd$5(currentData, newData) { + return !!currentData && !!newData && currentData.finalScriptSig === undefined; + } + finalScriptSig$1.canAdd = canAdd$5; + + var finalScriptWitness$1 = {}; + + Object.defineProperty(finalScriptWitness$1, '__esModule', { value: true }); + const typeFields_1$8 = typeFields; + function decode$7(keyVal) { + if (keyVal.key[0] !== typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS) { + throw new Error( + 'Decode Error: could not decode finalScriptWitness with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + finalScriptWitness$1.decode = decode$7; + function encode$7(data) { + const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + return { + key, + value: data, + }; + } + finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.expected = 'Buffer'; + function check$j(data) { + return isBuffer(data); + } + finalScriptWitness$1.check = check$j; + function canAdd$4(currentData, newData) { + return ( + !!currentData && !!newData && currentData.finalScriptWitness === undefined + ); + } + finalScriptWitness$1.canAdd = canAdd$4; + + var nonWitnessUtxo$1 = {}; + + Object.defineProperty(nonWitnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$7 = typeFields; + function decode$6(keyVal) { + if (keyVal.key[0] !== typeFields_1$7.InputTypes.NON_WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode nonWitnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + nonWitnessUtxo$1.decode = decode$6; + function encode$6(data) { + return { + key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + value: data, + }; + } + nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.expected = 'Buffer'; + function check$i(data) { + return isBuffer(data); + } + nonWitnessUtxo$1.check = check$i; + function canAdd$3(currentData, newData) { + return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined; + } + nonWitnessUtxo$1.canAdd = canAdd$3; + + var partialSig$1 = {}; + + Object.defineProperty(partialSig$1, '__esModule', { value: true }); + const typeFields_1$6 = typeFields; + function decode$5(keyVal) { + if (keyVal.key[0] !== typeFields_1$6.InputTypes.PARTIAL_SIG) { + throw new Error( + 'Decode Error: could not decode partialSig with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: partialSig has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + const pubkey = keyVal.key.slice(1); + return { + pubkey, + signature: keyVal.value, + }; + } + partialSig$1.decode = decode$5; + function encode$5(pSig) { + const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + return { + key: Buffer$k.concat([head, pSig.pubkey]), + value: pSig.signature, + }; + } + partialSig$1.encode = encode$5; + partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; + function check$h(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.signature) && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + isDerSigWithSighash(data.signature) + ); + } + partialSig$1.check = check$h; + function isDerSigWithSighash(buf) { + if (!isBuffer(buf) || buf.length < 9) return false; + if (buf[0] !== 0x30) return false; + if (buf.length !== buf[1] + 3) return false; + if (buf[2] !== 0x02) return false; + const rLen = buf[3]; + if (rLen > 33 || rLen < 1) return false; + if (buf[3 + rLen + 1] !== 0x02) return false; + const sLen = buf[3 + rLen + 2]; + if (sLen > 33 || sLen < 1) return false; + if (buf.length !== 3 + rLen + 2 + sLen + 2) return false; + return true; + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + partialSig$1.canAddToArray = canAddToArray; + + var porCommitment$1 = {}; + + Object.defineProperty(porCommitment$1, '__esModule', { value: true }); + const typeFields_1$5 = typeFields; + function decode$4(keyVal) { + if (keyVal.key[0] !== typeFields_1$5.InputTypes.POR_COMMITMENT) { + throw new Error( + 'Decode Error: could not decode porCommitment with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.toString('utf8'); + } + porCommitment$1.decode = decode$4; + function encode$4(data) { + const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + return { + key, + value: Buffer$k.from(data, 'utf8'), + }; + } + porCommitment$1.encode = encode$4; + porCommitment$1.expected = 'string'; + function check$g(data) { + return typeof data === 'string'; + } + porCommitment$1.check = check$g; + function canAdd$2(currentData, newData) { + return !!currentData && !!newData && currentData.porCommitment === undefined; + } + porCommitment$1.canAdd = canAdd$2; + + var sighashType$1 = {}; + + Object.defineProperty(sighashType$1, '__esModule', { value: true }); + const typeFields_1$4 = typeFields; + function decode$3(keyVal) { + if (keyVal.key[0] !== typeFields_1$4.InputTypes.SIGHASH_TYPE) { + throw new Error( + 'Decode Error: could not decode sighashType with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value.readUInt32LE(0); + } + sighashType$1.decode = decode$3; + function encode$3(data) { + const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$k.allocUnsafe(4); + value.writeUInt32LE(data, 0); + return { + key, + value, + }; + } + sighashType$1.encode = encode$3; + sighashType$1.expected = 'number'; + function check$f(data) { + return typeof data === 'number'; + } + sighashType$1.check = check$f; + function canAdd$1(currentData, newData) { + return !!currentData && !!newData && currentData.sighashType === undefined; + } + sighashType$1.canAdd = canAdd$1; + + var witnessUtxo$1 = {}; + + var tools = {}; + + var varint$1 = {}; + + Object.defineProperty(varint$1, '__esModule', { value: true }); + // Number.MAX_SAFE_INTEGER + const MAX_SAFE_INTEGER$2 = 9007199254740991; + function checkUInt53(n) { + if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) + throw new RangeError('value out of range'); + } + function encode$2(_number, buffer, offset) { + checkUInt53(_number); + if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + // 8 bit + if (_number < 0xfd) { + buffer.writeUInt8(_number, offset); + Object.assign(encode$2, { bytes: 1 }); + // 16 bit + } else if (_number <= 0xffff) { + buffer.writeUInt8(0xfd, offset); + buffer.writeUInt16LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 3 }); + // 32 bit + } else if (_number <= 0xffffffff) { + buffer.writeUInt8(0xfe, offset); + buffer.writeUInt32LE(_number, offset + 1); + Object.assign(encode$2, { bytes: 5 }); + // 64 bit + } else { + buffer.writeUInt8(0xff, offset); + buffer.writeUInt32LE(_number >>> 0, offset + 1); + buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); + Object.assign(encode$2, { bytes: 9 }); + } + return buffer; + } + varint$1.encode = encode$2; + function decode$2(buffer, offset) { + if (!isBuffer(buffer)) + throw new TypeError('buffer must be a Buffer instance'); + if (!offset) offset = 0; + const first = buffer.readUInt8(offset); + // 8 bit + if (first < 0xfd) { + Object.assign(decode$2, { bytes: 1 }); + return first; + // 16 bit + } else if (first === 0xfd) { + Object.assign(decode$2, { bytes: 3 }); + return buffer.readUInt16LE(offset + 1); + // 32 bit + } else if (first === 0xfe) { + Object.assign(decode$2, { bytes: 5 }); + return buffer.readUInt32LE(offset + 1); + // 64 bit + } else { + Object.assign(decode$2, { bytes: 9 }); + const lo = buffer.readUInt32LE(offset + 1); + const hi = buffer.readUInt32LE(offset + 5); + const _number = hi * 0x0100000000 + lo; + checkUInt53(_number); + return _number; + } + } + varint$1.decode = decode$2; + function encodingLength(_number) { + checkUInt53(_number); + return _number < 0xfd + ? 1 + : _number <= 0xffff + ? 3 + : _number <= 0xffffffff + ? 5 + : 9; + } + varint$1.encodingLength = encodingLength; + + Object.defineProperty(tools, '__esModule', { value: true }); + const varuint$3 = varint$1; + tools.range = n => [...Array(n).keys()]; + function reverseBuffer(buffer) { + if (buffer.length < 1) return buffer; + let j = buffer.length - 1; + let tmp = 0; + for (let i = 0; i < buffer.length / 2; i++) { + tmp = buffer[i]; + buffer[i] = buffer[j]; + buffer[j] = tmp; + j--; + } + return buffer; + } + tools.reverseBuffer = reverseBuffer; + function keyValsToBuffer(keyVals) { + const buffers = keyVals.map(keyValToBuffer); + buffers.push(Buffer$k.from([0])); + return Buffer$k.concat(buffers); + } + tools.keyValsToBuffer = keyValsToBuffer; + function keyValToBuffer(keyVal) { + const keyLen = keyVal.key.length; + const valLen = keyVal.value.length; + const keyVarIntLen = varuint$3.encodingLength(keyLen); + const valVarIntLen = varuint$3.encodingLength(valLen); + const buffer = Buffer$k.allocUnsafe( + keyVarIntLen + keyLen + valVarIntLen + valLen, + ); + varuint$3.encode(keyLen, buffer, 0); + keyVal.key.copy(buffer, keyVarIntLen); + varuint$3.encode(valLen, buffer, keyVarIntLen + keyLen); + keyVal.value.copy(buffer, keyVarIntLen + keyLen + valVarIntLen); + return buffer; + } + tools.keyValToBuffer = keyValToBuffer; + // https://github.com/feross/buffer/blob/master/index.js#L1127 + function verifuint(value, max) { + if (typeof value !== 'number') + throw new Error('cannot write a non-number as a number'); + if (value < 0) + throw new Error('specified a negative value for writing an unsigned value'); + if (value > max) throw new Error('RangeError: value out of range'); + if (Math.floor(value) !== value) + throw new Error('value has a fractional component'); + } + function readUInt64LE(buffer, offset) { + const a = buffer.readUInt32LE(offset); + let b = buffer.readUInt32LE(offset + 4); + b *= 0x100000000; + verifuint(b + a, 0x001fffffffffffff); + return b + a; + } + tools.readUInt64LE = readUInt64LE; + function writeUInt64LE(buffer, value, offset) { + verifuint(value, 0x001fffffffffffff); + buffer.writeInt32LE(value & -1, offset); + buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4); + return offset + 8; + } + tools.writeUInt64LE = writeUInt64LE; + + Object.defineProperty(witnessUtxo$1, '__esModule', { value: true }); + const typeFields_1$3 = typeFields; + const tools_1$2 = tools; + const varuint$2 = varint$1; + function decode$1(keyVal) { + if (keyVal.key[0] !== typeFields_1$3.InputTypes.WITNESS_UTXO) { + throw new Error( + 'Decode Error: could not decode witnessUtxo with key 0x' + + keyVal.key.toString('hex'), + ); + } + const value = tools_1$2.readUInt64LE(keyVal.value, 0); + let _offset = 8; + const scriptLen = varuint$2.decode(keyVal.value, _offset); + _offset += varuint$2.encodingLength(scriptLen); + const script = keyVal.value.slice(_offset); + if (script.length !== scriptLen) { + throw new Error('Decode Error: WITNESS_UTXO script is not proper length'); + } + return { + script, + value, + }; + } + witnessUtxo$1.decode = decode$1; + function encode$1(data) { + const { script, value } = data; + const varintLen = varuint$2.encodingLength(script.length); + const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); + tools_1$2.writeUInt64LE(result, value, 0); + varuint$2.encode(script.length, result, 8); + script.copy(result, 8 + varintLen); + return { + key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + value: result, + }; + } + witnessUtxo$1.encode = encode$1; + witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; + function check$e(data) { + return isBuffer(data.script) && typeof data.value === 'number'; + } + witnessUtxo$1.check = check$e; + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.witnessUtxo === undefined; + } + witnessUtxo$1.canAdd = canAdd; + + var bip32Derivation$1 = {}; + + Object.defineProperty(bip32Derivation$1, '__esModule', { value: true }); + const range$2 = n => [...Array(n).keys()]; + function makeConverter$2(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode bip32Derivation with key 0x' + + keyVal.key.toString('hex'), + ); + } + if ( + !(keyVal.key.length === 34 || keyVal.key.length === 66) || + ![2, 3, 4].includes(keyVal.key[1]) + ) { + throw new Error( + 'Decode Error: bip32Derivation has invalid pubkey in key 0x' + + keyVal.key.toString('hex'), + ); + } + if ((keyVal.value.length / 4) % 1 !== 0) { + throw new Error( + 'Decode Error: Input BIP32_DERIVATION value length should be multiple of 4', + ); + } + const pubkey = keyVal.key.slice(1); + const data = { + masterFingerprint: keyVal.value.slice(0, 4), + pubkey, + path: 'm', + }; + for (const i of range$2(keyVal.value.length / 4 - 1)) { + const val = keyVal.value.readUInt32LE(i * 4 + 4); + const isHard = !!(val & 0x80000000); + const idx = val & 0x7fffffff; + data.path += '/' + idx.toString(10) + (isHard ? "'" : ''); + } + return data; + } + function encode(data) { + const head = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$k.concat([head, data.pubkey]); + const splitPath = data.path.split('/'); + const value = Buffer$k.allocUnsafe(splitPath.length * 4); + data.masterFingerprint.copy(value, 0); + let offset = 4; + splitPath.slice(1).forEach(level => { + const isHard = level.slice(-1) === "'"; + let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10); + if (isHard) num += 0x80000000; + value.writeUInt32LE(num, offset); + offset += 4; + }); + return { + key, + value, + }; + } + const expected = + '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; + function check(data) { + return ( + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && + typeof data.path === 'string' && + [33, 65].includes(data.pubkey.length) && + [2, 3, 4].includes(data.pubkey[0]) && + data.masterFingerprint.length === 4 + ); + } + function canAddToArray(array, item, dupeSet) { + const dupeString = item.pubkey.toString('hex'); + if (dupeSet.has(dupeString)) return false; + dupeSet.add(dupeString); + return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0; + } + return { + decode, + encode, + check, + expected, + canAddToArray, + }; + } + bip32Derivation$1.makeConverter = makeConverter$2; + + var checkPubkey$1 = {}; + + Object.defineProperty(checkPubkey$1, '__esModule', { value: true }); + function makeChecker(pubkeyTypes) { + return checkPubkey; + function checkPubkey(keyVal) { + let pubkey; + if (pubkeyTypes.includes(keyVal.key[0])) { + pubkey = keyVal.key.slice(1); + if ( + !(pubkey.length === 33 || pubkey.length === 65) || + ![2, 3, 4].includes(pubkey[0]) + ) { + throw new Error( + 'Format Error: invalid pubkey in key 0x' + keyVal.key.toString('hex'), + ); + } + } + return pubkey; + } + } + checkPubkey$1.makeChecker = makeChecker; + + var redeemScript$1 = {}; + + Object.defineProperty(redeemScript$1, '__esModule', { value: true }); + function makeConverter$1(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode redeemScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$k.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return !!currentData && !!newData && currentData.redeemScript === undefined; + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + redeemScript$1.makeConverter = makeConverter$1; + + var witnessScript$1 = {}; + + Object.defineProperty(witnessScript$1, '__esModule', { value: true }); + function makeConverter(TYPE_BYTE) { + function decode(keyVal) { + if (keyVal.key[0] !== TYPE_BYTE) { + throw new Error( + 'Decode Error: could not decode witnessScript with key 0x' + + keyVal.key.toString('hex'), + ); + } + return keyVal.value; + } + function encode(data) { + const key = Buffer$k.from([TYPE_BYTE]); + return { + key, + value: data, + }; + } + const expected = 'Buffer'; + function check(data) { + return isBuffer(data); + } + function canAdd(currentData, newData) { + return ( + !!currentData && !!newData && currentData.witnessScript === undefined + ); + } + return { + decode, + encode, + check, + expected, + canAdd, + }; + } + witnessScript$1.makeConverter = makeConverter; + + Object.defineProperty(converter, '__esModule', { value: true }); + const typeFields_1$2 = typeFields; + const globalXpub = globalXpub$1; + const unsignedTx = unsignedTx$1; + const finalScriptSig = finalScriptSig$1; + const finalScriptWitness = finalScriptWitness$1; + const nonWitnessUtxo = nonWitnessUtxo$1; + const partialSig = partialSig$1; + const porCommitment = porCommitment$1; + const sighashType = sighashType$1; + const witnessUtxo = witnessUtxo$1; + const bip32Derivation = bip32Derivation$1; + const checkPubkey = checkPubkey$1; + const redeemScript = redeemScript$1; + const witnessScript = witnessScript$1; + const globals = { + unsignedTx, + globalXpub, + // pass an Array of key bytes that require pubkey beside the key + checkPubkey: checkPubkey.makeChecker([]), + }; + converter.globals = globals; + const inputs = { + nonWitnessUtxo, + partialSig, + sighashType, + finalScriptSig, + finalScriptWitness, + porCommitment, + witnessUtxo, + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.InputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.InputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.InputTypes.PARTIAL_SIG, + typeFields_1$2.InputTypes.BIP32_DERIVATION, + ]), + }; + converter.inputs = inputs; + const outputs = { + bip32Derivation: bip32Derivation.makeConverter( + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ), + redeemScript: redeemScript.makeConverter( + typeFields_1$2.OutputTypes.REDEEM_SCRIPT, + ), + witnessScript: witnessScript.makeConverter( + typeFields_1$2.OutputTypes.WITNESS_SCRIPT, + ), + checkPubkey: checkPubkey.makeChecker([ + typeFields_1$2.OutputTypes.BIP32_DERIVATION, + ]), + }; + converter.outputs = outputs; + + Object.defineProperty(fromBuffer, '__esModule', { value: true }); + const convert$1 = converter; + const tools_1$1 = tools; + const varuint$1 = varint$1; + const typeFields_1$1 = typeFields; + function psbtFromBuffer(buffer, txGetter) { + let offset = 0; + function varSlice() { + const keyLen = varuint$1.decode(buffer, offset); + offset += varuint$1.encodingLength(keyLen); + const key = buffer.slice(offset, offset + keyLen); + offset += keyLen; + return key; + } + function readUInt32BE() { + const num = buffer.readUInt32BE(offset); + offset += 4; + return num; + } + function readUInt8() { + const num = buffer.readUInt8(offset); + offset += 1; + return num; + } + function getKeyValue() { + const key = varSlice(); + const value = varSlice(); + return { + key, + value, + }; + } + function checkEndOfKeyValPairs() { + if (offset >= buffer.length) { + throw new Error('Format Error: Unexpected End of PSBT'); + } + const isEnd = buffer.readUInt8(offset) === 0; + if (isEnd) { + offset++; + } + return isEnd; + } + if (readUInt32BE() !== 0x70736274) { + throw new Error('Format Error: Invalid Magic Number'); + } + if (readUInt8() !== 0xff) { + throw new Error( + 'Format Error: Magic Number must be followed by 0xff separator', + ); + } + const globalMapKeyVals = []; + const globalKeyIndex = {}; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (globalKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for global keymap: key ' + hexKey, + ); + } + globalKeyIndex[hexKey] = 1; + globalMapKeyVals.push(keyVal); + } + const unsignedTxMaps = globalMapKeyVals.filter( + keyVal => keyVal.key[0] === typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (unsignedTxMaps.length !== 1) { + throw new Error('Format Error: Only one UNSIGNED_TX allowed'); + } + const unsignedTx = txGetter(unsignedTxMaps[0].value); + // Get input and output counts to loop the respective fields + const { inputCount, outputCount } = unsignedTx.getInputOutputCounts(); + const inputKeyVals = []; + const outputKeyVals = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const inputKeyIndex = {}; + const input = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (inputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each input: ' + + 'input index ' + + index + + ' key ' + + hexKey, + ); + } + inputKeyIndex[hexKey] = 1; + input.push(keyVal); + } + inputKeyVals.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const outputKeyIndex = {}; + const output = []; + while (!checkEndOfKeyValPairs()) { + const keyVal = getKeyValue(); + const hexKey = keyVal.key.toString('hex'); + if (outputKeyIndex[hexKey]) { + throw new Error( + 'Format Error: Keys must be unique for each output: ' + + 'output index ' + + index + + ' key ' + + hexKey, + ); + } + outputKeyIndex[hexKey] = 1; + output.push(keyVal); + } + outputKeyVals.push(output); + } + return psbtFromKeyVals(unsignedTx, { + globalMapKeyVals, + inputKeyVals, + outputKeyVals, + }); + } + fromBuffer.psbtFromBuffer = psbtFromBuffer; + function checkKeyBuffer(type, keyBuf, keyNum) { + if (!keyBuf.equals(Buffer$k.from([keyNum]))) { + throw new Error( + `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, + ); + } + } + fromBuffer.checkKeyBuffer = checkKeyBuffer; + function psbtFromKeyVals( + unsignedTx, + { globalMapKeyVals, inputKeyVals, outputKeyVals }, + ) { + // That was easy :-) + const globalMap = { + unsignedTx, + }; + let txCount = 0; + for (const keyVal of globalMapKeyVals) { + // If a globalMap item needs pubkey, uncomment + // const pubkey = convert.globals.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.GlobalTypes.UNSIGNED_TX: + checkKeyBuffer( + 'global', + keyVal.key, + typeFields_1$1.GlobalTypes.UNSIGNED_TX, + ); + if (txCount > 0) { + throw new Error('Format Error: GlobalMap has multiple UNSIGNED_TX'); + } + txCount++; + break; + case typeFields_1$1.GlobalTypes.GLOBAL_XPUB: + if (globalMap.globalXpub === undefined) { + globalMap.globalXpub = []; + } + globalMap.globalXpub.push(convert$1.globals.globalXpub.decode(keyVal)); + break; + default: + // This will allow inclusion during serialization. + if (!globalMap.unknownKeyVals) globalMap.unknownKeyVals = []; + globalMap.unknownKeyVals.push(keyVal); + } + } + // Get input and output counts to loop the respective fields + const inputCount = inputKeyVals.length; + const outputCount = outputKeyVals.length; + const inputs = []; + const outputs = []; + // Get input fields + for (const index of tools_1$1.range(inputCount)) { + const input = {}; + for (const keyVal of inputKeyVals[index]) { + convert$1.inputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.InputTypes.NON_WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.NON_WITNESS_UTXO, + ); + if (input.nonWitnessUtxo !== undefined) { + throw new Error( + 'Format Error: Input has multiple NON_WITNESS_UTXO', + ); + } + input.nonWitnessUtxo = convert$1.inputs.nonWitnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_UTXO: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_UTXO, + ); + if (input.witnessUtxo !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_UTXO'); + } + input.witnessUtxo = convert$1.inputs.witnessUtxo.decode(keyVal); + break; + case typeFields_1$1.InputTypes.PARTIAL_SIG: + if (input.partialSig === undefined) { + input.partialSig = []; + } + input.partialSig.push(convert$1.inputs.partialSig.decode(keyVal)); + break; + case typeFields_1$1.InputTypes.SIGHASH_TYPE: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.SIGHASH_TYPE, + ); + if (input.sighashType !== undefined) { + throw new Error('Format Error: Input has multiple SIGHASH_TYPE'); + } + input.sighashType = convert$1.inputs.sighashType.decode(keyVal); + break; + case typeFields_1$1.InputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.REDEEM_SCRIPT, + ); + if (input.redeemScript !== undefined) { + throw new Error('Format Error: Input has multiple REDEEM_SCRIPT'); + } + input.redeemScript = convert$1.inputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.WITNESS_SCRIPT, + ); + if (input.witnessScript !== undefined) { + throw new Error('Format Error: Input has multiple WITNESS_SCRIPT'); + } + input.witnessScript = convert$1.inputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.InputTypes.BIP32_DERIVATION: + if (input.bip32Derivation === undefined) { + input.bip32Derivation = []; + } + input.bip32Derivation.push( + convert$1.inputs.bip32Derivation.decode(keyVal), + ); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTSIG: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTSIG, + ); + input.finalScriptSig = convert$1.inputs.finalScriptSig.decode(keyVal); + break; + case typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.FINAL_SCRIPTWITNESS, + ); + input.finalScriptWitness = convert$1.inputs.finalScriptWitness.decode( + keyVal, + ); + break; + case typeFields_1$1.InputTypes.POR_COMMITMENT: + checkKeyBuffer( + 'input', + keyVal.key, + typeFields_1$1.InputTypes.POR_COMMITMENT, + ); + input.porCommitment = convert$1.inputs.porCommitment.decode(keyVal); + break; + default: + // This will allow inclusion during serialization. + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + } + } + inputs.push(input); + } + for (const index of tools_1$1.range(outputCount)) { + const output = {}; + for (const keyVal of outputKeyVals[index]) { + convert$1.outputs.checkPubkey(keyVal); + switch (keyVal.key[0]) { + case typeFields_1$1.OutputTypes.REDEEM_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.REDEEM_SCRIPT, + ); + if (output.redeemScript !== undefined) { + throw new Error('Format Error: Output has multiple REDEEM_SCRIPT'); + } + output.redeemScript = convert$1.outputs.redeemScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.WITNESS_SCRIPT: + checkKeyBuffer( + 'output', + keyVal.key, + typeFields_1$1.OutputTypes.WITNESS_SCRIPT, + ); + if (output.witnessScript !== undefined) { + throw new Error('Format Error: Output has multiple WITNESS_SCRIPT'); + } + output.witnessScript = convert$1.outputs.witnessScript.decode(keyVal); + break; + case typeFields_1$1.OutputTypes.BIP32_DERIVATION: + if (output.bip32Derivation === undefined) { + output.bip32Derivation = []; + } + output.bip32Derivation.push( + convert$1.outputs.bip32Derivation.decode(keyVal), + ); + break; + default: + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + } + } + outputs.push(output); + } + return { globalMap, inputs, outputs }; + } + fromBuffer.psbtFromKeyVals = psbtFromKeyVals; + + var toBuffer = {}; + + Object.defineProperty(toBuffer, '__esModule', { value: true }); + const convert = converter; + const tools_1 = tools; + function psbtToBuffer({ globalMap, inputs, outputs }) { + const { globalKeyVals, inputKeyVals, outputKeyVals } = psbtToKeyVals({ + globalMap, + inputs, + outputs, + }); + const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); + const keyValsOrEmptyToBuffer = keyVals => + keyVals.length === 0 + ? [Buffer$k.from([0])] + : keyVals.map(tools_1.keyValsToBuffer); + const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); + const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); + const header = Buffer$k.allocUnsafe(5); + header.writeUIntBE(0x70736274ff, 0, 5); + return Buffer$k.concat( + [header, globalBuffer].concat(inputBuffers, outputBuffers), + ); + } + toBuffer.psbtToBuffer = psbtToBuffer; + const sortKeyVals = (a, b) => { + return a.key.compare(b.key); + }; + function keyValsFromMap(keyValMap, converterFactory) { + const keyHexSet = new Set(); + const keyVals = Object.entries(keyValMap).reduce((result, [key, value]) => { + if (key === 'unknownKeyVals') return result; + // We are checking for undefined anyways. So ignore TS error + // @ts-ignore + const converter = converterFactory[key]; + if (converter === undefined) return result; + const encodedKeyVals = (Array.isArray(value) ? value : [value]).map( + converter.encode, + ); + const keyHexes = encodedKeyVals.map(kv => kv.key.toString('hex')); + keyHexes.forEach(hex => { + if (keyHexSet.has(hex)) + throw new Error('Serialize Error: Duplicate key: ' + hex); + keyHexSet.add(hex); + }); + return result.concat(encodedKeyVals); + }, []); + // Get other keyVals that have not yet been gotten + const otherKeyVals = keyValMap.unknownKeyVals + ? keyValMap.unknownKeyVals.filter(keyVal => { + return !keyHexSet.has(keyVal.key.toString('hex')); + }) + : []; + return keyVals.concat(otherKeyVals).sort(sortKeyVals); + } + function psbtToKeyVals({ globalMap, inputs, outputs }) { + // First parse the global keyVals + // Get any extra keyvals to pass along + return { + globalKeyVals: keyValsFromMap(globalMap, convert.globals), + inputKeyVals: inputs.map(i => keyValsFromMap(i, convert.inputs)), + outputKeyVals: outputs.map(o => keyValsFromMap(o, convert.outputs)), + }; + } + toBuffer.psbtToKeyVals = psbtToKeyVals; + + (function (exports) { + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, '__esModule', { value: true }); + __export(fromBuffer); + __export(toBuffer); + }(parser)); + + Object.defineProperty(combiner, '__esModule', { value: true }); + const parser_1$1 = parser; + function combine(psbts) { + const self = psbts[0]; + const selfKeyVals = parser_1$1.psbtToKeyVals(self); + const others = psbts.slice(1); + if (others.length === 0) throw new Error('Combine: Nothing to combine'); + const selfTx = getTx(self); + if (selfTx === undefined) { + throw new Error('Combine: Self missing transaction'); + } + const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals); + const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet); + const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet); + for (const other of others) { + const otherTx = getTx(other); + if ( + otherTx === undefined || + !otherTx.toBuffer().equals(selfTx.toBuffer()) + ) { + throw new Error( + 'Combine: One of the Psbts does not have the same transaction.', + ); + } + const otherKeyVals = parser_1$1.psbtToKeyVals(other); + const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals); + otherGlobalSet.forEach( + keyPusher( + selfGlobalSet, + selfKeyVals.globalKeyVals, + otherKeyVals.globalKeyVals, + ), + ); + const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet); + otherInputSets.forEach((inputSet, idx) => + inputSet.forEach( + keyPusher( + selfInputSets[idx], + selfKeyVals.inputKeyVals[idx], + otherKeyVals.inputKeyVals[idx], + ), + ), + ); + const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet); + otherOutputSets.forEach((outputSet, idx) => + outputSet.forEach( + keyPusher( + selfOutputSets[idx], + selfKeyVals.outputKeyVals[idx], + otherKeyVals.outputKeyVals[idx], + ), + ), + ); + } + return parser_1$1.psbtFromKeyVals(selfTx, { + globalMapKeyVals: selfKeyVals.globalKeyVals, + inputKeyVals: selfKeyVals.inputKeyVals, + outputKeyVals: selfKeyVals.outputKeyVals, + }); + } + combiner.combine = combine; + function keyPusher(selfSet, selfKeyVals, otherKeyVals) { + return key => { + if (selfSet.has(key)) return; + const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0]; + selfKeyVals.push(newKv); + selfSet.add(key); + }; + } + function getTx(psbt) { + return psbt.globalMap.unsignedTx; + } + function getKeySet(keyVals) { + const set = new Set(); + keyVals.forEach(keyVal => { + const hex = keyVal.key.toString('hex'); + if (set.has(hex)) + throw new Error('Combine: KeyValue Map keys should be unique'); + set.add(hex); + }); + return set; + } + + var utils = {}; + + (function (exports) { + Object.defineProperty(exports, '__esModule', { value: true }); + const converter$1 = converter; + function checkForInput(inputs, inputIndex) { + const input = inputs[inputIndex]; + if (input === undefined) throw new Error(`No input #${inputIndex}`); + return input; + } + exports.checkForInput = checkForInput; + function checkForOutput(outputs, outputIndex) { + const output = outputs[outputIndex]; + if (output === undefined) throw new Error(`No output #${outputIndex}`); + return output; + } + exports.checkForOutput = checkForOutput; + function checkHasKey(checkKeyVal, keyVals, enumLength) { + if (checkKeyVal.key[0] < enumLength) { + throw new Error( + `Use the method for your specific key instead of addUnknownKeyVal*`, + ); + } + if ( + keyVals && + keyVals.filter(kv => kv.key.equals(checkKeyVal.key)).length !== 0 + ) { + throw new Error(`Duplicate Key: ${checkKeyVal.key.toString('hex')}`); + } + } + exports.checkHasKey = checkHasKey; + function getEnumLength(myenum) { + let count = 0; + Object.keys(myenum).forEach(val => { + if (Number(isNaN(Number(val)))) { + count++; + } + }); + return count; + } + exports.getEnumLength = getEnumLength; + function inputCheckUncleanFinalized(inputIndex, input) { + let result = false; + if (input.nonWitnessUtxo || input.witnessUtxo) { + const needScriptSig = !!input.redeemScript; + const needWitnessScript = !!input.witnessScript; + const scriptSigOK = !needScriptSig || !!input.finalScriptSig; + const witnessScriptOK = !needWitnessScript || !!input.finalScriptWitness; + const hasOneFinal = !!input.finalScriptSig || !!input.finalScriptWitness; + result = scriptSigOK && witnessScriptOK && hasOneFinal; + } + if (result === false) { + throw new Error( + `Input #${inputIndex} has too much or too little data to clean`, + ); + } + } + exports.inputCheckUncleanFinalized = inputCheckUncleanFinalized; + function throwForUpdateMaker(typeName, name, expected, data) { + throw new Error( + `Data for ${typeName} key ${name} is incorrect: Expected ` + + `${expected} and got ${JSON.stringify(data)}`, + ); + } + function updateMaker(typeName) { + return (updateData, mainData) => { + for (const name of Object.keys(updateData)) { + // @ts-ignore + const data = updateData[name]; + // @ts-ignore + const { canAdd, canAddToArray, check, expected } = + // @ts-ignore + converter$1[typeName + 's'][name] || {}; + const isArray = !!canAddToArray; + // If unknown data. ignore and do not add + if (check) { + if (isArray) { + if ( + !Array.isArray(data) || + // @ts-ignore + (mainData[name] && !Array.isArray(mainData[name])) + ) { + throw new Error(`Key type ${name} must be an array`); + } + if (!data.every(check)) { + throwForUpdateMaker(typeName, name, expected, data); + } + // @ts-ignore + const arr = mainData[name] || []; + const dupeCheckSet = new Set(); + if (!data.every(v => canAddToArray(arr, v, dupeCheckSet))) { + throw new Error('Can not add duplicate data to array'); + } + // @ts-ignore + mainData[name] = arr.concat(data); + } else { + if (!check(data)) { + throwForUpdateMaker(typeName, name, expected, data); + } + if (!canAdd(mainData, data)) { + throw new Error(`Can not add duplicate data to ${typeName}`); + } + // @ts-ignore + mainData[name] = data; + } + } + } + }; + } + exports.updateGlobal = updateMaker('global'); + exports.updateInput = updateMaker('input'); + exports.updateOutput = updateMaker('output'); + function addInputAttributes(inputs, data) { + const index = inputs.length - 1; + const input = checkForInput(inputs, index); + exports.updateInput(data, input); + } + exports.addInputAttributes = addInputAttributes; + function addOutputAttributes(outputs, data) { + const index = outputs.length - 1; + const output = checkForInput(outputs, index); + exports.updateOutput(data, output); + } + exports.addOutputAttributes = addOutputAttributes; + function defaultVersionSetter(version, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Version: Invalid Transaction'); + } + txBuf.writeUInt32LE(version, 0); + return txBuf; + } + exports.defaultVersionSetter = defaultVersionSetter; + function defaultLocktimeSetter(locktime, txBuf) { + if (!isBuffer(txBuf) || txBuf.length < 4) { + throw new Error('Set Locktime: Invalid Transaction'); + } + txBuf.writeUInt32LE(locktime, txBuf.length - 4); + return txBuf; + } + exports.defaultLocktimeSetter = defaultLocktimeSetter; + }(utils)); + + Object.defineProperty(psbt, '__esModule', { value: true }); + const combiner_1 = combiner; + const parser_1 = parser; + const typeFields_1 = typeFields; + const utils_1$1 = utils; + class Psbt$1 { + constructor(tx) { + this.inputs = []; + this.outputs = []; + this.globalMap = { + unsignedTx: tx, + }; + } + static fromBase64(data, txFromBuffer) { + const buffer = Buffer$k.from(data, 'base64'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromHex(data, txFromBuffer) { + const buffer = Buffer$k.from(data, 'hex'); + return this.fromBuffer(buffer, txFromBuffer); + } + static fromBuffer(buffer, txFromBuffer) { + const results = parser_1.psbtFromBuffer(buffer, txFromBuffer); + const psbt = new this(results.globalMap.unsignedTx); + Object.assign(psbt, results); + return psbt; + } + toBase64() { + const buffer = this.toBuffer(); + return buffer.toString('base64'); + } + toHex() { + const buffer = this.toBuffer(); + return buffer.toString('hex'); + } + toBuffer() { + return parser_1.psbtToBuffer(this); + } + updateGlobal(updateData) { + utils_1$1.updateGlobal(updateData, this.globalMap); + return this; + } + updateInput(inputIndex, updateData) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.updateInput(updateData, input); + return this; + } + updateOutput(outputIndex, updateData) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.updateOutput(updateData, output); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + utils_1$1.checkHasKey( + keyVal, + this.globalMap.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.GlobalTypes), + ); + if (!this.globalMap.unknownKeyVals) this.globalMap.unknownKeyVals = []; + this.globalMap.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.checkHasKey( + keyVal, + input.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.InputTypes), + ); + if (!input.unknownKeyVals) input.unknownKeyVals = []; + input.unknownKeyVals.push(keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + const output = utils_1$1.checkForOutput(this.outputs, outputIndex); + utils_1$1.checkHasKey( + keyVal, + output.unknownKeyVals, + utils_1$1.getEnumLength(typeFields_1.OutputTypes), + ); + if (!output.unknownKeyVals) output.unknownKeyVals = []; + output.unknownKeyVals.push(keyVal); + return this; + } + addInput(inputData) { + this.globalMap.unsignedTx.addInput(inputData); + this.inputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = inputData.unknownKeyVals || []; + const inputIndex = this.inputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(inputIndex, keyVal), + ); + utils_1$1.addInputAttributes(this.inputs, inputData); + return this; + } + addOutput(outputData) { + this.globalMap.unsignedTx.addOutput(outputData); + this.outputs.push({ + unknownKeyVals: [], + }); + const addKeyVals = outputData.unknownKeyVals || []; + const outputIndex = this.outputs.length - 1; + if (!Array.isArray(addKeyVals)) { + throw new Error('unknownKeyVals must be an Array'); + } + addKeyVals.forEach(keyVal => + this.addUnknownKeyValToInput(outputIndex, keyVal), + ); + utils_1$1.addOutputAttributes(this.outputs, outputData); + return this; + } + clearFinalizedInput(inputIndex) { + const input = utils_1$1.checkForInput(this.inputs, inputIndex); + utils_1$1.inputCheckUncleanFinalized(inputIndex, input); + for (const key of Object.keys(input)) { + if ( + ![ + 'witnessUtxo', + 'nonWitnessUtxo', + 'finalScriptSig', + 'finalScriptWitness', + 'unknownKeyVals', + ].includes(key) + ) { + // @ts-ignore + delete input[key]; + } + } + return this; + } + combine(...those) { + // Combine this with those. + // Return self for chaining. + const result = combiner_1.combine([this].concat(those)); + Object.assign(this, result); + return this; + } + getTransaction() { + return this.globalMap.unsignedTx.toBuffer(); + } + } + psbt.Psbt = Psbt$1; + + Object.defineProperty(psbt$1, '__esModule', { value: true }); + const bip174_1 = psbt; + const varuint = varint$1; + const utils_1 = utils; + const address_1 = address$1; + const bufferutils_1$1 = bufferutils; + const crypto_1$1 = crypto$2; + const ecpair_1 = ecpair; + const networks_1 = networks$3; + const payments$2 = payments$4; + const bscript$f = script$1; + const transaction_1$2 = transaction; + /** + * These are the default arguments for a Psbt instance. + */ + const DEFAULT_OPTS = { + /** + * A bitcoinjs Network object. This is only used if you pass an `address` + * parameter to addOutput. Otherwise it is not needed and can be left default. + */ + network: networks_1.bitcoin, + /** + * When extractTransaction is called, the fee rate is checked. + * THIS IS NOT TO BE RELIED ON. + * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc. + */ + maximumFeeRate: 5000, + }; + /** + * Psbt class can parse and generate a PSBT binary based off of the BIP174. + * There are 6 roles that this class fulfills. (Explained in BIP174) + * + * Creator: This can be done with `new Psbt()` + * Updater: This can be done with `psbt.addInput(input)`, `psbt.addInputs(inputs)`, + * `psbt.addOutput(output)`, `psbt.addOutputs(outputs)` when you are looking to + * add new inputs and outputs to the PSBT, and `psbt.updateGlobal(itemObject)`, + * `psbt.updateInput(itemObject)`, `psbt.updateOutput(itemObject)` + * addInput requires hash: Buffer | string; and index: number; as attributes + * and can also include any attributes that are used in updateInput method. + * addOutput requires script: Buffer; and value: number; and likewise can include + * data for updateOutput. + * For a list of what attributes should be what types. Check the bip174 library. + * Also, check the integration tests for some examples of usage. + * Signer: There are a few methods. signAllInputs and signAllInputsAsync, which will search all input + * information for your pubkey or pubkeyhash, and only sign inputs where it finds + * your info. Or you can explicitly sign a specific input with signInput and + * signInputAsync. For the async methods you can create a SignerAsync object + * and use something like a hardware wallet to sign with. (You must implement this) + * Combiner: psbts can be combined easily with `psbt.combine(psbt2, psbt3, psbt4 ...)` + * the psbt calling combine will always have precedence when a conflict occurs. + * Combine checks if the internal bitcoin transaction is the same, so be sure that + * all sequences, version, locktime, etc. are the same before combining. + * Input Finalizer: This role is fairly important. Not only does it need to construct + * the input scriptSigs and witnesses, but it SHOULD verify the signatures etc. + * Before running `psbt.finalizeAllInputs()` please run `psbt.validateSignaturesOfAllInputs()` + * Running any finalize method will delete any data in the input(s) that are no longer + * needed due to the finalized scripts containing the information. + * Transaction Extractor: This role will perform some checks before returning a + * Transaction object. Such as fee rate not being larger than maximumFeeRate etc. + */ + class Psbt { + constructor(opts = {}, data = new bip174_1.Psbt(new PsbtTransaction())) { + this.data = data; + // set defaults + this.opts = Object.assign({}, DEFAULT_OPTS, opts); + this.__CACHE = { + __NON_WITNESS_UTXO_TX_CACHE: [], + __NON_WITNESS_UTXO_BUF_CACHE: [], + __TX_IN_CACHE: {}, + __TX: this.data.globalMap.unsignedTx.tx, + // Old TransactionBuilder behavior was to not confirm input values + // before signing. Even though we highly encourage people to get + // the full parent transaction to verify values, the ability to + // sign non-segwit inputs without the full transaction was often + // requested. So the only way to activate is to use @ts-ignore. + // We will disable exporting the Psbt when unsafe sign is active. + // because it is not BIP174 compliant. + __UNSAFE_SIGN_NONSEGWIT: false, + }; + if (this.data.inputs.length === 0) this.setVersion(2); + // Make data hidden when enumerating + const dpew = (obj, attr, enumerable, writable) => + Object.defineProperty(obj, attr, { + enumerable, + writable, + }); + dpew(this, '__CACHE', false, true); + dpew(this, 'opts', false, true); + } + static fromBase64(data, opts = {}) { + const buffer = Buffer$k.from(data, 'base64'); + return this.fromBuffer(buffer, opts); + } + static fromHex(data, opts = {}) { + const buffer = Buffer$k.from(data, 'hex'); + return this.fromBuffer(buffer, opts); + } + static fromBuffer(buffer, opts = {}) { + const psbtBase = bip174_1.Psbt.fromBuffer(buffer, transactionFromBuffer); + const psbt = new Psbt(opts, psbtBase); + checkTxForDupeIns(psbt.__CACHE.__TX, psbt.__CACHE); + return psbt; + } + get inputCount() { + return this.data.inputs.length; + } + get version() { + return this.__CACHE.__TX.version; + } + set version(version) { + this.setVersion(version); + } + get locktime() { + return this.__CACHE.__TX.locktime; + } + set locktime(locktime) { + this.setLocktime(locktime); + } + get txInputs() { + return this.__CACHE.__TX.ins.map(input => ({ + hash: bufferutils_1$1.cloneBuffer(input.hash), + index: input.index, + sequence: input.sequence, + })); + } + get txOutputs() { + return this.__CACHE.__TX.outs.map(output => { + let address; + try { + address = address_1.fromOutputScript(output.script, this.opts.network); + } catch (_) {} + return { + script: bufferutils_1$1.cloneBuffer(output.script), + value: output.value, + address, + }; + }); + } + combine(...those) { + this.data.combine(...those.map(o => o.data)); + return this; + } + clone() { + // TODO: more efficient cloning + const res = Psbt.fromBuffer(this.data.toBuffer()); + res.opts = JSON.parse(JSON.stringify(this.opts)); + return res; + } + setMaximumFeeRate(satoshiPerByte) { + check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw + this.opts.maximumFeeRate = satoshiPerByte; + } + setVersion(version) { + check32Bit(version); + checkInputsForPartialSig(this.data.inputs, 'setVersion'); + const c = this.__CACHE; + c.__TX.version = version; + c.__EXTRACTED_TX = undefined; + return this; + } + setLocktime(locktime) { + check32Bit(locktime); + checkInputsForPartialSig(this.data.inputs, 'setLocktime'); + const c = this.__CACHE; + c.__TX.locktime = locktime; + c.__EXTRACTED_TX = undefined; + return this; + } + setInputSequence(inputIndex, sequence) { + check32Bit(sequence); + checkInputsForPartialSig(this.data.inputs, 'setInputSequence'); + const c = this.__CACHE; + if (c.__TX.ins.length <= inputIndex) { + throw new Error('Input index too high'); + } + c.__TX.ins[inputIndex].sequence = sequence; + c.__EXTRACTED_TX = undefined; + return this; + } + addInputs(inputDatas) { + inputDatas.forEach(inputData => this.addInput(inputData)); + return this; + } + addInput(inputData) { + if ( + arguments.length > 1 || + !inputData || + inputData.hash === undefined || + inputData.index === undefined + ) { + throw new Error( + `Invalid arguments for Psbt.addInput. ` + + `Requires single object with at least [hash] and [index]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addInput'); + if (inputData.witnessScript) checkInvalidP2WSH(inputData.witnessScript); + const c = this.__CACHE; + this.data.addInput(inputData); + const txIn = c.__TX.ins[c.__TX.ins.length - 1]; + checkTxInputCache(c, txIn); + const inputIndex = this.data.inputs.length - 1; + const input = this.data.inputs[inputIndex]; + if (input.nonWitnessUtxo) { + addNonWitnessTxCache(this.__CACHE, input, inputIndex); + } + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + addOutputs(outputDatas) { + outputDatas.forEach(outputData => this.addOutput(outputData)); + return this; + } + addOutput(outputData) { + if ( + arguments.length > 1 || + !outputData || + outputData.value === undefined || + (outputData.address === undefined && outputData.script === undefined) + ) { + throw new Error( + `Invalid arguments for Psbt.addOutput. ` + + `Requires single object with at least [script or address] and [value]`, + ); + } + checkInputsForPartialSig(this.data.inputs, 'addOutput'); + const { address } = outputData; + if (typeof address === 'string') { + const { network } = this.opts; + const script = address_1.toOutputScript(address, network); + outputData = Object.assign(outputData, { script }); + } + const c = this.__CACHE; + this.data.addOutput(outputData); + c.__FEE = undefined; + c.__FEE_RATE = undefined; + c.__EXTRACTED_TX = undefined; + return this; + } + extractTransaction(disableFeeCheck) { + if (!this.data.inputs.every(isFinalized)) throw new Error('Not finalized'); + const c = this.__CACHE; + if (!disableFeeCheck) { + checkFees(this, c, this.opts); + } + if (c.__EXTRACTED_TX) return c.__EXTRACTED_TX; + const tx = c.__TX.clone(); + inputFinalizeGetAmts(this.data.inputs, tx, c, true); + return tx; + } + getFeeRate() { + return getTxCacheValue( + '__FEE_RATE', + 'fee rate', + this.data.inputs, + this.__CACHE, + ); + } + getFee() { + return getTxCacheValue('__FEE', 'fee', this.data.inputs, this.__CACHE); + } + finalizeAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + range$1(this.data.inputs.length).forEach(idx => this.finalizeInput(idx)); + return this; + } + finalizeInput(inputIndex, finalScriptsFunc = getFinalScripts) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput( + inputIndex, + input, + this.__CACHE, + ); + if (!script) throw new Error(`No script found for input #${inputIndex}`); + checkPartialSigSighashes(input); + const { finalScriptSig, finalScriptWitness } = finalScriptsFunc( + inputIndex, + input, + script, + isSegwit, + isP2SH, + isP2WSH, + ); + if (finalScriptSig) this.data.updateInput(inputIndex, { finalScriptSig }); + if (finalScriptWitness) + this.data.updateInput(inputIndex, { finalScriptWitness }); + if (!finalScriptSig && !finalScriptWitness) + throw new Error(`Unknown error finalizing input #${inputIndex}`); + this.data.clearFinalizedInput(inputIndex); + return this; + } + getInputType(inputIndex) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const script = getScriptFromUtxo(inputIndex, input, this.__CACHE); + const result = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), + input.witnessScript || + redeemFromFinalWitnessScript(input.finalScriptWitness), + ); + const type = result.type === 'raw' ? '' : result.type + '-'; + const mainType = classifyScript(result.meaningfulScript); + return type + mainType; + } + inputHasPubkey(inputIndex, pubkey) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + return pubkeyInInput(pubkey, input, inputIndex, this.__CACHE); + } + inputHasHDKey(inputIndex, root) { + const input = utils_1.checkForInput(this.data.inputs, inputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine) + ); + } + outputHasPubkey(outputIndex, pubkey) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + return pubkeyInOutput(pubkey, output, outputIndex, this.__CACHE); + } + outputHasHDKey(outputIndex, root) { + const output = utils_1.checkForOutput(this.data.outputs, outputIndex); + const derivationIsMine = bip32DerivationIsMine(root); + return ( + !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine) + ); + } + validateSignaturesOfAllInputs() { + utils_1.checkForInput(this.data.inputs, 0); // making sure we have at least one + const results = range$1(this.data.inputs.length).map(idx => + this.validateSignaturesOfInput(idx), + ); + return results.reduce((final, res) => res === true && final, true); + } + validateSignaturesOfInput(inputIndex, pubkey) { + const input = this.data.inputs[inputIndex]; + const partialSig = (input || {}).partialSig; + if (!input || !partialSig || partialSig.length < 1) + throw new Error('No signatures to validate'); + const mySigs = pubkey + ? partialSig.filter(sig => sig.pubkey.equals(pubkey)) + : partialSig; + if (mySigs.length < 1) throw new Error('No signatures for this pubkey'); + const results = []; + let hashCache; + let scriptCache; + let sighashCache; + for (const pSig of mySigs) { + const sig = bscript$f.signature.decode(pSig.signature); + const { hash, script } = + sighashCache !== sig.hashType + ? getHashForSig( + inputIndex, + Object.assign({}, input, { sighashType: sig.hashType }), + this.__CACHE, + true, + ) + : { hash: hashCache, script: scriptCache }; + sighashCache = sig.hashType; + hashCache = hash; + scriptCache = script; + checkScriptForPubkey(pSig.pubkey, script, 'verify'); + const keypair = ecpair_1.fromPublicKey(pSig.pubkey); + results.push(keypair.verify(hash, sig.signature)); + } + return results.every(res => res === true); + } + signAllInputsHD( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInputHD(i, hdKeyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsHDAsync( + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const results = []; + const promises = []; + for (const i of range$1(this.data.inputs.length)) { + promises.push( + this.signInputHDAsync(i, hdKeyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInputHD( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + throw new Error('Need HDSigner to sign input'); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + signers.forEach(signer => this.signInput(inputIndex, signer, sighashTypes)); + return this; + } + signInputHDAsync( + inputIndex, + hdKeyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) { + return reject(new Error('Need HDSigner to sign input')); + } + const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair); + const promises = signers.map(signer => + this.signInputAsync(inputIndex, signer, sighashTypes), + ); + return Promise.all(promises) + .then(() => { + resolve(); + }) + .catch(reject); + }); + } + signAllInputs( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + for (const i of range$1(this.data.inputs.length)) { + try { + this.signInput(i, keyPair, sighashTypes); + results.push(true); + } catch (err) { + results.push(false); + } + } + if (results.every(v => v === false)) { + throw new Error('No inputs were signed'); + } + return this; + } + signAllInputsAsync( + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return new Promise((resolve, reject) => { + if (!keyPair || !keyPair.publicKey) + return reject(new Error('Need Signer to sign input')); + // TODO: Add a pubkey/pubkeyhash cache to each input + // as input information is added, then eventually + // optimize this method. + const results = []; + const promises = []; + for (const [i] of this.data.inputs.entries()) { + promises.push( + this.signInputAsync(i, keyPair, sighashTypes).then( + () => { + results.push(true); + }, + () => { + results.push(false); + }, + ), + ); + } + return Promise.all(promises).then(() => { + if (results.every(v => v === false)) { + return reject(new Error('No inputs were signed')); + } + resolve(); + }); + }); + } + signInput( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(keyPair.sign(hash), sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + return this; + } + signInputAsync( + inputIndex, + keyPair, + sighashTypes = [transaction_1$2.Transaction.SIGHASH_ALL], + ) { + return Promise.resolve().then(() => { + if (!keyPair || !keyPair.publicKey) + throw new Error('Need Signer to sign input'); + const { hash, sighashType } = getHashAndSighashType( + this.data.inputs, + inputIndex, + keyPair.publicKey, + this.__CACHE, + sighashTypes, + ); + return Promise.resolve(keyPair.sign(hash)).then(signature => { + const partialSig = [ + { + pubkey: keyPair.publicKey, + signature: bscript$f.signature.encode(signature, sighashType), + }, + ]; + this.data.updateInput(inputIndex, { partialSig }); + }); + }); + } + toBuffer() { + checkCache(this.__CACHE); + return this.data.toBuffer(); + } + toHex() { + checkCache(this.__CACHE); + return this.data.toHex(); + } + toBase64() { + checkCache(this.__CACHE); + return this.data.toBase64(); + } + updateGlobal(updateData) { + this.data.updateGlobal(updateData); + return this; + } + updateInput(inputIndex, updateData) { + if (updateData.witnessScript) checkInvalidP2WSH(updateData.witnessScript); + this.data.updateInput(inputIndex, updateData); + if (updateData.nonWitnessUtxo) { + addNonWitnessTxCache( + this.__CACHE, + this.data.inputs[inputIndex], + inputIndex, + ); + } + return this; + } + updateOutput(outputIndex, updateData) { + this.data.updateOutput(outputIndex, updateData); + return this; + } + addUnknownKeyValToGlobal(keyVal) { + this.data.addUnknownKeyValToGlobal(keyVal); + return this; + } + addUnknownKeyValToInput(inputIndex, keyVal) { + this.data.addUnknownKeyValToInput(inputIndex, keyVal); + return this; + } + addUnknownKeyValToOutput(outputIndex, keyVal) { + this.data.addUnknownKeyValToOutput(outputIndex, keyVal); + return this; + } + clearFinalizedInput(inputIndex) { + this.data.clearFinalizedInput(inputIndex); + return this; + } + } + psbt$1.Psbt = Psbt; + /** + * This function is needed to pass to the bip174 base class's fromBuffer. + * It takes the "transaction buffer" portion of the psbt buffer and returns a + * Transaction (From the bip174 library) interface. + */ + const transactionFromBuffer = buffer => new PsbtTransaction(buffer); + /** + * This class implements the Transaction interface from bip174 library. + * It contains a bitcoinjs-lib Transaction object. + */ + class PsbtTransaction { + constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + this.tx = transaction_1$2.Transaction.fromBuffer(buffer); + checkTxEmpty(this.tx); + Object.defineProperty(this, 'tx', { + enumerable: false, + writable: true, + }); + } + getInputOutputCounts() { + return { + inputCount: this.tx.ins.length, + outputCount: this.tx.outs.length, + }; + } + addInput(input) { + if ( + input.hash === undefined || + input.index === undefined || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || + typeof input.index !== 'number' + ) { + throw new Error('Error adding input.'); + } + const hash = + typeof input.hash === 'string' + ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) + : input.hash; + this.tx.addInput(hash, input.index, input.sequence); + } + addOutput(output) { + if ( + output.script === undefined || + output.value === undefined || + !isBuffer(output.script) || + typeof output.value !== 'number' + ) { + throw new Error('Error adding output.'); + } + this.tx.addOutput(output.script, output.value); + } + toBuffer() { + return this.tx.toBuffer(); + } + } + function canFinalize(input, script, scriptType) { + switch (scriptType) { + case 'pubkey': + case 'pubkeyhash': + case 'witnesspubkeyhash': + return hasSigs(1, input.partialSig); + case 'multisig': + const p2ms = payments$2.p2ms({ output: script }); + return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys); + default: + return false; + } + } + function checkCache(cache) { + if (cache.__UNSAFE_SIGN_NONSEGWIT !== false) { + throw new Error('Not BIP174 compliant, can not export'); + } + } + function hasSigs(neededSigs, partialSig, pubkeys) { + if (!partialSig) return false; + let sigs; + if (pubkeys) { + sigs = pubkeys + .map(pkey => { + const pubkey = ecpair_1.fromPublicKey(pkey, { compressed: true }) + .publicKey; + return partialSig.find(pSig => pSig.pubkey.equals(pubkey)); + }) + .filter(v => !!v); + } else { + sigs = partialSig; + } + if (sigs.length > neededSigs) throw new Error('Too many signatures'); + return sigs.length === neededSigs; + } + function isFinalized(input) { + return !!input.finalScriptSig || !!input.finalScriptWitness; + } + function isPaymentFactory(payment) { + return script => { + try { + payment({ output: script }); + return true; + } catch (err) { + return false; + } + }; + } + const isP2MS = isPaymentFactory(payments$2.p2ms); + const isP2PK = isPaymentFactory(payments$2.p2pk); + const isP2PKH = isPaymentFactory(payments$2.p2pkh); + const isP2WPKH = isPaymentFactory(payments$2.p2wpkh); + const isP2WSHScript = isPaymentFactory(payments$2.p2wsh); + const isP2SHScript = isPaymentFactory(payments$2.p2sh); + function bip32DerivationIsMine(root) { + return d => { + if (!d.masterFingerprint.equals(root.fingerprint)) return false; + if (!root.derivePath(d.path).publicKey.equals(d.pubkey)) return false; + return true; + }; + } + function check32Bit(num) { + if ( + typeof num !== 'number' || + num !== Math.floor(num) || + num > 0xffffffff || + num < 0 + ) { + throw new Error('Invalid 32 bit integer'); + } + } + function checkFees(psbt, cache, opts) { + const feeRate = cache.__FEE_RATE || psbt.getFeeRate(); + const vsize = cache.__EXTRACTED_TX.virtualSize(); + const satoshis = feeRate * vsize; + if (feeRate >= opts.maximumFeeRate) { + throw new Error( + `Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` + + `fees, which is ${feeRate} satoshi per byte for a transaction ` + + `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` + + `byte). Use setMaximumFeeRate method to raise your threshold, or ` + + `pass true to the first arg of extractTransaction.`, + ); + } + } + function checkInputsForPartialSig(inputs, action) { + inputs.forEach(input => { + let throws = false; + let pSigs = []; + if ((input.partialSig || []).length === 0) { + if (!input.finalScriptSig && !input.finalScriptWitness) return; + pSigs = getPsigsFromInputFinalScripts(input); + } else { + pSigs = input.partialSig; + } + pSigs.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + const whitelist = []; + const isAnyoneCanPay = + hashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY; + if (isAnyoneCanPay) whitelist.push('addInput'); + const hashMod = hashType & 0x1f; + switch (hashMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + case transaction_1$2.Transaction.SIGHASH_NONE: + whitelist.push('addOutput'); + whitelist.push('setInputSequence'); + break; + } + if (whitelist.indexOf(action) === -1) { + throws = true; + } + }); + if (throws) { + throw new Error('Can not modify transaction, signatures exist.'); + } + }); + } + function checkPartialSigSighashes(input) { + if (!input.sighashType || !input.partialSig) return; + const { partialSig, sighashType } = input; + partialSig.forEach(pSig => { + const { hashType } = bscript$f.signature.decode(pSig.signature); + if (sighashType !== hashType) { + throw new Error('Signature sighash does not match input sighash type'); + } + }); + } + function checkScriptForPubkey(pubkey, script, action) { + if (!pubkeyInScript(pubkey, script)) { + throw new Error( + `Can not ${action} for this input with the key ${pubkey.toString('hex')}`, + ); + } + } + function checkTxEmpty(tx) { + const isEmpty = tx.ins.every( + input => + input.script && + input.script.length === 0 && + input.witness && + input.witness.length === 0, + ); + if (!isEmpty) { + throw new Error('Format Error: Transaction ScriptSigs are not empty'); + } + } + function checkTxForDupeIns(tx, cache) { + tx.ins.forEach(input => { + checkTxInputCache(cache, input); + }); + } + function checkTxInputCache(cache, input) { + const key = + bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + + ':' + + input.index; + if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); + cache.__TX_IN_CACHE[key] = 1; + } + function scriptCheckerFactory(payment, paymentScriptName) { + return (inputIndex, scriptPubKey, redeemScript, ioType) => { + const redeemScriptOutput = payment({ + redeem: { output: redeemScript }, + }).output; + if (!scriptPubKey.equals(redeemScriptOutput)) { + throw new Error( + `${paymentScriptName} for ${ioType} #${inputIndex} doesn't match the scriptPubKey in the prevout`, + ); + } + }; + } + const checkRedeemScript = scriptCheckerFactory(payments$2.p2sh, 'Redeem script'); + const checkWitnessScript = scriptCheckerFactory( + payments$2.p2wsh, + 'Witness script', + ); + function getTxCacheValue(key, name, inputs, c) { + if (!inputs.every(isFinalized)) + throw new Error(`PSBT must be finalized to calculate ${name}`); + if (key === '__FEE_RATE' && c.__FEE_RATE) return c.__FEE_RATE; + if (key === '__FEE' && c.__FEE) return c.__FEE; + let tx; + let mustFinalize = true; + if (c.__EXTRACTED_TX) { + tx = c.__EXTRACTED_TX; + mustFinalize = false; + } else { + tx = c.__TX.clone(); + } + inputFinalizeGetAmts(inputs, tx, c, mustFinalize); + if (key === '__FEE_RATE') return c.__FEE_RATE; + else if (key === '__FEE') return c.__FEE; + } + function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH) { + const scriptType = classifyScript(script); + if (!canFinalize(input, script, scriptType)) + throw new Error(`Can not finalize input #${inputIndex}`); + return prepareFinalScripts( + script, + scriptType, + input.partialSig, + isSegwit, + isP2SH, + isP2WSH, + ); + } + function prepareFinalScripts( + script, + scriptType, + partialSig, + isSegwit, + isP2SH, + isP2WSH, + ) { + let finalScriptSig; + let finalScriptWitness; + // Wow, the payments API is very handy + const payment = getPayment(script, scriptType, partialSig); + const p2wsh = !isP2WSH ? null : payments$2.p2wsh({ redeem: payment }); + const p2sh = !isP2SH ? null : payments$2.p2sh({ redeem: p2wsh || payment }); + if (isSegwit) { + if (p2wsh) { + finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness); + } else { + finalScriptWitness = witnessStackToScriptWitness(payment.witness); + } + if (p2sh) { + finalScriptSig = p2sh.input; + } + } else { + if (p2sh) { + finalScriptSig = p2sh.input; + } else { + finalScriptSig = payment.input; + } + } + return { + finalScriptSig, + finalScriptWitness, + }; + } + function getHashAndSighashType( + inputs, + inputIndex, + pubkey, + cache, + sighashTypes, + ) { + const input = utils_1.checkForInput(inputs, inputIndex); + const { hash, sighashType, script } = getHashForSig( + inputIndex, + input, + cache, + false, + sighashTypes, + ); + checkScriptForPubkey(pubkey, script, 'sign'); + return { + hash, + sighashType, + }; + } + function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) { + const unsignedTx = cache.__TX; + const sighashType = + input.sighashType || transaction_1$2.Transaction.SIGHASH_ALL; + if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) { + const str = sighashTypeToString(sighashType); + throw new Error( + `Sighash type is not allowed. Retry the sign method passing the ` + + `sighashTypes array of whitelisted types. Sighash type: ${str}`, + ); + } + let hash; + let prevout; + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutHash = unsignedTx.ins[inputIndex].hash; + const utxoHash = nonWitnessUtxoTx.getHash(); + // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout + if (!prevoutHash.equals(utxoHash)) { + throw new Error( + `Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`, + ); + } + const prevoutIndex = unsignedTx.ins[inputIndex].index; + prevout = nonWitnessUtxoTx.outs[prevoutIndex]; + } else if (input.witnessUtxo) { + prevout = input.witnessUtxo; + } else { + throw new Error('Need a Utxo input item for signing'); + } + const { meaningfulScript, type } = getMeaningfulScript( + prevout.script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) { + hash = unsignedTx.hashForWitnessV0( + inputIndex, + meaningfulScript, + prevout.value, + sighashType, + ); + } else if (isP2WPKH(meaningfulScript)) { + // P2WPKH uses the P2PKH template for prevoutScript when signing + const signingScript = payments$2.p2pkh({ hash: meaningfulScript.slice(2) }) + .output; + hash = unsignedTx.hashForWitnessV0( + inputIndex, + signingScript, + prevout.value, + sighashType, + ); + } else { + // non-segwit + if ( + input.nonWitnessUtxo === undefined && + cache.__UNSAFE_SIGN_NONSEGWIT === false + ) + throw new Error( + `Input #${inputIndex} has witnessUtxo but non-segwit script: ` + + `${meaningfulScript.toString('hex')}`, + ); + if (!forValidate && cache.__UNSAFE_SIGN_NONSEGWIT !== false) + console.warn( + 'Warning: Signing non-segwit inputs without the full parent transaction ' + + 'means there is a chance that a miner could feed you incorrect information ' + + 'to trick you into paying large fees. This behavior is the same as the old ' + + 'TransactionBuilder class when signing non-segwit scripts. You are not ' + + 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' + + 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' + + '*********************', + ); + hash = unsignedTx.hashForSignature( + inputIndex, + meaningfulScript, + sighashType, + ); + } + return { + script: meaningfulScript, + sighashType, + hash, + }; + } + function getPayment(script, scriptType, partialSig) { + let payment; + switch (scriptType) { + case 'multisig': + const sigs = getSortedSigs(script, partialSig); + payment = payments$2.p2ms({ + output: script, + signatures: sigs, + }); + break; + case 'pubkey': + payment = payments$2.p2pk({ + output: script, + signature: partialSig[0].signature, + }); + break; + case 'pubkeyhash': + payment = payments$2.p2pkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + case 'witnesspubkeyhash': + payment = payments$2.p2wpkh({ + output: script, + pubkey: partialSig[0].pubkey, + signature: partialSig[0].signature, + }); + break; + } + return payment; + } + function getPsigsFromInputFinalScripts(input) { + const scriptItems = !input.finalScriptSig + ? [] + : bscript$f.decompile(input.finalScriptSig) || []; + const witnessItems = !input.finalScriptWitness + ? [] + : bscript$f.decompile(input.finalScriptWitness) || []; + return scriptItems + .concat(witnessItems) + .filter(item => { + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + }) + .map(sig => ({ signature: sig })); + } + function getScriptFromInput(inputIndex, input, cache) { + const unsignedTx = cache.__TX; + const res = { + script: null, + isSegwit: false, + isP2SH: false, + isP2WSH: false, + }; + res.isP2SH = !!input.redeemScript; + res.isP2WSH = !!input.witnessScript; + if (input.witnessScript) { + res.script = input.witnessScript; + } else if (input.redeemScript) { + res.script = input.redeemScript; + } else { + if (input.nonWitnessUtxo) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + const prevoutIndex = unsignedTx.ins[inputIndex].index; + res.script = nonWitnessUtxoTx.outs[prevoutIndex].script; + } else if (input.witnessUtxo) { + res.script = input.witnessUtxo.script; + } + } + if (input.witnessScript || isP2WPKH(res.script)) { + res.isSegwit = true; + } + return res; + } + function getSignersFromHD(inputIndex, inputs, hdKeyPair) { + const input = utils_1.checkForInput(inputs, inputIndex); + if (!input.bip32Derivation || input.bip32Derivation.length === 0) { + throw new Error('Need bip32Derivation to sign with HD'); + } + const myDerivations = input.bip32Derivation + .map(bipDv => { + if (bipDv.masterFingerprint.equals(hdKeyPair.fingerprint)) { + return bipDv; + } else { + return; + } + }) + .filter(v => !!v); + if (myDerivations.length === 0) { + throw new Error( + 'Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint', + ); + } + const signers = myDerivations.map(bipDv => { + const node = hdKeyPair.derivePath(bipDv.path); + if (!bipDv.pubkey.equals(node.publicKey)) { + throw new Error('pubkey did not match bip32Derivation'); + } + return node; + }); + return signers; + } + function getSortedSigs(script, partialSig) { + const p2ms = payments$2.p2ms({ output: script }); + // for each pubkey in order of p2ms script + return p2ms.pubkeys + .map(pk => { + // filter partialSig array by pubkey being equal + return ( + partialSig.filter(ps => { + return ps.pubkey.equals(pk); + })[0] || {} + ).signature; + // Any pubkey without a match will return undefined + // this last filter removes all the undefined items in the array. + }) + .filter(v => !!v); + } + function scriptWitnessToWitnessStack(buffer) { + let offset = 0; + function readSlice(n) { + offset += n; + return buffer.slice(offset - n, offset); + } + function readVarInt() { + const vi = varuint.decode(buffer, offset); + offset += varuint.decode.bytes; + return vi; + } + function readVarSlice() { + return readSlice(readVarInt()); + } + function readVector() { + const count = readVarInt(); + const vector = []; + for (let i = 0; i < count; i++) vector.push(readVarSlice()); + return vector; + } + return readVector(); + } + function sighashTypeToString(sighashType) { + let text = + sighashType & transaction_1$2.Transaction.SIGHASH_ANYONECANPAY + ? 'SIGHASH_ANYONECANPAY | ' + : ''; + const sigMod = sighashType & 0x1f; + switch (sigMod) { + case transaction_1$2.Transaction.SIGHASH_ALL: + text += 'SIGHASH_ALL'; + break; + case transaction_1$2.Transaction.SIGHASH_SINGLE: + text += 'SIGHASH_SINGLE'; + break; + case transaction_1$2.Transaction.SIGHASH_NONE: + text += 'SIGHASH_NONE'; + break; + } + return text; + } + function witnessStackToScriptWitness(witness) { + let buffer = Buffer$k.allocUnsafe(0); + function writeSlice(slice) { + buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); + } + function writeVarInt(i) { + const currentLen = buffer.length; + const varintLen = varuint.encodingLength(i); + buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); + varuint.encode(i, buffer, currentLen); + } + function writeVarSlice(slice) { + writeVarInt(slice.length); + writeSlice(slice); + } + function writeVector(vector) { + writeVarInt(vector.length); + vector.forEach(writeVarSlice); + } + writeVector(witness); + return buffer; + } + function addNonWitnessTxCache(cache, input, inputIndex) { + cache.__NON_WITNESS_UTXO_BUF_CACHE[inputIndex] = input.nonWitnessUtxo; + const tx = transaction_1$2.Transaction.fromBuffer(input.nonWitnessUtxo); + cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx; + const self = cache; + const selfIndex = inputIndex; + delete input.nonWitnessUtxo; + Object.defineProperty(input, 'nonWitnessUtxo', { + enumerable: true, + get() { + const buf = self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex]; + const txCache = self.__NON_WITNESS_UTXO_TX_CACHE[selfIndex]; + if (buf !== undefined) { + return buf; + } else { + const newBuf = txCache.toBuffer(); + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = newBuf; + return newBuf; + } + }, + set(data) { + self.__NON_WITNESS_UTXO_BUF_CACHE[selfIndex] = data; + }, + }); + } + function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize) { + let inputAmount = 0; + inputs.forEach((input, idx) => { + if (mustFinalize && input.finalScriptSig) + tx.ins[idx].script = input.finalScriptSig; + if (mustFinalize && input.finalScriptWitness) { + tx.ins[idx].witness = scriptWitnessToWitnessStack( + input.finalScriptWitness, + ); + } + if (input.witnessUtxo) { + inputAmount += input.witnessUtxo.value; + } else if (input.nonWitnessUtxo) { + const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx); + const vout = tx.ins[idx].index; + const out = nwTx.outs[vout]; + inputAmount += out.value; + } + }); + const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0); + const fee = inputAmount - outputAmount; + if (fee < 0) { + throw new Error('Outputs are spending more than Inputs'); + } + const bytes = tx.virtualSize(); + cache.__FEE = fee; + cache.__EXTRACTED_TX = tx; + cache.__FEE_RATE = Math.floor(fee / bytes); + } + function nonWitnessUtxoTxFromCache(cache, input, inputIndex) { + const c = cache.__NON_WITNESS_UTXO_TX_CACHE; + if (!c[inputIndex]) { + addNonWitnessTxCache(cache, input, inputIndex); + } + return c[inputIndex]; + } + function getScriptFromUtxo(inputIndex, input, cache) { + if (input.witnessUtxo !== undefined) { + return input.witnessUtxo.script; + } else if (input.nonWitnessUtxo !== undefined) { + const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache( + cache, + input, + inputIndex, + ); + return nonWitnessUtxoTx.outs[cache.__TX.ins[inputIndex].index].script; + } else { + throw new Error("Can't find pubkey in input without Utxo data"); + } + } + function pubkeyInInput(pubkey, input, inputIndex, cache) { + const script = getScriptFromUtxo(inputIndex, input, cache); + const { meaningfulScript } = getMeaningfulScript( + script, + inputIndex, + 'input', + input.redeemScript, + input.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function pubkeyInOutput(pubkey, output, outputIndex, cache) { + const script = cache.__TX.outs[outputIndex].script; + const { meaningfulScript } = getMeaningfulScript( + script, + outputIndex, + 'output', + output.redeemScript, + output.witnessScript, + ); + return pubkeyInScript(pubkey, meaningfulScript); + } + function redeemFromFinalScriptSig(finalScript) { + if (!finalScript) return; + const decomp = bscript$f.decompile(finalScript); + if (!decomp) return; + const lastItem = decomp[decomp.length - 1]; + if ( + !isBuffer(lastItem) || + isPubkeyLike(lastItem) || + isSigLike(lastItem) + ) + return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function redeemFromFinalWitnessScript(finalScript) { + if (!finalScript) return; + const decomp = scriptWitnessToWitnessStack(finalScript); + const lastItem = decomp[decomp.length - 1]; + if (isPubkeyLike(lastItem)) return; + const sDecomp = bscript$f.decompile(lastItem); + if (!sDecomp) return; + return lastItem; + } + function isPubkeyLike(buf) { + return buf.length === 33 && bscript$f.isCanonicalPubKey(buf); + } + function isSigLike(buf) { + return bscript$f.isCanonicalScriptSignature(buf); + } + function getMeaningfulScript( + script, + index, + ioType, + redeemScript, + witnessScript, + ) { + const isP2SH = isP2SHScript(script); + const isP2SHP2WSH = isP2SH && redeemScript && isP2WSHScript(redeemScript); + const isP2WSH = isP2WSHScript(script); + if (isP2SH && redeemScript === undefined) + throw new Error('scriptPubkey is P2SH but redeemScript missing'); + if ((isP2WSH || isP2SHP2WSH) && witnessScript === undefined) + throw new Error( + 'scriptPubkey or redeemScript is P2WSH but witnessScript missing', + ); + let meaningfulScript; + if (isP2SHP2WSH) { + meaningfulScript = witnessScript; + checkRedeemScript(index, script, redeemScript, ioType); + checkWitnessScript(index, redeemScript, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2WSH) { + meaningfulScript = witnessScript; + checkWitnessScript(index, script, witnessScript, ioType); + checkInvalidP2WSH(meaningfulScript); + } else if (isP2SH) { + meaningfulScript = redeemScript; + checkRedeemScript(index, script, redeemScript, ioType); + } else { + meaningfulScript = script; + } + return { + meaningfulScript, + type: isP2SHP2WSH + ? 'p2sh-p2wsh' + : isP2SH + ? 'p2sh' + : isP2WSH + ? 'p2wsh' + : 'raw', + }; + } + function checkInvalidP2WSH(script) { + if (isP2WPKH(script) || isP2SHScript(script)) { + throw new Error('P2WPKH or P2SH can not be contained within P2WSH'); + } + } + function pubkeyInScript(pubkey, script) { + const pubkeyHash = crypto_1$1.hash160(pubkey); + const decompiled = bscript$f.decompile(script); + if (decompiled === null) throw new Error('Unknown script error'); + return decompiled.some(element => { + if (typeof element === 'number') return false; + return element.equals(pubkey) || element.equals(pubkeyHash); + }); + } + function classifyScript(script) { + if (isP2WPKH(script)) return 'witnesspubkeyhash'; + if (isP2PKH(script)) return 'pubkeyhash'; + if (isP2MS(script)) return 'multisig'; + if (isP2PK(script)) return 'pubkey'; + return 'nonstandard'; + } + function range$1(n) { + return [...Array(n).keys()]; + } + + var transaction_builder = {}; + + var classify$1 = {}; + + var multisig$1 = {}; + + var input$b = {}; + + // OP_0 [signatures ...] + Object.defineProperty(input$b, '__esModule', { value: true }); + const bscript$e = script$1; + const script_1$a = script$1; + function partialSignature(value) { + return ( + value === script_1$a.OPS.OP_0 || bscript$e.isCanonicalScriptSignature(value) + ); + } + function check$d(script, allowIncomplete) { + const chunks = bscript$e.decompile(script); + if (chunks.length < 2) return false; + if (chunks[0] !== script_1$a.OPS.OP_0) return false; + if (allowIncomplete) { + return chunks.slice(1).every(partialSignature); + } + return chunks.slice(1).every(bscript$e.isCanonicalScriptSignature); + } + input$b.check = check$d; + check$d.toJSON = () => { + return 'multisig input'; + }; + + var output$e = {}; + + // m [pubKeys ...] n OP_CHECKMULTISIG + Object.defineProperty(output$e, '__esModule', { value: true }); + const bscript$d = script$1; + const script_1$9 = script$1; + const types$3 = types$a; + const OP_INT_BASE = script_1$9.OPS.OP_RESERVED; // OP_1 - 1 + function check$c(script, allowIncomplete) { + const chunks = bscript$d.decompile(script); + if (chunks.length < 4) return false; + if (chunks[chunks.length - 1] !== script_1$9.OPS.OP_CHECKMULTISIG) return false; + if (!types$3.Number(chunks[0])) return false; + if (!types$3.Number(chunks[chunks.length - 2])) return false; + const m = chunks[0] - OP_INT_BASE; + const n = chunks[chunks.length - 2] - OP_INT_BASE; + if (m <= 0) return false; + if (n > 16) return false; + if (m > n) return false; + if (n !== chunks.length - 3) return false; + if (allowIncomplete) return true; + const keys = chunks.slice(1, -2); + return keys.every(bscript$d.isCanonicalPubKey); + } + output$e.check = check$c; + check$c.toJSON = () => { + return 'multi-sig output'; + }; + + Object.defineProperty(multisig$1, '__esModule', { value: true }); + const input$a = input$b; + multisig$1.input = input$a; + const output$d = output$e; + multisig$1.output = output$d; + + var nulldata = {}; + + Object.defineProperty(nulldata, '__esModule', { value: true }); + // OP_RETURN {data} + const bscript$c = script$1; + const OPS = bscript$c.OPS; + function check$b(script) { + const buffer = bscript$c.compile(script); + return buffer.length > 1 && buffer[0] === OPS.OP_RETURN; + } + nulldata.check = check$b; + check$b.toJSON = () => { + return 'null data output'; + }; + const output$c = { check: check$b }; + nulldata.output = output$c; + + var pubkey = {}; + + var input$9 = {}; + + // {signature} + Object.defineProperty(input$9, '__esModule', { value: true }); + const bscript$b = script$1; + function check$a(script) { + const chunks = bscript$b.decompile(script); + return chunks.length === 1 && bscript$b.isCanonicalScriptSignature(chunks[0]); + } + input$9.check = check$a; + check$a.toJSON = () => { + return 'pubKey input'; + }; + + var output$b = {}; + + // {pubKey} OP_CHECKSIG + Object.defineProperty(output$b, '__esModule', { value: true }); + const bscript$a = script$1; + const script_1$8 = script$1; + function check$9(script) { + const chunks = bscript$a.decompile(script); + return ( + chunks.length === 2 && + bscript$a.isCanonicalPubKey(chunks[0]) && + chunks[1] === script_1$8.OPS.OP_CHECKSIG + ); + } + output$b.check = check$9; + check$9.toJSON = () => { + return 'pubKey output'; + }; + + Object.defineProperty(pubkey, '__esModule', { value: true }); + const input$8 = input$9; + pubkey.input = input$8; + const output$a = output$b; + pubkey.output = output$a; + + var pubkeyhash = {}; + + var input$7 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$7, '__esModule', { value: true }); + const bscript$9 = script$1; + function check$8(script) { + const chunks = bscript$9.decompile(script); + return ( + chunks.length === 2 && + bscript$9.isCanonicalScriptSignature(chunks[0]) && + bscript$9.isCanonicalPubKey(chunks[1]) + ); + } + input$7.check = check$8; + check$8.toJSON = () => { + return 'pubKeyHash input'; + }; + + var output$9 = {}; + + // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG + Object.defineProperty(output$9, '__esModule', { value: true }); + const bscript$8 = script$1; + const script_1$7 = script$1; + function check$7(script) { + const buffer = bscript$8.compile(script); + return ( + buffer.length === 25 && + buffer[0] === script_1$7.OPS.OP_DUP && + buffer[1] === script_1$7.OPS.OP_HASH160 && + buffer[2] === 0x14 && + buffer[23] === script_1$7.OPS.OP_EQUALVERIFY && + buffer[24] === script_1$7.OPS.OP_CHECKSIG + ); + } + output$9.check = check$7; + check$7.toJSON = () => { + return 'pubKeyHash output'; + }; + + Object.defineProperty(pubkeyhash, '__esModule', { value: true }); + const input$6 = input$7; + pubkeyhash.input = input$6; + const output$8 = output$9; + pubkeyhash.output = output$8; + + var scripthash = {}; + + var input$5 = {}; + + var output$7 = {}; + + // OP_0 {pubKeyHash} + Object.defineProperty(output$7, '__esModule', { value: true }); + const bscript$7 = script$1; + const script_1$6 = script$1; + function check$6(script) { + const buffer = bscript$7.compile(script); + return ( + buffer.length === 22 && + buffer[0] === script_1$6.OPS.OP_0 && + buffer[1] === 0x14 + ); + } + output$7.check = check$6; + check$6.toJSON = () => { + return 'Witness pubKeyHash output'; + }; + + var output$6 = {}; + + // OP_0 {scriptHash} + Object.defineProperty(output$6, '__esModule', { value: true }); + const bscript$6 = script$1; + const script_1$5 = script$1; + function check$5(script) { + const buffer = bscript$6.compile(script); + return ( + buffer.length === 34 && + buffer[0] === script_1$5.OPS.OP_0 && + buffer[1] === 0x20 + ); + } + output$6.check = check$5; + check$5.toJSON = () => { + return 'Witness scriptHash output'; + }; + + // {serialized scriptPubKey script} + Object.defineProperty(input$5, '__esModule', { value: true }); + const bscript$5 = script$1; + const p2ms$1 = multisig$1; + const p2pk$1 = pubkey; + const p2pkh$2 = pubkeyhash; + const p2wpkho = output$7; + const p2wsho = output$6; + function check$4(script, allowIncomplete) { + const chunks = bscript$5.decompile(script); + if (chunks.length < 1) return false; + const lastChunk = chunks[chunks.length - 1]; + if (!isBuffer(lastChunk)) return false; + const scriptSigChunks = bscript$5.decompile( + bscript$5.compile(chunks.slice(0, -1)), + ); + const redeemScriptChunks = bscript$5.decompile(lastChunk); + // is redeemScript a valid script? + if (!redeemScriptChunks) return false; + // is redeemScriptSig push only? + if (!bscript$5.isPushOnly(scriptSigChunks)) return false; + // is witness? + if (chunks.length === 1) { + return ( + p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) + ); + } + // match types + if ( + p2pkh$2.input.check(scriptSigChunks) && + p2pkh$2.output.check(redeemScriptChunks) + ) + return true; + if ( + p2ms$1.input.check(scriptSigChunks, allowIncomplete) && + p2ms$1.output.check(redeemScriptChunks) + ) + return true; + if ( + p2pk$1.input.check(scriptSigChunks) && + p2pk$1.output.check(redeemScriptChunks) + ) + return true; + return false; + } + input$5.check = check$4; + check$4.toJSON = () => { + return 'scriptHash input'; + }; + + var output$5 = {}; + + // OP_HASH160 {scriptHash} OP_EQUAL + Object.defineProperty(output$5, '__esModule', { value: true }); + const bscript$4 = script$1; + const script_1$4 = script$1; + function check$3(script) { + const buffer = bscript$4.compile(script); + return ( + buffer.length === 23 && + buffer[0] === script_1$4.OPS.OP_HASH160 && + buffer[1] === 0x14 && + buffer[22] === script_1$4.OPS.OP_EQUAL + ); + } + output$5.check = check$3; + check$3.toJSON = () => { + return 'scriptHash output'; + }; + + Object.defineProperty(scripthash, '__esModule', { value: true }); + const input$4 = input$5; + scripthash.input = input$4; + const output$4 = output$5; + scripthash.output = output$4; + + var witnesscommitment = {}; + + var output$3 = {}; + + // OP_RETURN {aa21a9ed} {commitment} + Object.defineProperty(output$3, '__esModule', { value: true }); + const bscript$3 = script$1; + const script_1$3 = script$1; + const types$2 = types$a; + const typeforce$2 = typeforce_1; + const HEADER = Buffer$k.from('aa21a9ed', 'hex'); + function check$2(script) { + const buffer = bscript$3.compile(script); + return ( + buffer.length > 37 && + buffer[0] === script_1$3.OPS.OP_RETURN && + buffer[1] === 0x24 && + buffer.slice(2, 6).equals(HEADER) + ); + } + output$3.check = check$2; + check$2.toJSON = () => { + return 'Witness commitment output'; + }; + function encode(commitment) { + typeforce$2(types$2.Hash256bit, commitment); + const buffer = Buffer$k.allocUnsafe(36); + HEADER.copy(buffer, 0); + commitment.copy(buffer, 4); + return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); + } + output$3.encode = encode; + function decode(buffer) { + typeforce$2(check$2, buffer); + return bscript$3.decompile(buffer)[1].slice(4, 36); + } + output$3.decode = decode; + + Object.defineProperty(witnesscommitment, '__esModule', { value: true }); + const output$2 = output$3; + witnesscommitment.output = output$2; + + var witnesspubkeyhash = {}; + + var input$3 = {}; + + // {signature} {pubKey} + Object.defineProperty(input$3, '__esModule', { value: true }); + const bscript$2 = script$1; + function isCompressedCanonicalPubKey(pubKey) { + return bscript$2.isCanonicalPubKey(pubKey) && pubKey.length === 33; + } + function check$1(script) { + const chunks = bscript$2.decompile(script); + return ( + chunks.length === 2 && + bscript$2.isCanonicalScriptSignature(chunks[0]) && + isCompressedCanonicalPubKey(chunks[1]) + ); + } + input$3.check = check$1; + check$1.toJSON = () => { + return 'witnessPubKeyHash input'; + }; + + Object.defineProperty(witnesspubkeyhash, '__esModule', { value: true }); + const input$2 = input$3; + witnesspubkeyhash.input = input$2; + const output$1 = output$7; + witnesspubkeyhash.output = output$1; + + var witnessscripthash = {}; + + var input$1 = {}; + + // {serialized scriptPubKey script} + Object.defineProperty(input$1, '__esModule', { value: true }); + const bscript$1 = script$1; + const typeforce$1 = typeforce_1; + const p2ms = multisig$1; + const p2pk = pubkey; + const p2pkh$1 = pubkeyhash; + function check(chunks, allowIncomplete) { + typeforce$1(typeforce$1.Array, chunks); + if (chunks.length < 1) return false; + const witnessScript = chunks[chunks.length - 1]; + if (!isBuffer(witnessScript)) return false; + const witnessScriptChunks = bscript$1.decompile(witnessScript); + // is witnessScript a valid script? + if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; + const witnessRawScriptSig = bscript$1.compile(chunks.slice(0, -1)); + // match types + if ( + p2pkh$1.input.check(witnessRawScriptSig) && + p2pkh$1.output.check(witnessScriptChunks) + ) + return true; + if ( + p2ms.input.check(witnessRawScriptSig, allowIncomplete) && + p2ms.output.check(witnessScriptChunks) + ) + return true; + if ( + p2pk.input.check(witnessRawScriptSig) && + p2pk.output.check(witnessScriptChunks) + ) + return true; + return false; + } + input$1.check = check; + check.toJSON = () => { + return 'witnessScriptHash input'; + }; + + Object.defineProperty(witnessscripthash, '__esModule', { value: true }); + const input = input$1; + witnessscripthash.input = input; + const output = output$6; + witnessscripthash.output = output; + + Object.defineProperty(classify$1, '__esModule', { value: true }); + const script_1$2 = script$1; + const multisig = multisig$1; + const nullData = nulldata; + const pubKey = pubkey; + const pubKeyHash = pubkeyhash; + const scriptHash = scripthash; + const witnessCommitment = witnesscommitment; + const witnessPubKeyHash = witnesspubkeyhash; + const witnessScriptHash = witnessscripthash; + const types$1 = { + P2MS: 'multisig', + NONSTANDARD: 'nonstandard', + NULLDATA: 'nulldata', + P2PK: 'pubkey', + P2PKH: 'pubkeyhash', + P2SH: 'scripthash', + P2WPKH: 'witnesspubkeyhash', + P2WSH: 'witnessscripthash', + WITNESS_COMMITMENT: 'witnesscommitment', + }; + classify$1.types = types$1; + function classifyOutput(script) { + if (witnessPubKeyHash.output.check(script)) return types$1.P2WPKH; + if (witnessScriptHash.output.check(script)) return types$1.P2WSH; + if (pubKeyHash.output.check(script)) return types$1.P2PKH; + if (scriptHash.output.check(script)) return types$1.P2SH; + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (multisig.output.check(chunks)) return types$1.P2MS; + if (pubKey.output.check(chunks)) return types$1.P2PK; + if (witnessCommitment.output.check(chunks)) return types$1.WITNESS_COMMITMENT; + if (nullData.output.check(chunks)) return types$1.NULLDATA; + return types$1.NONSTANDARD; + } + classify$1.output = classifyOutput; + function classifyInput(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (pubKeyHash.input.check(chunks)) return types$1.P2PKH; + if (scriptHash.input.check(chunks, allowIncomplete)) return types$1.P2SH; + if (multisig.input.check(chunks, allowIncomplete)) return types$1.P2MS; + if (pubKey.input.check(chunks)) return types$1.P2PK; + return types$1.NONSTANDARD; + } + classify$1.input = classifyInput; + function classifyWitness(script, allowIncomplete) { + // XXX: optimization, below functions .decompile before use + const chunks = script_1$2.decompile(script); + if (!chunks) throw new TypeError('Invalid script'); + if (witnessPubKeyHash.input.check(chunks)) return types$1.P2WPKH; + if (witnessScriptHash.input.check(chunks, allowIncomplete)) + return types$1.P2WSH; + return types$1.NONSTANDARD; + } + classify$1.witness = classifyWitness; + + Object.defineProperty(transaction_builder, '__esModule', { value: true }); + const baddress = address$1; + const bufferutils_1 = bufferutils; + const classify = classify$1; + const bcrypto = crypto$2; + const ECPair$1 = ecpair; + const networks$1 = networks$3; + const payments$1 = payments$4; + const bscript = script$1; + const script_1$1 = script$1; + const transaction_1$1 = transaction; + const types = types$a; + const typeforce = typeforce_1; + const SCRIPT_TYPES = classify.types; + const PREVOUT_TYPES = new Set([ + // Raw + 'p2pkh', + 'p2pk', + 'p2wpkh', + 'p2ms', + // P2SH wrapped + 'p2sh-p2pkh', + 'p2sh-p2pk', + 'p2sh-p2wpkh', + 'p2sh-p2ms', + // P2WSH wrapped + 'p2wsh-p2pkh', + 'p2wsh-p2pk', + 'p2wsh-p2ms', + // P2SH-P2WSH wrapper + 'p2sh-p2wsh-p2pkh', + 'p2sh-p2wsh-p2pk', + 'p2sh-p2wsh-p2ms', + ]); + function tfMessage(type, value, message) { + try { + typeforce(type, value); + } catch (err) { + throw new Error(message); + } + } + function txIsString(tx) { + return typeof tx === 'string' || tx instanceof String; + } + function txIsTransaction(tx) { + return tx instanceof transaction_1$1.Transaction; + } + class TransactionBuilder { + // WARNING: maximumFeeRate is __NOT__ to be relied on, + // it's just another potential safety mechanism (safety in-depth) + constructor(network = networks$1.bitcoin, maximumFeeRate = 2500) { + this.network = network; + this.maximumFeeRate = maximumFeeRate; + this.__PREV_TX_SET = {}; + this.__INPUTS = []; + this.__TX = new transaction_1$1.Transaction(); + this.__TX.version = 2; + this.__USE_LOW_R = false; + console.warn( + 'Deprecation Warning: TransactionBuilder will be removed in the future. ' + + '(v6.x.x or later) Please use the Psbt class instead. Examples of usage ' + + 'are available in the transactions-psbt.js integration test file on our ' + + 'Github. A high level explanation is available in the psbt.ts and psbt.js ' + + 'files as well.', + ); + } + static fromTransaction(transaction, network) { + const txb = new TransactionBuilder(network); + // Copy transaction fields + txb.setVersion(transaction.version); + txb.setLockTime(transaction.locktime); + // Copy outputs (done first to avoid signature invalidation) + transaction.outs.forEach(txOut => { + txb.addOutput(txOut.script, txOut.value); + }); + // Copy inputs + transaction.ins.forEach(txIn => { + txb.__addInputUnsafe(txIn.hash, txIn.index, { + sequence: txIn.sequence, + script: txIn.script, + witness: txIn.witness, + }); + }); + // fix some things not possible through the public API + txb.__INPUTS.forEach((input, i) => { + fixMultisigOrder(input, transaction, i); + }); + return txb; + } + setLowR(setting) { + typeforce(typeforce.maybe(typeforce.Boolean), setting); + if (setting === undefined) { + setting = true; + } + this.__USE_LOW_R = setting; + return setting; + } + setLockTime(locktime) { + typeforce(types.UInt32, locktime); + // if any signatures exist, throw + if ( + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(s => s !== undefined); + }) + ) { + throw new Error('No, this would invalidate signatures'); + } + this.__TX.locktime = locktime; + } + setVersion(version) { + typeforce(types.UInt32, version); + // XXX: this might eventually become more complex depending on what the versions represent + this.__TX.version = version; + } + addInput(txHash, vout, sequence, prevOutScript) { + if (!this.__canModifyInputs()) { + throw new Error('No, this would invalidate signatures'); + } + let value; + // is it a hex string? + if (txIsString(txHash)) { + // transaction hashs's are displayed in reverse order, un-reverse it + txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); + // is it a Transaction object? + } else if (txIsTransaction(txHash)) { + const txOut = txHash.outs[vout]; + prevOutScript = txOut.script; + value = txOut.value; + txHash = txHash.getHash(false); + } + return this.__addInputUnsafe(txHash, vout, { + sequence, + prevOutScript, + value, + }); + } + addOutput(scriptPubKey, value) { + if (!this.__canModifyOutputs()) { + throw new Error('No, this would invalidate signatures'); + } + // Attempt to get a script if it's a base58 or bech32 address string + if (typeof scriptPubKey === 'string') { + scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network); + } + return this.__TX.addOutput(scriptPubKey, value); + } + build() { + return this.__build(false); + } + buildIncomplete() { + return this.__build(true); + } + sign( + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + ) { + trySign( + getSigningData( + this.network, + this.__INPUTS, + this.__needsOutputs.bind(this), + this.__TX, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + this.__USE_LOW_R, + ), + ); + } + __addInputUnsafe(txHash, vout, options) { + if (transaction_1$1.Transaction.isCoinbaseHash(txHash)) { + throw new Error('coinbase inputs not supported'); + } + const prevTxOut = txHash.toString('hex') + ':' + vout; + if (this.__PREV_TX_SET[prevTxOut] !== undefined) + throw new Error('Duplicate TxOut: ' + prevTxOut); + let input = {}; + // derive what we can from the scriptSig + if (options.script !== undefined) { + input = expandInput(options.script, options.witness || []); + } + // if an input value was given, retain it + if (options.value !== undefined) { + input.value = options.value; + } + // derive what we can from the previous transactions output script + if (!input.prevOutScript && options.prevOutScript) { + let prevOutType; + if (!input.pubkeys && !input.signatures) { + const expanded = expandOutput(options.prevOutScript); + if (expanded.pubkeys) { + input.pubkeys = expanded.pubkeys; + input.signatures = expanded.signatures; + } + prevOutType = expanded.type; + } + input.prevOutScript = options.prevOutScript; + input.prevOutType = prevOutType || classify.output(options.prevOutScript); + } + const vin = this.__TX.addInput( + txHash, + vout, + options.sequence, + options.scriptSig, + ); + this.__INPUTS[vin] = input; + this.__PREV_TX_SET[prevTxOut] = true; + return vin; + } + __build(allowIncomplete) { + if (!allowIncomplete) { + if (!this.__TX.ins.length) throw new Error('Transaction has no inputs'); + if (!this.__TX.outs.length) throw new Error('Transaction has no outputs'); + } + const tx = this.__TX.clone(); + // create script signatures from inputs + this.__INPUTS.forEach((input, i) => { + if (!input.prevOutType && !allowIncomplete) + throw new Error('Transaction is not complete'); + const result = build(input.prevOutType, input, allowIncomplete); + if (!result) { + if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) + throw new Error('Unknown input type'); + if (!allowIncomplete) throw new Error('Not enough information'); + return; + } + tx.setInputScript(i, result.input); + tx.setWitness(i, result.witness); + }); + if (!allowIncomplete) { + // do not rely on this, its merely a last resort + if (this.__overMaximumFees(tx.virtualSize())) { + throw new Error('Transaction has absurd fees'); + } + } + return tx; + } + __canModifyInputs() { + return this.__INPUTS.every(input => { + if (!input.signatures) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + // if SIGHASH_ANYONECANPAY is set, signatures would not + // be invalidated by more inputs + return ( + (hashType & transaction_1$1.Transaction.SIGHASH_ANYONECANPAY) !== 0 + ); + }); + }); + } + __needsOutputs(signingHashType) { + if (signingHashType === transaction_1$1.Transaction.SIGHASH_ALL) { + return this.__TX.outs.length === 0; + } + // if inputs are being signed with SIGHASH_NONE, we don't strictly need outputs + // .build() will fail, but .buildIncomplete() is OK + return ( + this.__TX.outs.length === 0 && + this.__INPUTS.some(input => { + if (!input.signatures) return false; + return input.signatures.some(signature => { + if (!signature) return false; // no signature, no issue + const hashType = signatureHashType(signature); + if (hashType & transaction_1$1.Transaction.SIGHASH_NONE) return false; // SIGHASH_NONE doesn't care about outputs + return true; // SIGHASH_* does care + }); + }) + ); + } + __canModifyOutputs() { + const nInputs = this.__TX.ins.length; + const nOutputs = this.__TX.outs.length; + return this.__INPUTS.every(input => { + if (input.signatures === undefined) return true; + return input.signatures.every(signature => { + if (!signature) return true; + const hashType = signatureHashType(signature); + const hashTypeMod = hashType & 0x1f; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_NONE) return true; + if (hashTypeMod === transaction_1$1.Transaction.SIGHASH_SINGLE) { + // if SIGHASH_SINGLE is set, and nInputs > nOutputs + // some signatures would be invalidated by the addition + // of more outputs + return nInputs <= nOutputs; + } + return false; + }); + }); + } + __overMaximumFees(bytes) { + // not all inputs will have .value defined + const incoming = this.__INPUTS.reduce((a, x) => a + (x.value >>> 0), 0); + // but all outputs do, and if we have any input value + // we can immediately determine if the outputs are too small + const outgoing = this.__TX.outs.reduce((a, x) => a + x.value, 0); + const fee = incoming - outgoing; + const feeRate = fee / bytes; + return feeRate > this.maximumFeeRate; + } + } + transaction_builder.TransactionBuilder = TransactionBuilder; + function expandInput(scriptSig, witnessStack, type, scriptPubKey) { + if (scriptSig.length === 0 && witnessStack.length === 0) return {}; + if (!type) { + let ssType = classify.input(scriptSig, true); + let wsType = classify.witness(witnessStack, true); + if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined; + if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined; + type = ssType || wsType; + } + switch (type) { + case SCRIPT_TYPES.P2WPKH: { + const { output, pubkey, signature } = payments$1.p2wpkh({ + witness: witnessStack, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WPKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PKH: { + const { output, pubkey, signature } = payments$1.p2pkh({ + input: scriptSig, + }); + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2PKH, + pubkeys: [pubkey], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2PK: { + const { signature } = payments$1.p2pk({ input: scriptSig }); + return { + prevOutType: SCRIPT_TYPES.P2PK, + pubkeys: [undefined], + signatures: [signature], + }; + } + case SCRIPT_TYPES.P2MS: { + const { m, pubkeys, signatures } = payments$1.p2ms( + { + input: scriptSig, + output: scriptPubKey, + }, + { allowIncomplete: true }, + ); + return { + prevOutType: SCRIPT_TYPES.P2MS, + pubkeys, + signatures, + maxSignatures: m, + }; + } + } + if (type === SCRIPT_TYPES.P2SH) { + const { output, redeem } = payments$1.p2sh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + const expanded = expandInput( + redeem.input, + redeem.witness, + outputType, + redeem.output, + ); + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2SH, + redeemScript: redeem.output, + redeemScriptType: expanded.prevOutType, + witnessScript: expanded.witnessScript, + witnessScriptType: expanded.witnessScriptType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + if (type === SCRIPT_TYPES.P2WSH) { + const { output, redeem } = payments$1.p2wsh({ + input: scriptSig, + witness: witnessStack, + }); + const outputType = classify.output(redeem.output); + let expanded; + if (outputType === SCRIPT_TYPES.P2WPKH) { + expanded = expandInput(redeem.input, redeem.witness, outputType); + } else { + expanded = expandInput( + bscript.compile(redeem.witness), + [], + outputType, + redeem.output, + ); + } + if (!expanded.prevOutType) return {}; + return { + prevOutScript: output, + prevOutType: SCRIPT_TYPES.P2WSH, + witnessScript: redeem.output, + witnessScriptType: expanded.prevOutType, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + }; + } + return { + prevOutType: SCRIPT_TYPES.NONSTANDARD, + prevOutScript: scriptSig, + }; + } + // could be done in expandInput, but requires the original Transaction for hashForSignature + function fixMultisigOrder(input, transaction, vin) { + if (input.redeemScriptType !== SCRIPT_TYPES.P2MS || !input.redeemScript) + return; + if (input.pubkeys.length === input.signatures.length) return; + const unmatched = input.signatures.concat(); + input.signatures = input.pubkeys.map(pubKey => { + const keyPair = ECPair$1.fromPublicKey(pubKey); + let match; + // check for a signature + unmatched.some((signature, i) => { + // skip if undefined || OP_0 + if (!signature) return false; + // TODO: avoid O(n) hashForSignature + const parsed = bscript.signature.decode(signature); + const hash = transaction.hashForSignature( + vin, + input.redeemScript, + parsed.hashType, + ); + // skip if signature does not match pubKey + if (!keyPair.verify(hash, parsed.signature)) return false; + // remove matched signature from unmatched + unmatched[i] = undefined; + match = signature; + return true; + }); + return match; + }); + } + function expandOutput(script, ourPubKey) { + typeforce(types.Buffer, script); + const type = classify.output(script); + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const pkh1 = payments$1.p2pkh({ output: script }).hash; + const pkh2 = bcrypto.hash160(ourPubKey); + if (!pkh1.equals(pkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2WPKH: { + if (!ourPubKey) return { type }; + // does our hash160(pubKey) match the output scripts? + const wpkh1 = payments$1.p2wpkh({ output: script }).hash; + const wpkh2 = bcrypto.hash160(ourPubKey); + if (!wpkh1.equals(wpkh2)) return { type }; + return { + type, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2PK: { + const p2pk = payments$1.p2pk({ output: script }); + return { + type, + pubkeys: [p2pk.pubkey], + signatures: [undefined], + }; + } + case SCRIPT_TYPES.P2MS: { + const p2ms = payments$1.p2ms({ output: script }); + return { + type, + pubkeys: p2ms.pubkeys, + signatures: p2ms.pubkeys.map(() => undefined), + maxSignatures: p2ms.m, + }; + } + } + return { type }; + } + function prepareInput(input, ourPubKey, redeemScript, witnessScript) { + if (redeemScript && witnessScript) { + const p2wsh = payments$1.p2wsh({ + redeem: { output: witnessScript }, + }); + const p2wshAlt = payments$1.p2wsh({ output: redeemScript }); + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + const p2shAlt = payments$1.p2sh({ redeem: p2wsh }); + // enforces P2SH(P2WSH(...)) + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure'); + return { + redeemScript, + redeemScriptType: SCRIPT_TYPES.P2WSH, + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (redeemScript) { + const p2sh = payments$1.p2sh({ redeem: { output: redeemScript } }); + if (input.prevOutScript) { + let p2shAlt; + try { + p2shAlt = payments$1.p2sh({ output: input.prevOutScript }); + } catch (e) { + throw new Error('PrevOutScript must be P2SH'); + } + if (!p2sh.hash.equals(p2shAlt.hash)) + throw new Error('Redeem script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2sh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as redeemScript (' + + bscript.toASM(redeemScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = redeemScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + redeemScript, + redeemScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2SH, + prevOutScript: p2sh.output, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (witnessScript) { + const p2wsh = payments$1.p2wsh({ redeem: { output: witnessScript } }); + if (input.prevOutScript) { + const p2wshAlt = payments$1.p2wsh({ output: input.prevOutScript }); + if (!p2wsh.hash.equals(p2wshAlt.hash)) + throw new Error('Witness script inconsistent with prevOutScript'); + } + const expanded = expandOutput(p2wsh.redeem.output, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported as witnessScript (' + + bscript.toASM(witnessScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + const signScript = witnessScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) + throw new Error('P2WSH(P2WPKH) is a consensus failure'); + return { + witnessScript, + witnessScriptType: expanded.type, + prevOutType: SCRIPT_TYPES.P2WSH, + prevOutScript: p2wsh.output, + hasWitness: true, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + if (input.prevOutType && input.prevOutScript) { + // embedded scripts are not possible without extra information + if (input.prevOutType === SCRIPT_TYPES.P2SH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires redeemScript', + ); + if (input.prevOutType === SCRIPT_TYPES.P2WSH) + throw new Error( + 'PrevOutScript is ' + input.prevOutType + ', requires witnessScript', + ); + if (!input.prevOutScript) throw new Error('PrevOutScript is missing'); + const expanded = expandOutput(input.prevOutScript, ourPubKey); + if (!expanded.pubkeys) + throw new Error( + expanded.type + + ' not supported (' + + bscript.toASM(input.prevOutScript) + + ')', + ); + if (input.signatures && input.signatures.some(x => x !== undefined)) { + expanded.signatures = input.signatures; + } + let signScript = input.prevOutScript; + if (expanded.type === SCRIPT_TYPES.P2WPKH) { + signScript = payments$1.p2pkh({ pubkey: expanded.pubkeys[0] }).output; + } + return { + prevOutType: expanded.type, + prevOutScript: input.prevOutScript, + hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, + signScript, + signType: expanded.type, + pubkeys: expanded.pubkeys, + signatures: expanded.signatures, + maxSignatures: expanded.maxSignatures, + }; + } + const prevOutScript = payments$1.p2pkh({ pubkey: ourPubKey }).output; + return { + prevOutType: SCRIPT_TYPES.P2PKH, + prevOutScript, + hasWitness: false, + signScript: prevOutScript, + signType: SCRIPT_TYPES.P2PKH, + pubkeys: [ourPubKey], + signatures: [undefined], + }; + } + function build(type, input, allowIncomplete) { + const pubkeys = input.pubkeys || []; + let signatures = input.signatures || []; + switch (type) { + case SCRIPT_TYPES.P2PKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2WPKH: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }); + } + case SCRIPT_TYPES.P2PK: { + if (pubkeys.length === 0) break; + if (signatures.length === 0) break; + return payments$1.p2pk({ signature: signatures[0] }); + } + case SCRIPT_TYPES.P2MS: { + const m = input.maxSignatures; + if (allowIncomplete) { + signatures = signatures.map(x => x || script_1$1.OPS.OP_0); + } else { + signatures = signatures.filter(x => x); + } + // if the transaction is not not complete (complete), or if signatures.length === m, validate + // otherwise, the number of OP_0's may be >= m, so don't validate (boo) + const validate = !allowIncomplete || m === signatures.length; + return payments$1.p2ms( + { m, pubkeys, signatures }, + { allowIncomplete, validate }, + ); + } + case SCRIPT_TYPES.P2SH: { + const redeem = build(input.redeemScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2sh({ + redeem: { + output: redeem.output || input.redeemScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + case SCRIPT_TYPES.P2WSH: { + const redeem = build(input.witnessScriptType, input, allowIncomplete); + if (!redeem) return; + return payments$1.p2wsh({ + redeem: { + output: input.witnessScript, + input: redeem.input, + witness: redeem.witness, + }, + }); + } + } + } + function canSign(input) { + return ( + input.signScript !== undefined && + input.signType !== undefined && + input.pubkeys !== undefined && + input.signatures !== undefined && + input.signatures.length === input.pubkeys.length && + input.pubkeys.length > 0 && + (input.hasWitness === false || input.value !== undefined) + ); + } + function signatureHashType(buffer) { + return buffer.readUInt8(buffer.length - 1); + } + function checkSignArgs(inputs, signParams) { + if (!PREVOUT_TYPES.has(signParams.prevOutScriptType)) { + throw new TypeError( + `Unknown prevOutScriptType "${signParams.prevOutScriptType}"`, + ); + } + tfMessage( + typeforce.Number, + signParams.vin, + `sign must include vin parameter as Number (input index)`, + ); + tfMessage( + types.Signer, + signParams.keyPair, + `sign must include keyPair parameter as Signer interface`, + ); + tfMessage( + typeforce.maybe(typeforce.Number), + signParams.hashType, + `sign hashType parameter must be a number`, + ); + const prevOutType = (inputs[signParams.vin] || []).prevOutType; + const posType = signParams.prevOutScriptType; + switch (posType) { + case 'p2pkh': + if (prevOutType && prevOutType !== 'pubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2pk': + if (prevOutType && prevOutType !== 'pubkey') { + throw new TypeError( + `input #${signParams.vin} is not of type p2pk: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wpkh': + if (prevOutType && prevOutType !== 'witnesspubkeyhash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2ms': + if (prevOutType && prevOutType !== 'multisig') { + throw new TypeError( + `input #${signParams.vin} is not of type p2ms: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2sh-p2wpkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type p2sh-p2wpkh: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2ms': + case 'p2sh-p2pk': + case 'p2sh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.value(undefined), + signParams.witnessScript, + `${posType} requires NO witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires redeemScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.witnessValue, + `${posType} requires NO witnessValue`, + ); + break; + case 'p2wsh-p2ms': + case 'p2wsh-p2pk': + case 'p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'witnessscripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.value(undefined), + signParams.redeemScript, + `${posType} requires NO redeemScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessValue`, + ); + break; + case 'p2sh-p2wsh-p2ms': + case 'p2sh-p2wsh-p2pk': + case 'p2sh-p2wsh-p2pkh': + if (prevOutType && prevOutType !== 'scripthash') { + throw new TypeError( + `input #${signParams.vin} is not of type ${posType}: ${prevOutType}`, + ); + } + tfMessage( + typeforce.Buffer, + signParams.witnessScript, + `${posType} requires witnessScript`, + ); + tfMessage( + typeforce.Buffer, + signParams.redeemScript, + `${posType} requires witnessScript`, + ); + tfMessage( + types.Satoshi, + signParams.witnessValue, + `${posType} requires witnessScript`, + ); + break; + } + } + function trySign({ + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR, + }) { + // enforce in order signing of public keys + let signed = false; + for (const [i, pubKey] of input.pubkeys.entries()) { + if (!ourPubKey.equals(pubKey)) continue; + if (input.signatures[i]) throw new Error('Signature already exists'); + // TODO: add tests + if (ourPubKey.length !== 33 && input.hasWitness) { + throw new Error( + 'BIP143 rejects uncompressed public keys in P2WPKH or P2WSH', + ); + } + const signature = keyPair.sign(signatureHash, useLowR); + input.signatures[i] = bscript.signature.encode(signature, hashType); + signed = true; + } + if (!signed) throw new Error('Key pair cannot sign for this input'); + } + function getSigningData( + network, + inputs, + needsOutputs, + tx, + signParams, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + useLowR, + ) { + let vin; + if (typeof signParams === 'number') { + console.warn( + 'DEPRECATED: TransactionBuilder sign method arguments ' + + 'will change in v6, please use the TxbSignArg interface', + ); + vin = signParams; + } else if (typeof signParams === 'object') { + checkSignArgs(inputs, signParams); + ({ + vin, + keyPair, + redeemScript, + hashType, + witnessValue, + witnessScript, + } = signParams); + } else { + throw new TypeError( + 'TransactionBuilder sign first arg must be TxbSignArg or number', + ); + } + if (keyPair === undefined) { + throw new Error('sign requires keypair'); + } + // TODO: remove keyPair.network matching in 4.0.0 + if (keyPair.network && keyPair.network !== network) + throw new TypeError('Inconsistent network'); + if (!inputs[vin]) throw new Error('No input at index: ' + vin); + hashType = hashType || transaction_1$1.Transaction.SIGHASH_ALL; + if (needsOutputs(hashType)) throw new Error('Transaction needs outputs'); + const input = inputs[vin]; + // if redeemScript was previously provided, enforce consistency + if ( + input.redeemScript !== undefined && + redeemScript && + !input.redeemScript.equals(redeemScript) + ) { + throw new Error('Inconsistent redeemScript'); + } + const ourPubKey = + keyPair.publicKey || (keyPair.getPublicKey && keyPair.getPublicKey()); + if (!canSign(input)) { + if (witnessValue !== undefined) { + if (input.value !== undefined && input.value !== witnessValue) + throw new Error('Input did not match witnessValue'); + typeforce(types.Satoshi, witnessValue); + input.value = witnessValue; + } + if (!canSign(input)) { + const prepared = prepareInput( + input, + ourPubKey, + redeemScript, + witnessScript, + ); + // updates inline + Object.assign(input, prepared); + } + if (!canSign(input)) throw Error(input.prevOutType + ' not supported'); + } + // ready to sign + let signatureHash; + if (input.hasWitness) { + signatureHash = tx.hashForWitnessV0( + vin, + input.signScript, + input.value, + hashType, + ); + } else { + signatureHash = tx.hashForSignature(vin, input.signScript, hashType); + } + return { + input, + ourPubKey, + keyPair, + signatureHash, + hashType, + useLowR: !!useLowR, + }; + } + + Object.defineProperty(src$1, '__esModule', { value: true }); + const bip32 = src; + src$1.bip32 = bip32; + const address = address$1; + src$1.address = address; + const crypto = crypto$2; + var crypto_1 = src$1.crypto = crypto; + const ECPair = ecpair; + src$1.ECPair = ECPair; + const networks = networks$3; + src$1.networks = networks; + const payments = payments$4; + src$1.payments = payments; + const script = script$1; + src$1.script = script; + var block_1 = block; + src$1.Block = block_1.Block; + var psbt_1 = psbt$1; + src$1.Psbt = psbt_1.Psbt; + var script_1 = script$1; + src$1.opcodes = script_1.OPS; + var transaction_1 = transaction; + src$1.Transaction = transaction_1.Transaction; + var transaction_builder_1 = transaction_builder; + src$1.TransactionBuilder = transaction_builder_1.TransactionBuilder; + + var re$5 = {exports: {}}; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + + const MAX_LENGTH$2 = 256; + const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991; + + // Max safe segment length for coercion. + const MAX_SAFE_COMPONENT_LENGTH = 16; + + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH + }; + + const debug$3 = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) + ) ? (...args) => console.error('SEMVER', ...args) + : () => {}; + + var debug_1 = debug$3; + + (function (module, exports) { + const { MAX_SAFE_COMPONENT_LENGTH } = constants; + const debug = debug_1; + exports = module.exports = {}; + + // The actual regexps go on exports.re + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + + // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + + // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`); + + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + + // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`); + + // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + + // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + + // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + + // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`); + + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + + // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`); + + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + + createToken('GTLT', '((?:<|>)?=?)'); + + // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`); + + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + + // Coercion. + // Extract anything that could conceivably be a part of a valid semver + createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + + // Tilde ranges. + // Meaning is "reasonably at or greater than" + createToken('LONETILDE', '(?:~>?)'); + + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + + // Caret ranges. + // Meaning is "at least and backwards compatible with" + createToken('LONECARET', '(?:\\^)'); + + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + + // A simple gt/lt/eq thing, or just "" to indicate "any version" + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + + // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + + // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`); + + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`); + + // Star ranges basically just allow anything at all. + createToken('STAR', '(<|>)?=?\\s*\\*'); + // >=0.0.0 is like a star + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }(re$5, re$5.exports)); + + // parse out just the options we care about so we always get a consistent + // obj with keys in a consistent order. + const opts = ['includePrerelease', 'loose', 'rtl']; + const parseOptions$4 = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true; + return options + }, {}); + var parseOptions_1 = parseOptions$4; + + const numeric = /^[0-9]+$/; + const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + + var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers + }; + + const debug$2 = debug_1; + const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants; + const { re: re$4, t: t$4 } = re$5.exports; + + const parseOptions$3 = parseOptions_1; + const { compareIdentifiers } = identifiers; + class SemVer$e { + constructor (version, options) { + options = parseOptions$3(options); + + if (version instanceof SemVer$e) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError( + `version is longer than ${MAX_LENGTH$1} characters` + ) + } + + debug$2('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease; + + const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug$2('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer$e)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer$e(other, this.options); + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer$e)) { + other = new SemVer$e(other, this.options); + } + + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug$2('prerelease compare', i, a, b); + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + this.inc('pre', identifier); + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format(); + this.raw = this.version; + return this + } + } + + var semver$1 = SemVer$e; + + const {MAX_LENGTH} = constants; + const { re: re$3, t: t$3 } = re$5.exports; + const SemVer$d = semver$1; + + const parseOptions$2 = parseOptions_1; + const parse$5 = (version, options) => { + options = parseOptions$2(options); + + if (version instanceof SemVer$d) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]; + if (!r.test(version)) { + return null + } + + try { + return new SemVer$d(version, options) + } catch (er) { + return null + } + }; + + var parse_1 = parse$5; + + const parse$4 = parse_1; + const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null + }; + var valid_1 = valid$1; + + const parse$3 = parse_1; + const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null + }; + var clean_1 = clean; + + const SemVer$c = semver$1; + + const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$c(version, options).inc(release, identifier).version + } catch (er) { + return null + } + }; + var inc_1 = inc; + + const SemVer$b = semver$1; + const compare$a = (a, b, loose) => + new SemVer$b(a, loose).compare(new SemVer$b(b, loose)); + + var compare_1 = compare$a; + + const compare$9 = compare_1; + const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + var eq_1 = eq$2; + + const parse$2 = parse_1; + const eq$1 = eq_1; + + const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } + }; + var diff_1 = diff; + + const SemVer$a = semver$1; + const major = (a, loose) => new SemVer$a(a, loose).major; + var major_1 = major; + + const SemVer$9 = semver$1; + const minor = (a, loose) => new SemVer$9(a, loose).minor; + var minor_1 = minor; + + const SemVer$8 = semver$1; + const patch = (a, loose) => new SemVer$8(a, loose).patch; + var patch_1 = patch; + + const parse$1 = parse_1; + const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + }; + var prerelease_1 = prerelease; + + const compare$8 = compare_1; + const rcompare = (a, b, loose) => compare$8(b, a, loose); + var rcompare_1 = rcompare; + + const compare$7 = compare_1; + const compareLoose = (a, b) => compare$7(a, b, true); + var compareLoose_1 = compareLoose; + + const SemVer$7 = semver$1; + const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$7(a, loose); + const versionB = new SemVer$7(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB) + }; + var compareBuild_1 = compareBuild$2; + + const compareBuild$1 = compareBuild_1; + const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + var sort_1 = sort; + + const compareBuild = compareBuild_1; + const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + var rsort_1 = rsort; + + const compare$6 = compare_1; + const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + var gt_1 = gt$3; + + const compare$5 = compare_1; + const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + var lt_1 = lt$2; + + const compare$4 = compare_1; + const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + var neq_1 = neq$1; + + const compare$3 = compare_1; + const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + var gte_1 = gte$2; + + const compare$2 = compare_1; + const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + var lte_1 = lte$2; + + const eq = eq_1; + const neq = neq_1; + const gt$2 = gt_1; + const gte$1 = gte_1; + const lt$1 = lt_1; + const lte$1 = lte_1; + + const cmp$1 = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version; + if (typeof b === 'object') + b = b.version; + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt$2(a, b, loose) + + case '>=': + return gte$1(a, b, loose) + + case '<': + return lt$1(a, b, loose) + + case '<=': + return lte$1(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } + }; + var cmp_1 = cmp$1; + + const SemVer$6 = semver$1; + const parse = parse_1; + const {re: re$2, t: t$2} = re$5.exports; + + const coerce = (version, options) => { + if (version instanceof SemVer$6) { + return version + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null + } + + options = options || {}; + + let match = null; + if (!options.rtl) { + match = version.match(re$2[t$2.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next; + while ((next = re$2[t$2.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + // leave it in a clean state + re$2[t$2.COERCERTL].lastIndex = -1; + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + }; + var coerce_1 = coerce; + + var yallist = Yallist$1; + + Yallist$1.Node = Node$1; + Yallist$1.create = Yallist$1; + + function Yallist$1 (list) { + var self = this; + if (!(self instanceof Yallist$1)) { + self = new Yallist$1(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self + } + + Yallist$1.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist$1.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist$1.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist$1.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist$1.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist$1.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist$1.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist$1.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist$1.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist$1.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist$1(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist$1.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist$1.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist$1.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist$1.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist$1.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist$1(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + return ret; + }; + + Yallist$1.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node$1(value, null, node, self) : + new Node$1(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted + } + + function push (self, item) { + self.tail = new Node$1(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } + + function unshift (self, item) { + self.head = new Node$1(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node$1 (value, prev, next, list) { + if (!(this instanceof Node$1)) { + return new Node$1(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist$1); + } catch (er) {} + + // A linked list to keep track of recently-used-ness + const Yallist = yallist; + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get$1(this, key, true) + } + + peek (key) { + return get$1(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get$1(this, key, false)); + } + } + + const get$1 = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + var lruCache = LRUCache; + + // hoisted class for cyclic dependency + class Range$a { + constructor (range, options) { + options = parseOptions$1(options); + + if (range instanceof Range$a) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range$a(range.raw, options) + } + } + + if (range instanceof Comparator$3) { + // just put it in the set and return + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + + // First, split based on boolean or || + this.raw = range; + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + if (this.set.length === 0) + this.set = [first]; + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break + } + } + } + } + + this.format(); + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim(); + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim(); + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + if (cached) + return cached + + const loose = this.options.loose; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug$1('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace); + debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR]; + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator$3(comp, this.options)); + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + rangeList.length; + const rangeMap = new Map(); + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete(''); + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result + } + + intersects (range, options) { + if (!(range instanceof Range$a)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer$5(version, this.options); + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } + } + var range = Range$a; + + const LRU = lruCache; + const cache = new LRU({ max: 1000 }); + + const parseOptions$1 = parseOptions_1; + const Comparator$3 = comparator; + const debug$1 = debug_1; + const SemVer$5 = semver$1; + const { + re: re$1, + t: t$1, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$5.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + const isAny = c => c.value === ''; + + // take a set of comparators and determine whether there + // exists a version which can satisfy it + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }); + + testComparator = remainingComparators.pop(); + } + + return result + }; + + // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + const parseComparator = (comp, options) => { + debug$1('comp', comp, options); + comp = replaceCarets(comp, options); + debug$1('caret', comp); + comp = replaceTildes(comp, options); + debug$1('tildes', comp); + comp = replaceXRanges(comp, options); + debug$1('xrange', comp); + comp = replaceStars(comp, options); + debug$1('stars', comp); + return comp + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 + const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug$1('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0`; + } + + debug$1('tilde return', ret); + return ret + }) + }; + + // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 + // ^1.2.3 --> >=1.2.3 <2.0.0-0 + // ^1.2.0 --> >=1.2.0 <2.0.0-0 + const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' '); + + const replaceCaret = (comp, options) => { + debug$1('caret', comp, options); + const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug$1('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug$1('replaceCaret pr', pr); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0`; + } + } else { + debug$1('no pr'); + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0`; + } + } + + debug$1('caret return', ret); + return ret + }) + }; + + const replaceXRanges = (comp, options) => { + debug$1('replaceXRanges', comp, options); + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug$1('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') + pr = '-0'; + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0`; + } + + debug$1('xRange return', ret); + + return ret + }) + }; + + // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + const replaceStars = (comp, options) => { + debug$1('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re$1[t$1.STAR], '') + }; + + const replaceGTE0 = (comp, options) => { + debug$1('replaceGTE0', comp, options); + return comp.trim() + .replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '') + }; + + // This function is passed to string.replace(re[t.HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 + const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return (`${from} ${to}`).trim() + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug$1(set[i].semver); + if (set[i].semver === Comparator$3.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true + }; + + const ANY$2 = Symbol('SemVer ANY'); + // hoisted class for cyclic dependency + class Comparator$2 { + static get ANY () { + return ANY$2 + } + constructor (comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator$2) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value; + } + } + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY$2) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug('comp', this); + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : ''; + if (this.operator === '=') { + this.operator = ''; + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY$2; + } else { + this.semver = new SemVer$4(m[2], this.options.loose); + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY$2 || version === ANY$2) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer$4(version, this.options); + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator$2)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range$9(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range$9(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>'); + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } + } + + var comparator = Comparator$2; + + const parseOptions = parseOptions_1; + const {re, t} = re$5.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer$4 = semver$1; + const Range$9 = range; + + const Range$8 = range; + const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false + } + return range.test(version) + }; + var satisfies_1 = satisfies$3; + + const Range$7 = range; + + // Mostly just for testing and legacy API reasons + const toComparators = (range, options) => + new Range$7(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + + var toComparators_1 = toComparators; + + const SemVer$3 = semver$1; + const Range$6 = range; + + const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max + }; + var maxSatisfying_1 = maxSatisfying; + + const SemVer$2 = semver$1; + const Range$5 = range; + const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min + }; + var minSatisfying_1 = minSatisfying; + + const SemVer$1 = semver$1; + const Range$4 = range; + const gt$1 = gt_1; + + const minVersion = (range, loose) => { + range = new Range$4(range, loose); + + let minver = new SemVer$1('0.0.0'); + if (range.test(minver)) { + return minver + } + + minver = new SemVer$1('0.0.0-0'); + if (range.test(minver)) { + return minver + } + + minver = null; + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let setMin = null; + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer$1(comparator.semver.version); + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }); + if (setMin && (!minver || gt$1(minver, setMin))) + minver = setMin; + } + + if (minver && range.test(minver)) { + return minver + } + + return null + }; + var minVersion_1 = minVersion; + + const Range$3 = range; + const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range$3(range, options).range || '*' + } catch (er) { + return null + } + }; + var valid = validRange; + + const SemVer = semver$1; + const Comparator$1 = comparator; + const {ANY: ANY$1} = Comparator$1; + const Range$2 = range; + const satisfies$2 = satisfies_1; + const gt = gt_1; + const lt = lt_1; + const lte = lte_1; + const gte = gte_1; + + const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies$2(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + + let high = null; + let low = null; + + comparators.forEach((comparator) => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true + }; + + var outside_1 = outside$2; + + // Determine if version is greater than all the versions possible in the range. + const outside$1 = outside_1; + const gtr = (version, range, options) => outside$1(version, range, '>', options); + var gtr_1 = gtr; + + const outside = outside_1; + // Determine if version is less than all the versions possible in the range + const ltr = (version, range, options) => outside(version, range, '<', options); + var ltr_1 = ltr; + + const Range$1 = range; + const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2) + }; + var intersects_1 = intersects; + + // given a set of versions and a range, create a "simplified" range + // that includes the same versions that the original range does + // If the original range is shorter than the simplified one, return that. + const satisfies$1 = satisfies_1; + const compare$1 = compare_1; + var simplify = (versions, range, options) => { + const set = []; + let min = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + for (const version of v) { + const included = satisfies$1(version, range, options); + if (included) { + prev = version; + if (!min) + min = version; + } else { + if (prev) { + set.push([min, prev]); + } + prev = null; + min = null; + } + } + if (min) + set.push([min, null]); + + const ranges = []; + for (const [min, max] of set) { + if (min === max) + ranges.push(min); + else if (!max && min === v[0]) + ranges.push('*'); + else if (!max) + ranges.push(`>=${min}`); + else if (min === v[0]) + ranges.push(`<=${max}`); + else + ranges.push(`${min} - ${max}`); + } + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range + }; + + const Range = range; + const Comparator = comparator; + const { ANY } = Comparator; + const satisfies = satisfies_1; + const compare = compare_1; + + // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: + // - Every simple range `r1, r2, ...` is a null set, OR + // - Every simple range `r1, r2, ...` which is not a null set is a subset of + // some `R1, R2, ...` + // + // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: + // - If c is only the ANY comparator + // - If C is only the ANY comparator, return true + // - Else if in prerelease mode, return false + // - else replace c with `[>=0.0.0]` + // - If C is only the ANY comparator + // - if in prerelease mode, return true + // - else replace C with `[>=0.0.0]` + // - Let EQ be the set of = comparators in c + // - If EQ is more than one, return true (null set) + // - Let GT be the highest > or >= comparator in c + // - Let LT be the lowest < or <= comparator in c + // - If GT and LT, and GT.semver > LT.semver, return true (null set) + // - If any C is a = range, and GT or LT are set, return false + // - If EQ + // - If GT, and EQ does not satisfy GT, return true (null set) + // - If LT, and EQ does not satisfy LT, return true (null set) + // - If EQ satisfies every C, return true + // - Else return false + // - If GT + // - If GT.semver is lower than any > or >= comp in C, return false + // - If GT is >=, and GT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the GT.semver tuple, return false + // - If LT + // - If LT.semver is greater than any < or <= comp in C, return false + // - If LT is <=, and LT.semver does not satisfy every C, return false + // - If GT.semver has a prerelease, and not in prerelease mode + // - If no C has a prerelease and the LT.semver tuple, return false + // - Else return true + + const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true + }; + + const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ]; + else + sub = [ new Comparator('>=0.0.0') ]; + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ]; + } + + const eqSet = new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options); + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options); + else + eqSet.add(c.semver); + } + + if (eqSet.size > 1) + return null + + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower; + let hasDomLT, hasDomGT; + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false; + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true + }; + + // >=1.2.3 is lower than >1.2.3 + const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a + }; + + // <=1.2.3 is higher than <1.2.3 + const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a + }; + + var subset_1 = subset; + + // just pre-load all the stuff that index.js lazily exports + const internalRe = re$5.exports; + var semver = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$1, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: comparator, + Range: range, + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1, + }; + + function unsafeTo64bitLE(n) { + // we want to represent the input as a 8-bytes array + if (n > Number.MAX_SAFE_INTEGER) { + throw new Error("Can't convert numbers > MAX_SAFE_INT"); + } + var byteArray = Buffer$k.alloc(8, 0); + for (var index = 0; index < byteArray.length; index++) { + var byte = n & 0xff; + byteArray[index] = byte; + n = (n - byte) / 256; + } + return byteArray; + } + function unsafeFrom64bitLE(byteArray) { + var value = 0; + if (byteArray.length != 8) { + throw new Error("Expected Bufffer of lenght 8"); + } + if (byteArray[7] != 0) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + if (byteArray[6] > 0x1f) { + throw new Error("Can't encode numbers > MAX_SAFE_INT"); + } + for (var i = byteArray.length - 1; i >= 0; i--) { + value = value * 256 + byteArray[i]; + } + return value; + } + var BufferWriter = /** @class */ (function () { + function BufferWriter() { + this.bufs = []; + } + BufferWriter.prototype.write = function (alloc, fn) { + var b = Buffer$k.alloc(alloc); + fn(b); + this.bufs.push(b); + }; + BufferWriter.prototype.writeUInt8 = function (i) { + this.write(1, function (b) { return b.writeUInt8(i, 0); }); + }; + BufferWriter.prototype.writeInt32 = function (i) { + this.write(4, function (b) { return b.writeInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt32 = function (i) { + this.write(4, function (b) { return b.writeUInt32LE(i, 0); }); + }; + BufferWriter.prototype.writeUInt64 = function (i) { + var bytes = unsafeTo64bitLE(i); + this.writeSlice(bytes); + }; + BufferWriter.prototype.writeVarInt = function (i) { + this.bufs.push(varuintBitcoin.encode(i)); + }; + BufferWriter.prototype.writeSlice = function (slice) { + this.bufs.push(Buffer$k.from(slice)); + }; + BufferWriter.prototype.writeVarSlice = function (slice) { + this.writeVarInt(slice.length); + this.writeSlice(slice); + }; + BufferWriter.prototype.buffer = function () { + return Buffer$k.concat(this.bufs); + }; + return BufferWriter; + }()); + var BufferReader = /** @class */ (function () { + function BufferReader(buffer, offset) { + if (offset === void 0) { offset = 0; } + this.buffer = buffer; + this.offset = offset; + } + BufferReader.prototype.available = function () { + return this.buffer.length - this.offset; + }; + BufferReader.prototype.readUInt8 = function () { + var result = this.buffer.readUInt8(this.offset); + this.offset++; + return result; + }; + BufferReader.prototype.readInt32 = function () { + var result = this.buffer.readInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt32 = function () { + var result = this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return result; + }; + BufferReader.prototype.readUInt64 = function () { + var buf = this.readSlice(8); + var n = unsafeFrom64bitLE(buf); + return n; + }; + BufferReader.prototype.readVarInt = function () { + var vi = varuintBitcoin.decode(this.buffer, this.offset); + this.offset += varuintBitcoin.decode.bytes; + return vi; + }; + BufferReader.prototype.readSlice = function (n) { + if (this.buffer.length < this.offset + n) { + throw new Error("Cannot read slice out of bounds"); + } + var result = this.buffer.slice(this.offset, this.offset + n); + this.offset += n; + return result; + }; + BufferReader.prototype.readVarSlice = function () { + return this.readSlice(this.readVarInt()); + }; + BufferReader.prototype.readVector = function () { + var count = this.readVarInt(); + var vector = []; + for (var i = 0; i < count; i++) + vector.push(this.readVarSlice()); + return vector; + }; + return BufferReader; + }()); + + // flow + var MAX_SCRIPT_BLOCK = 50; + var DEFAULT_VERSION = 1; + var DEFAULT_LOCKTIME = 0; + var DEFAULT_SEQUENCE = 0xffffffff; + var SIGHASH_ALL = 1; + var OP_DUP = 0x76; + var OP_HASH160 = 0xa9; + var HASH_SIZE = 0x14; + var OP_EQUAL = 0x87; + var OP_EQUALVERIFY = 0x88; + var OP_CHECKSIG = 0xac; + + function hashPublicKey(buffer) { + return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); + } + + var __extends$6 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var BaseAccount = /** @class */ (function () { + function BaseAccount(psbt, masterFp) { + this.psbt = psbt; + this.masterFp = masterFp; + } + return BaseAccount; + }()); + /** + * Superclass for single signature accounts. This will make sure that the pubkey + * arrays and path arrays in the method arguments contains exactly one element + * and calls an abstract method to do the actual work. + */ + var SingleKeyAccount = /** @class */ (function (_super) { + __extends$6(SingleKeyAccount, _super); + function SingleKeyAccount() { + return _super !== null && _super.apply(this, arguments) || this; + } + SingleKeyAccount.prototype.spendingCondition = function (pubkeys) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + return this.singleKeyCondition(pubkeys[0]); + }; + SingleKeyAccount.prototype.setInput = function (i, inputTx, spentOutput, pubkeys, pathElems) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (pathElems.length != 1) { + throw new Error("Expected single path, got " + pathElems.length); + } + this.setSingleKeyInput(i, inputTx, spentOutput, pubkeys[0], pathElems[0]); + }; + SingleKeyAccount.prototype.setOwnOutput = function (i, cond, pubkeys, paths) { + if (pubkeys.length != 1) { + throw new Error("Expected single key, got " + pubkeys.length); + } + if (paths.length != 1) { + throw new Error("Expected single path, got " + paths.length); + } + this.setSingleKeyOutput(i, cond, pubkeys[0], paths[0]); + }; + return SingleKeyAccount; + }(BaseAccount)); + var p2pkh = /** @class */ (function (_super) { + __extends$6(p2pkh, _super); + function p2pkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2pkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); + return { scriptPubKey: buf.buffer() }; + }; + p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2pkh.prototype.getDescriptorTemplate = function () { + return "pkh(@0)"; + }; + return p2pkh; + }(SingleKeyAccount)); + var p2tr = /** @class */ (function (_super) { + __extends$6(p2tr, _super); + function p2tr() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2tr.prototype.singleKeyCondition = function (pubkey) { + var xonlyPubkey = pubkey.slice(1); // x-only pubkey + var buf = new BufferWriter(); + var outputKey = this.getTaprootOutputKey(xonlyPubkey); + buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(outputKey); + return { scriptPubKey: buf.buffer() }; + }; + p2tr.prototype.setSingleKeyInput = function (i, _inputTx, spentOutput, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setInputTapBip32Derivation(i, xonly, [], this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2tr.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + var xonly = pubkey.slice(1); + this.psbt.setOutputTapBip32Derivation(i, xonly, [], this.masterFp, path); + }; + p2tr.prototype.getDescriptorTemplate = function () { + return "tr(@0)"; + }; + /* + The following two functions are copied from wallet-btc and adapted. + They should be moved to a library to avoid code reuse. + */ + p2tr.prototype.hashTapTweak = function (x) { + // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 + // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification + var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$k.concat([h, h, x])); + }; + /** + * Calculates a taproot output key from an internal key. This output key will be + * used as witness program in a taproot output. The internal key is tweaked + * according to recommendation in BIP341: + * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 + * + * @param internalPubkey A 32 byte x-only taproot internal key + * @returns The output key + */ + p2tr.prototype.getTaprootOutputKey = function (internalPubkey) { + if (internalPubkey.length != 32) { + throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); + } + // A BIP32 derived key can be converted to a schnorr pubkey by dropping + // the first byte, which represent the oddness/evenness. In schnorr all + // pubkeys are even. + // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion + var evenEcdsaPubkey = Buffer$k.concat([ + Buffer$k.from([0x02]), + internalPubkey, + ]); + var tweak = this.hashTapTweak(internalPubkey); + // Q = P + int(hash_TapTweak(bytes(P)))G + var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + // Convert to schnorr. + var outputSchnorrKey = outputEcdsaKey.slice(1); + // Create address + return outputSchnorrKey; + }; + return p2tr; + }(SingleKeyAccount)); + var p2wpkhWrapped = /** @class */ (function (_super) { + __extends$6(p2wpkhWrapped, _super); + function p2wpkhWrapped() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkhWrapped.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var redeemScript = this.createRedeemScript(pubkey); + var scriptHash = hashPublicKey(redeemScript); + buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(scriptHash); + buf.writeUInt8(OP_EQUAL); + return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; + }; + p2wpkhWrapped.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + var userSuppliedRedeemScript = spentOutput.cond.redeemScript; + var expectedRedeemScript = this.createRedeemScript(pubkey); + if (userSuppliedRedeemScript && + !expectedRedeemScript.equals(userSuppliedRedeemScript)) { + // At what point might a user set the redeemScript on its own? + throw new Error("User-supplied redeemScript " + userSuppliedRedeemScript.toString("hex") + " doesn't\n match expected " + expectedRedeemScript.toString("hex") + " for input " + i); + } + this.psbt.setInputRedeemScript(i, expectedRedeemScript); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkhWrapped.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputRedeemScript(i, cond.redeemScript); + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkhWrapped.prototype.getDescriptorTemplate = function () { + return "sh(wpkh(@0))"; + }; + p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { + var pubkeyHash = hashPublicKey(pubkey); + return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); + }; + return p2wpkhWrapped; + }(SingleKeyAccount)); + var p2wpkh = /** @class */ (function (_super) { + __extends$6(p2wpkh, _super); + function p2wpkh() { + return _super !== null && _super.apply(this, arguments) || this; + } + p2wpkh.prototype.singleKeyCondition = function (pubkey) { + var buf = new BufferWriter(); + var pubkeyHash = hashPublicKey(pubkey); + buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); + buf.writeSlice(pubkeyHash); + return { scriptPubKey: buf.buffer() }; + }; + p2wpkh.prototype.setSingleKeyInput = function (i, inputTx, spentOutput, pubkey, path) { + if (!inputTx) { + throw new Error("Full input base transaction required"); + } + this.psbt.setInputNonWitnessUtxo(i, inputTx); + this.psbt.setInputBip32Derivation(i, pubkey, this.masterFp, path); + this.psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.cond.scriptPubKey); + }; + p2wpkh.prototype.setSingleKeyOutput = function (i, cond, pubkey, path) { + this.psbt.setOutputBip32Derivation(i, pubkey, this.masterFp, path); + }; + p2wpkh.prototype.getDescriptorTemplate = function () { + return "wpkh(@0)"; + }; + return p2wpkh; + }(SingleKeyAccount)); + + var __read$3 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$3 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class implements the merkle tree used by Ledger Bitcoin app v2+, + * which is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md + */ + var Merkle = /** @class */ (function () { + function Merkle(leaves, hasher) { + if (hasher === void 0) { hasher = crypto_1.sha256; } + this.leaves = leaves; + this.h = hasher; + var nodes = this.calculateRoot(leaves); + this.rootNode = nodes.root; + this.leafNodes = nodes.leaves; + } + Merkle.prototype.getRoot = function () { + return this.rootNode.hash; + }; + Merkle.prototype.size = function () { + return this.leaves.length; + }; + Merkle.prototype.getLeaves = function () { + return this.leaves; + }; + Merkle.prototype.getLeafHash = function (index) { + return this.leafNodes[index].hash; + }; + Merkle.prototype.getProof = function (index) { + if (index >= this.leaves.length) + throw Error("Index out of bounds"); + return proveNode(this.leafNodes[index]); + }; + Merkle.prototype.calculateRoot = function (leaves) { + var n = leaves.length; + if (n == 0) { + return { + root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), + leaves: [] + }; + } + if (n == 1) { + var newNode = new Node(undefined, undefined, leaves[0]); + return { root: newNode, leaves: [newNode] }; + } + var leftCount = highestPowerOf2LessThan(n); + var leftBranch = this.calculateRoot(leaves.slice(0, leftCount)); + var rightBranch = this.calculateRoot(leaves.slice(leftCount)); + var leftChild = leftBranch.root; + var rightChild = rightBranch.root; + var hash = this.hashNode(leftChild.hash, rightChild.hash); + var node = new Node(leftChild, rightChild, hash); + leftChild.parent = node; + rightChild.parent = node; + return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; + }; + Merkle.prototype.hashNode = function (left, right) { + return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); + }; + return Merkle; + }()); + function hashLeaf(buf, hashFunction) { + if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } + return hashConcat(Buffer$k.from([0]), buf, hashFunction); + } + function hashConcat(bufA, bufB, hashFunction) { + return hashFunction(Buffer$k.concat([bufA, bufB])); + } + var Node = /** @class */ (function () { + function Node(left, right, hash) { + this.leftChild = left; + this.rightChild = right; + this.hash = hash; + } + Node.prototype.isLeaf = function () { + return this.leftChild == undefined; + }; + return Node; + }()); + function proveNode(node) { + if (!node.parent) { + return []; + } + if (node.parent.leftChild == node) { + if (!node.parent.rightChild) { + throw new Error("Expected right child to exist"); + } + return __spreadArray$3([node.parent.rightChild.hash], __read$3(proveNode(node.parent)), false); + } + else { + if (!node.parent.leftChild) { + throw new Error("Expected left child to exist"); + } + return __spreadArray$3([node.parent.leftChild.hash], __read$3(proveNode(node.parent)), false); + } + } + function highestPowerOf2LessThan(n) { + if (n < 2) { + throw Error("Expected n >= 2"); + } + if (isPowerOf2(n)) { + return n / 2; + } + return 1 << Math.floor(Math.log2(n)); + } + function isPowerOf2(n) { + return (n & (n - 1)) == 0; + } + + /** + * The Bitcon hardware app uses a descriptors-like thing to describe + * how to construct output scripts from keys. A "Wallet Policy" consists + * of a "Descriptor Template" and a list of "keys". A key is basically + * a serialized BIP32 extended public key with some added derivation path + * information. This is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/wallet.md + */ + var WalletPolicy = /** @class */ (function () { + /** + * For now, we only support default descriptor templates. + */ + function WalletPolicy(descriptorTemplate, key) { + this.descriptorTemplate = descriptorTemplate; + this.keys = [key]; + } + WalletPolicy.prototype.getWalletId = function () { + // wallet_id (sha256 of the wallet serialization), + return crypto_1.sha256(this.serialize()); + }; + WalletPolicy.prototype.serialize = function () { + var keyBuffers = this.keys.map(function (k) { + return Buffer$k.from(k, "ascii"); + }); + var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); + var buf = new BufferWriter(); + buf.writeUInt8(0x01); // wallet type (policy map) + buf.writeUInt8(0); // length of wallet name (empty string for default wallets) + buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); + buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); + return buf.buffer(); + }; + return WalletPolicy; + }()); + function createKey$1(masterFingerprint, path, xpub) { + var accountPath = pathArrayToString(path); + return "[" + masterFingerprint.toString("hex") + accountPath.substring(1) + "]" + xpub + "/**"; + } + + /** + * This implements the "Transaction Extractor" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#transaction-extractor). However + * the role is partially documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#transaction-extractor). + */ + function extract(psbt) { + var _a, _b; + var tx = new BufferWriter(); + tx.writeUInt32(psbt.getGlobalTxVersion()); + var isSegwit = !!psbt.getInputWitnessUtxo(0); + if (isSegwit) { + tx.writeSlice(Buffer$k.from([0, 1])); + } + var inputCount = psbt.getGlobalInputCount(); + tx.writeVarInt(inputCount); + var witnessWriter = new BufferWriter(); + for (var i = 0; i < inputCount; i++) { + tx.writeSlice(psbt.getInputPreviousTxid(i)); + tx.writeUInt32(psbt.getInputOutputIndex(i)); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); + tx.writeUInt32(psbt.getInputSequence(i)); + if (isSegwit) { + witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); + } + } + var outputCount = psbt.getGlobalOutputCount(); + tx.writeVarInt(outputCount); + for (var i = 0; i < outputCount; i++) { + tx.writeUInt64(psbt.getOutputAmount(i)); + tx.writeVarSlice(psbt.getOutputScript(i)); + } + tx.writeSlice(witnessWriter.buffer()); + tx.writeUInt32((_b = psbt.getGlobalFallbackLocktime()) !== null && _b !== void 0 ? _b : 0); + return tx.buffer(); + } + + var __extends$5 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign$5 = (undefined && undefined.__assign) || function () { + __assign$5 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$5.apply(this, arguments); + }; + var psbtGlobal; + (function (psbtGlobal) { + psbtGlobal[psbtGlobal["TX_VERSION"] = 2] = "TX_VERSION"; + psbtGlobal[psbtGlobal["FALLBACK_LOCKTIME"] = 3] = "FALLBACK_LOCKTIME"; + psbtGlobal[psbtGlobal["INPUT_COUNT"] = 4] = "INPUT_COUNT"; + psbtGlobal[psbtGlobal["OUTPUT_COUNT"] = 5] = "OUTPUT_COUNT"; + psbtGlobal[psbtGlobal["TX_MODIFIABLE"] = 6] = "TX_MODIFIABLE"; + psbtGlobal[psbtGlobal["VERSION"] = 251] = "VERSION"; + })(psbtGlobal || (psbtGlobal = {})); + var psbtIn; + (function (psbtIn) { + psbtIn[psbtIn["NON_WITNESS_UTXO"] = 0] = "NON_WITNESS_UTXO"; + psbtIn[psbtIn["WITNESS_UTXO"] = 1] = "WITNESS_UTXO"; + psbtIn[psbtIn["PARTIAL_SIG"] = 2] = "PARTIAL_SIG"; + psbtIn[psbtIn["SIGHASH_TYPE"] = 3] = "SIGHASH_TYPE"; + psbtIn[psbtIn["REDEEM_SCRIPT"] = 4] = "REDEEM_SCRIPT"; + psbtIn[psbtIn["BIP32_DERIVATION"] = 6] = "BIP32_DERIVATION"; + psbtIn[psbtIn["FINAL_SCRIPTSIG"] = 7] = "FINAL_SCRIPTSIG"; + psbtIn[psbtIn["FINAL_SCRIPTWITNESS"] = 8] = "FINAL_SCRIPTWITNESS"; + psbtIn[psbtIn["PREVIOUS_TXID"] = 14] = "PREVIOUS_TXID"; + psbtIn[psbtIn["OUTPUT_INDEX"] = 15] = "OUTPUT_INDEX"; + psbtIn[psbtIn["SEQUENCE"] = 16] = "SEQUENCE"; + psbtIn[psbtIn["TAP_KEY_SIG"] = 19] = "TAP_KEY_SIG"; + psbtIn[psbtIn["TAP_BIP32_DERIVATION"] = 22] = "TAP_BIP32_DERIVATION"; + })(psbtIn || (psbtIn = {})); + var psbtOut; + (function (psbtOut) { + psbtOut[psbtOut["REDEEM_SCRIPT"] = 0] = "REDEEM_SCRIPT"; + psbtOut[psbtOut["BIP_32_DERIVATION"] = 2] = "BIP_32_DERIVATION"; + psbtOut[psbtOut["AMOUNT"] = 3] = "AMOUNT"; + psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; + psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; + })(psbtOut || (psbtOut = {})); + var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var NoSuchEntry = /** @class */ (function (_super) { + __extends$5(NoSuchEntry, _super); + function NoSuchEntry() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NoSuchEntry; + }(Error)); + /** + * Implements Partially Signed Bitcoin Transaction version 2, BIP370, as + * documented at https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki + * and https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki + * + * A psbt is a data structure that can carry all relevant information about a + * transaction through all stages of the signing process. From constructing an + * unsigned transaction to extracting the final serialized transaction ready for + * broadcast. + * + * This implementation is limited to what's needed in ledgerjs to carry out its + * duties, which means that support for features like multisig or taproot script + * path spending are not implemented. Specifically, it supports p2pkh, + * p2wpkhWrappedInP2sh, p2wpkh and p2tr key path spending. + * + * This class is made purposefully dumb, so it's easy to add support for + * complemantary fields as needed in the future. + */ + var PsbtV2 = /** @class */ (function () { + function PsbtV2() { + this.globalMap = new Map(); + this.inputMaps = []; + this.outputMaps = []; + } + PsbtV2.prototype.setGlobalTxVersion = function (version) { + this.setGlobal(psbtGlobal.TX_VERSION, uint32LE(version)); + }; + PsbtV2.prototype.getGlobalTxVersion = function () { + return this.getGlobal(psbtGlobal.TX_VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalFallbackLocktime = function (locktime) { + this.setGlobal(psbtGlobal.FALLBACK_LOCKTIME, uint32LE(locktime)); + }; + PsbtV2.prototype.getGlobalFallbackLocktime = function () { + var _a; + return (_a = this.getGlobalOptional(psbtGlobal.FALLBACK_LOCKTIME)) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0); + }; + PsbtV2.prototype.setGlobalInputCount = function (inputCount) { + this.setGlobal(psbtGlobal.INPUT_COUNT, varint(inputCount)); + }; + PsbtV2.prototype.getGlobalInputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.INPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalOutputCount = function (outputCount) { + this.setGlobal(psbtGlobal.OUTPUT_COUNT, varint(outputCount)); + }; + PsbtV2.prototype.getGlobalOutputCount = function () { + return fromVarint(this.getGlobal(psbtGlobal.OUTPUT_COUNT)); + }; + PsbtV2.prototype.setGlobalTxModifiable = function (byte) { + this.setGlobal(psbtGlobal.TX_MODIFIABLE, byte); + }; + PsbtV2.prototype.getGlobalTxModifiable = function () { + return this.getGlobalOptional(psbtGlobal.TX_MODIFIABLE); + }; + PsbtV2.prototype.setGlobalPsbtVersion = function (psbtVersion) { + this.setGlobal(psbtGlobal.VERSION, uint32LE(psbtVersion)); + }; + PsbtV2.prototype.getGlobalPsbtVersion = function () { + return this.getGlobal(psbtGlobal.VERSION).readUInt32LE(0); + }; + PsbtV2.prototype.setInputNonWitnessUtxo = function (inputIndex, transaction) { + this.setInput(inputIndex, psbtIn.NON_WITNESS_UTXO, b(), transaction); + }; + PsbtV2.prototype.getInputNonWitnessUtxo = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.NON_WITNESS_UTXO, b()); + }; + PsbtV2.prototype.setInputWitnessUtxo = function (inputIndex, amount, scriptPubKey) { + var buf = new BufferWriter(); + buf.writeSlice(amount); + buf.writeVarSlice(scriptPubKey); + this.setInput(inputIndex, psbtIn.WITNESS_UTXO, b(), buf.buffer()); + }; + PsbtV2.prototype.getInputWitnessUtxo = function (inputIndex) { + var utxo = this.getInputOptional(inputIndex, psbtIn.WITNESS_UTXO, b()); + if (!utxo) + return undefined; + var buf = new BufferReader(utxo); + return { amount: buf.readSlice(8), scriptPubKey: buf.readVarSlice() }; + }; + PsbtV2.prototype.setInputPartialSig = function (inputIndex, pubkey, signature) { + this.setInput(inputIndex, psbtIn.PARTIAL_SIG, pubkey, signature); + }; + PsbtV2.prototype.getInputPartialSig = function (inputIndex, pubkey) { + return this.getInputOptional(inputIndex, psbtIn.PARTIAL_SIG, pubkey); + }; + PsbtV2.prototype.setInputSighashType = function (inputIndex, sigHashtype) { + this.setInput(inputIndex, psbtIn.SIGHASH_TYPE, b(), uint32LE(sigHashtype)); + }; + PsbtV2.prototype.getInputSighashType = function (inputIndex) { + var result = this.getInputOptional(inputIndex, psbtIn.SIGHASH_TYPE, b()); + if (!result) + return undefined; + return result.readUInt32LE(0); + }; + PsbtV2.prototype.setInputRedeemScript = function (inputIndex, redeemScript) { + this.setInput(inputIndex, psbtIn.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getInputRedeemScript = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setInputBip32Derivation = function (inputIndex, pubkey, masterFingerprint, path) { + if (pubkey.length != 33) + throw new Error("Invalid pubkey length: " + pubkey.length); + this.setInput(inputIndex, psbtIn.BIP32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getInputBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInputOptional(inputIndex, psbtIn.BIP32_DERIVATION, pubkey); + if (!buf) + return undefined; + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setInputFinalScriptsig = function (inputIndex, scriptSig) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTSIG, b(), scriptSig); + }; + PsbtV2.prototype.getInputFinalScriptsig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.FINAL_SCRIPTSIG, b()); + }; + PsbtV2.prototype.setInputFinalScriptwitness = function (inputIndex, scriptWitness) { + this.setInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b(), scriptWitness); + }; + PsbtV2.prototype.getInputFinalScriptwitness = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.FINAL_SCRIPTWITNESS, b()); + }; + PsbtV2.prototype.setInputPreviousTxId = function (inputIndex, txid) { + this.setInput(inputIndex, psbtIn.PREVIOUS_TXID, b(), txid); + }; + PsbtV2.prototype.getInputPreviousTxid = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.PREVIOUS_TXID, b()); + }; + PsbtV2.prototype.setInputOutputIndex = function (inputIndex, outputIndex) { + this.setInput(inputIndex, psbtIn.OUTPUT_INDEX, b(), uint32LE(outputIndex)); + }; + PsbtV2.prototype.getInputOutputIndex = function (inputIndex) { + return this.getInput(inputIndex, psbtIn.OUTPUT_INDEX, b()).readUInt32LE(0); + }; + PsbtV2.prototype.setInputSequence = function (inputIndex, sequence) { + this.setInput(inputIndex, psbtIn.SEQUENCE, b(), uint32LE(sequence)); + }; + PsbtV2.prototype.getInputSequence = function (inputIndex) { + var _a, _b; + return ((_b = (_a = this.getInputOptional(inputIndex, psbtIn.SEQUENCE, b())) === null || _a === void 0 ? void 0 : _a.readUInt32LE(0)) !== null && _b !== void 0 ? _b : 0xffffffff); + }; + PsbtV2.prototype.setInputTapKeySig = function (inputIndex, sig) { + this.setInput(inputIndex, psbtIn.TAP_KEY_SIG, b(), sig); + }; + PsbtV2.prototype.getInputTapKeySig = function (inputIndex) { + return this.getInputOptional(inputIndex, psbtIn.TAP_KEY_SIG, b()); + }; + PsbtV2.prototype.setInputTapBip32Derivation = function (inputIndex, pubkey, hashes, masterFingerprint, path) { + if (pubkey.length != 32) + throw new Error("Invalid pubkey length: " + pubkey.length); + var buf = this.encodeTapBip32Derivation(hashes, masterFingerprint, path); + this.setInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getInputTapBip32Derivation = function (inputIndex, pubkey) { + var buf = this.getInput(inputIndex, psbtIn.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.getInputKeyDatas = function (inputIndex, keyType) { + return this.getKeyDatas(this.inputMaps[inputIndex], keyType); + }; + PsbtV2.prototype.setOutputRedeemScript = function (outputIndex, redeemScript) { + this.setOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b(), redeemScript); + }; + PsbtV2.prototype.getOutputRedeemScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.REDEEM_SCRIPT, b()); + }; + PsbtV2.prototype.setOutputBip32Derivation = function (outputIndex, pubkey, masterFingerprint, path) { + this.setOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey, this.encodeBip32Derivation(masterFingerprint, path)); + }; + PsbtV2.prototype.getOutputBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.BIP_32_DERIVATION, pubkey); + return this.decodeBip32Derivation(buf); + }; + PsbtV2.prototype.setOutputAmount = function (outputIndex, amount) { + this.setOutput(outputIndex, psbtOut.AMOUNT, b(), uint64LE(amount)); + }; + PsbtV2.prototype.getOutputAmount = function (outputIndex) { + var buf = this.getOutput(outputIndex, psbtOut.AMOUNT, b()); + return unsafeFrom64bitLE(buf); + }; + PsbtV2.prototype.setOutputScript = function (outputIndex, scriptPubKey) { + this.setOutput(outputIndex, psbtOut.SCRIPT, b(), scriptPubKey); + }; + PsbtV2.prototype.getOutputScript = function (outputIndex) { + return this.getOutput(outputIndex, psbtOut.SCRIPT, b()); + }; + PsbtV2.prototype.setOutputTapBip32Derivation = function (outputIndex, pubkey, hashes, fingerprint, path) { + var buf = this.encodeTapBip32Derivation(hashes, fingerprint, path); + this.setOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey, buf); + }; + PsbtV2.prototype.getOutputTapBip32Derivation = function (outputIndex, pubkey) { + var buf = this.getOutput(outputIndex, psbtOut.TAP_BIP32_DERIVATION, pubkey); + return this.decodeTapBip32Derivation(buf); + }; + PsbtV2.prototype.deleteInputEntries = function (inputIndex, keyTypes) { + var _this = this; + var map = this.inputMaps[inputIndex]; + map.forEach(function (_v, k, m) { + if (_this.isKeyType(k, keyTypes)) { + m["delete"](k); + } + }); + }; + PsbtV2.prototype.copy = function (to) { + this.copyMap(this.globalMap, to.globalMap); + this.copyMaps(this.inputMaps, to.inputMaps); + this.copyMaps(this.outputMaps, to.outputMaps); + }; + PsbtV2.prototype.copyMaps = function (from, to) { + var _this = this; + from.forEach(function (m, index) { + var to_index = new Map(); + _this.copyMap(m, to_index); + to[index] = to_index; + }); + }; + PsbtV2.prototype.copyMap = function (from, to) { + from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); + }; + PsbtV2.prototype.serialize = function () { + var buf = new BufferWriter(); + buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); + serializeMap(buf, this.globalMap); + this.inputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + this.outputMaps.forEach(function (map) { + serializeMap(buf, map); + }); + return buf.buffer(); + }; + PsbtV2.prototype.deserialize = function (psbt) { + var buf = new BufferReader(psbt); + if (!buf.readSlice(5).equals(PSBT_MAGIC_BYTES)) { + throw new Error("Invalid magic bytes"); + } + while (this.readKeyPair(this.globalMap, buf)) + ; + for (var i = 0; i < this.getGlobalInputCount(); i++) { + this.inputMaps[i] = new Map(); + while (this.readKeyPair(this.inputMaps[i], buf)) + ; + } + for (var i = 0; i < this.getGlobalOutputCount(); i++) { + this.outputMaps[i] = new Map(); + while (this.readKeyPair(this.outputMaps[i], buf)) + ; + } + }; + PsbtV2.prototype.readKeyPair = function (map, buf) { + var keyLen = buf.readVarInt(); + if (keyLen == 0) { + return false; + } + var keyType = buf.readUInt8(); + var keyData = buf.readSlice(keyLen - 1); + var value = buf.readVarSlice(); + set(map, keyType, keyData, value); + return true; + }; + PsbtV2.prototype.getKeyDatas = function (map, keyType) { + var _this = this; + var result = []; + map.forEach(function (_v, k) { + if (_this.isKeyType(k, [keyType])) { + result.push(Buffer$k.from(k.substring(2), "hex")); + } + }); + return result; + }; + PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { + var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); + return keyTypes.some(function (k) { return k == keyType; }); + }; + PsbtV2.prototype.setGlobal = function (keyType, value) { + var key = new Key(keyType, Buffer$k.from([])); + this.globalMap.set(key.toString(), value); + }; + PsbtV2.prototype.getGlobal = function (keyType) { + return get(this.globalMap, keyType, b(), false); + }; + PsbtV2.prototype.getGlobalOptional = function (keyType) { + return get(this.globalMap, keyType, b(), true); + }; + PsbtV2.prototype.setInput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.inputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getInput = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getInputOptional = function (index, keyType, keyData) { + return get(this.inputMaps[index], keyType, keyData, true); + }; + PsbtV2.prototype.setOutput = function (index, keyType, keyData, value) { + set(this.getMap(index, this.outputMaps), keyType, keyData, value); + }; + PsbtV2.prototype.getOutput = function (index, keyType, keyData) { + return get(this.outputMaps[index], keyType, keyData, false); + }; + PsbtV2.prototype.getMap = function (index, maps) { + if (maps[index]) { + return maps[index]; + } + return (maps[index] = new Map()); + }; + PsbtV2.prototype.encodeBip32Derivation = function (masterFingerprint, path) { + var buf = new BufferWriter(); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + return this.readBip32Derivation(buf); + }; + PsbtV2.prototype.writeBip32Derivation = function (buf, masterFingerprint, path) { + buf.writeSlice(masterFingerprint); + path.forEach(function (element) { + buf.writeUInt32(element); + }); + }; + PsbtV2.prototype.readBip32Derivation = function (buf) { + var masterFingerprint = buf.readSlice(4); + var path = []; + while (buf.offset < buf.buffer.length) { + path.push(buf.readUInt32()); + } + return { masterFingerprint: masterFingerprint, path: path }; + }; + PsbtV2.prototype.encodeTapBip32Derivation = function (hashes, masterFingerprint, path) { + var buf = new BufferWriter(); + buf.writeVarInt(hashes.length); + hashes.forEach(function (h) { + buf.writeSlice(h); + }); + this.writeBip32Derivation(buf, masterFingerprint, path); + return buf.buffer(); + }; + PsbtV2.prototype.decodeTapBip32Derivation = function (buffer) { + var buf = new BufferReader(buffer); + var hashCount = buf.readVarInt(); + var hashes = []; + for (var i = 0; i < hashCount; i++) { + hashes.push(buf.readSlice(32)); + } + var deriv = this.readBip32Derivation(buf); + return __assign$5({ hashes: hashes }, deriv); + }; + return PsbtV2; + }()); + function get(map, keyType, keyData, acceptUndefined) { + if (!map) + throw Error("No such map"); + var key = new Key(keyType, keyData); + var value = map.get(key.toString()); + if (!value) { + if (acceptUndefined) { + return undefined; + } + throw new NoSuchEntry(key.toString()); + } + // Make sure to return a copy, to protect the underlying data. + return Buffer$k.from(value); + } + var Key = /** @class */ (function () { + function Key(keyType, keyData) { + this.keyType = keyType; + this.keyData = keyData; + } + Key.prototype.toString = function () { + var buf = new BufferWriter(); + this.toBuffer(buf); + return buf.buffer().toString("hex"); + }; + Key.prototype.serialize = function (buf) { + buf.writeVarInt(1 + this.keyData.length); + this.toBuffer(buf); + }; + Key.prototype.toBuffer = function (buf) { + buf.writeUInt8(this.keyType); + buf.writeSlice(this.keyData); + }; + return Key; + }()); + var KeyPair = /** @class */ (function () { + function KeyPair(key, value) { + this.key = key; + this.value = value; + } + KeyPair.prototype.serialize = function (buf) { + this.key.serialize(buf); + buf.writeVarSlice(this.value); + }; + return KeyPair; + }()); + function createKey(buf) { + return new Key(buf.readUInt8(0), buf.slice(1)); + } + function serializeMap(buf, map) { + for (var k in map.keys) { + var value = map.get(k); + var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); + keyPair.serialize(buf); + } + buf.writeUInt8(0); + } + function b() { + return Buffer$k.from([]); + } + function set(map, keyType, keyData, value) { + var key = new Key(keyType, keyData); + map.set(key.toString(), value); + } + function uint32LE(n) { + var b = Buffer$k.alloc(4); + b.writeUInt32LE(n, 0); + return b; + } + function uint64LE(n) { + return unsafeTo64bitLE(n); + } + function varint(n) { + var b = new BufferWriter(); + b.writeVarInt(n); + return b.buffer(); + } + function fromVarint(buf) { + return new BufferReader(buf).readVarInt(); + } + + /** + * This roughly implements the "input finalizer" role of BIP370 (PSBTv2 + * https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki). However + * the role is documented in BIP174 (PSBTv0 + * https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki). + * + * Verify that all inputs have a signature, and set inputFinalScriptwitness + * and/or inputFinalScriptSig depending on the type of the spent outputs. Clean + * fields that aren't useful anymore, partial signatures, redeem script and + * derivation paths. + * + * @param psbt The psbt with all signatures added as partial sigs, either + * through PSBT_IN_PARTIAL_SIG or PSBT_IN_TAP_KEY_SIG + */ + function finalize(psbt) { + // First check that each input has a signature + var inputCount = psbt.getGlobalInputCount(); + for (var i = 0; i < inputCount; i++) { + var legacyPubkeys = psbt.getInputKeyDatas(i, psbtIn.PARTIAL_SIG); + var taprootSig = psbt.getInputTapKeySig(i); + if (legacyPubkeys.length == 0 && !taprootSig) { + throw Error("No signature for input " + i + " present"); + } + if (legacyPubkeys.length > 0) { + if (legacyPubkeys.length > 1) { + throw Error("Expected exactly one signature, got " + legacyPubkeys.length); + } + if (taprootSig) { + throw Error("Both taproot and non-taproot signatures present."); + } + var isSegwitV0 = !!psbt.getInputWitnessUtxo(i); + var redeemScript = psbt.getInputRedeemScript(i); + var isWrappedSegwit = !!redeemScript; + var signature = psbt.getInputPartialSig(i, legacyPubkeys[0]); + if (!signature) + throw new Error("Expected partial signature for input " + i); + if (isSegwitV0) { + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(2); + witnessBuf.writeVarInt(signature.length); + witnessBuf.writeSlice(signature); + witnessBuf.writeVarInt(legacyPubkeys[0].length); + witnessBuf.writeSlice(legacyPubkeys[0]); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + if (isWrappedSegwit) { + if (!redeemScript || redeemScript.length == 0) { + throw new Error("Expected non-empty redeemscript. Can't finalize intput " + i); + } + var scriptSigBuf = new BufferWriter(); + // Push redeemScript length + scriptSigBuf.writeUInt8(redeemScript.length); + scriptSigBuf.writeSlice(redeemScript); + psbt.setInputFinalScriptsig(i, scriptSigBuf.buffer()); + } + } + else { + // Legacy input + var scriptSig = new BufferWriter(); + writePush(scriptSig, signature); + writePush(scriptSig, legacyPubkeys[0]); + psbt.setInputFinalScriptsig(i, scriptSig.buffer()); + } + } + else { + // Taproot input + var signature = psbt.getInputTapKeySig(i); + if (!signature) { + throw Error("No taproot signature found"); + } + if (signature.length != 64 && signature.length != 65) { + throw Error("Unexpected length of schnorr signature."); + } + var witnessBuf = new BufferWriter(); + witnessBuf.writeVarInt(1); + witnessBuf.writeVarSlice(signature); + psbt.setInputFinalScriptwitness(i, witnessBuf.buffer()); + } + clearFinalizedInput(psbt, i); + } + } + /** + * Deletes fields that are no longer neccesary from the psbt. + * + * Note, the spec doesn't say anything about removing ouput fields + * like PSBT_OUT_BIP32_DERIVATION_PATH and others, so we keep them + * without actually knowing why. I think we should remove them too. + */ + function clearFinalizedInput(psbt, inputIndex) { + var keyTypes = [ + psbtIn.BIP32_DERIVATION, + psbtIn.PARTIAL_SIG, + psbtIn.TAP_BIP32_DERIVATION, + psbtIn.TAP_KEY_SIG, + ]; + var witnessUtxoAvailable = !!psbt.getInputWitnessUtxo(inputIndex); + var nonWitnessUtxoAvailable = !!psbt.getInputNonWitnessUtxo(inputIndex); + if (witnessUtxoAvailable && nonWitnessUtxoAvailable) { + // Remove NON_WITNESS_UTXO for segwit v0 as it's only needed while signing. + // Segwit v1 doesn't have NON_WITNESS_UTXO set. + // See https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#cite_note-7 + keyTypes.push(psbtIn.NON_WITNESS_UTXO); + } + psbt.deleteInputEntries(inputIndex, keyTypes); + } + /** + * Writes a script push operation to buf, which looks different + * depending on the size of the data. See + * https://en.bitcoin.it/wiki/Script#Constants + * + * @param buf the BufferWriter to write to + * @param data the Buffer to be pushed. + */ + function writePush(buf, data) { + if (data.length <= 75) { + buf.writeUInt8(data.length); + } + else if (data.length <= 256) { + buf.writeUInt8(76); + buf.writeUInt8(data.length); + } + else if (data.length <= 256 * 256) { + buf.writeUInt8(77); + var b = Buffer$k.alloc(2); + b.writeUInt16LE(data.length, 0); + buf.writeSlice(b); + } + buf.writeSlice(data); + } + + function getVarint(data, offset) { + if (data[offset] < 0xfd) { + return [data[offset], 1]; + } + if (data[offset] === 0xfd) { + return [(data[offset + 2] << 8) + data[offset + 1], 3]; + } + if (data[offset] === 0xfe) { + return [ + (data[offset + 4] << 24) + + (data[offset + 3] << 16) + + (data[offset + 2] << 8) + + data[offset + 1], + 5, + ]; + } + throw new Error("getVarint called with unexpected parameters"); + } + function createVarint(value) { + if (value < 0xfd) { + var buffer_1 = Buffer$k.alloc(1); + buffer_1[0] = value; + return buffer_1; + } + if (value <= 0xffff) { + var buffer_2 = Buffer$k.alloc(3); + buffer_2[0] = 0xfd; + buffer_2[1] = value & 0xff; + buffer_2[2] = (value >> 8) & 0xff; + return buffer_2; + } + var buffer = Buffer$k.alloc(5); + buffer[0] = 0xfe; + buffer[1] = value & 0xff; + buffer[2] = (value >> 8) & 0xff; + buffer[3] = (value >> 16) & 0xff; + buffer[4] = (value >> 24) & 0xff; + return buffer; + } + + /** + @example + const tx1 = btc.splitTransaction("01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000"); + const outputScript = btc.serializeTransactionOutputs(tx1).toString('hex'); + */ + function serializeTransactionOutputs(_a) { + var outputs = _a.outputs; + var outputBuffer = Buffer$k.alloc(0); + if (typeof outputs !== "undefined") { + outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); + outputs.forEach(function (output) { + outputBuffer = Buffer$k.concat([ + outputBuffer, + output.amount, + createVarint(output.script.length), + output.script, + ]); + }); + } + return outputBuffer; + } + function serializeTransaction(transaction, skipWitness, timestamp, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var isBech32 = additionals.includes("bech32"); + var inputBuffer = Buffer$k.alloc(0); + var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; + transaction.inputs.forEach(function (input) { + inputBuffer = + isDecred || isBech32 + ? Buffer$k.concat([ + inputBuffer, + input.prevout, + Buffer$k.from([0x00]), + input.sequence, + ]) + : Buffer$k.concat([ + inputBuffer, + input.prevout, + createVarint(input.script.length), + input.script, + input.sequence, + ]); + }); + var outputBuffer = serializeTransactionOutputs(transaction); + if (typeof transaction.outputs !== "undefined" && + typeof transaction.locktime !== "undefined") { + outputBuffer = Buffer$k.concat([ + outputBuffer, + (useWitness && transaction.witness) || Buffer$k.alloc(0), + transaction.locktime, + transaction.nExpiryHeight || Buffer$k.alloc(0), + transaction.extraData || Buffer$k.alloc(0), + ]); + } + return Buffer$k.concat([ + transaction.version, + timestamp ? timestamp : Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), + createVarint(transaction.inputs.length), + inputBuffer, + outputBuffer, + ]); + } + + var __awaiter$f = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$f = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var newSupportedApps = ["Bitcoin", "Bitcoin Test"]; + function canSupportApp(appAndVersion) { + return (newSupportedApps.includes(appAndVersion.name) && + semver.major(appAndVersion.version) >= 2); + } + /** + * This class implements the same interface as BtcOld (formerly + * named Btc), but interacts with Bitcoin hardware app version 2+ + * which uses a totally new APDU protocol. This new + * protocol is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + * + * Since the interface must remain compatible with BtcOld, the methods + * of this class are quite clunky, because it needs to adapt legacy + * input data into the PSBT process. In the future, a new interface should + * be developed that exposes PSBT to the outer world, which would render + * a much cleaner implementation. + */ + var BtcNew = /** @class */ (function () { + function BtcNew(client) { + this.client = client; + } + /** + * This is a new method that allow users to get an xpub at a standard path. + * Standard paths are described at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description + * + * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): + * M/44'/N'/x'/** + * M/48'/N'/x'/y'/** + * M/49'/N'/x'/** + * M/84'/N'/x'/** + * M/86'/N'/x'/** + * + * The method was added because of added security in the hardware app v2+. The + * new hardware app will allow export of any xpub up to and including the + * deepest hardened key of standard derivation paths, whereas the old app + * would allow export of any key. + * + * This caused an issue for callers of this class, who only had + * getWalletPublicKey() to call which means they have to constuct xpub + * themselves: + * + * Suppose a user of this class wants to create an account xpub on a standard + * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) + * by requesting the parent key M/44'/0'. The new app won't allow that, because + * it only allows exporting deepest level hardened path. So the options are to + * allow requesting M/44'/0' from the app, or to add a new function + * "getWalletXpub". + * + * We opted for adding a new function, which can greatly simplify client code. + */ + BtcNew.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$f(this, void 0, void 0, function () { + var pathElements, xpub, xpubComponents; + return __generator$f(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _b.sent(); + xpubComponents = getXpubComponents(xpub); + if (xpubComponents.version != xpubVersion) { + throw new Error("Expected xpub version " + xpubVersion + " doesn't match the xpub version from the device " + xpubComponents.version); + } + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * This method returns a public key, a bitcoin address, and and a chaincode + * for a specific derivation path. + * + * Limitation: If the path is not a leaf node of a standard path, the address + * will be the empty string "", see this.getWalletAddress() for details. + */ + BtcNew.prototype.getWalletPublicKey = function (path, opts) { + var _a, _b; + return __awaiter$f(this, void 0, void 0, function () { + var pathElements, xpub, display, address, components, uncompressedPubkey; + return __generator$f(this, function (_c) { + switch (_c.label) { + case 0: + pathElements = pathStringToArray(path); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpub = _c.sent(); + display = (_a = opts === null || opts === void 0 ? void 0 : opts.verify) !== null && _a !== void 0 ? _a : false; + return [4 /*yield*/, this.getWalletAddress(pathElements, descrTemplFrom((_b = opts === null || opts === void 0 ? void 0 : opts.format) !== null && _b !== void 0 ? _b : "legacy"), display)]; + case 2: + address = _c.sent(); + components = getXpubComponents(xpub); + uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); + return [2 /*return*/, { + publicKey: uncompressedPubkey.toString("hex"), + bitcoinAddress: address, + chainCode: components.chaincode.toString("hex") + }]; + } + }); + }); + }; + /** + * Get an address for the specified path. + * + * If display is true, we must get the address from the device, which would require + * us to determine WalletPolicy. This requires two *extra* queries to the device, one + * for the account xpub and one for master key fingerprint. + * + * If display is false we *could* generate the address ourselves, but chose to + * get it from the device to save development time. However, it shouldn't take + * too much time to implement local address generation. + * + * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no + * way to get the address from the device. In this case we have to create it + * ourselves, but we don't at this time, and instead return an empty ("") address. + */ + BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { + return __awaiter$f(this, void 0, void 0, function () { + var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; + return __generator$f(this, function (_a) { + switch (_a.label) { + case 0: + accountPath = hardenedPathOf(pathElements); + if (accountPath.length + 2 != pathElements.length) { + return [2 /*return*/, ""]; + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 1: + accountXpub = _a.sent(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 2: + masterFingerprint = _a.sent(); + policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); + changeAndIndex = pathElements.slice(-2, pathElements.length); + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + } + }); + }); + }; + /** + * Build and sign a transaction. See Btc.createPaymentTransactionNew for + * details on how to use this method. + * + * This method will convert the legacy arguments, CreateTransactionArg, into + * a psbt which is finally signed and finalized, and the extracted fully signed + * transaction is returned. + */ + BtcNew.prototype.createPaymentTransactionNew = function (arg) { + return __awaiter$f(this, void 0, void 0, function () { + var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; + return __generator$f(this, function (_a) { + switch (_a.label) { + case 0: + inputCount = arg.inputs.length; + if (inputCount == 0) { + throw Error("No inputs"); + } + psbt = new PsbtV2(); + return [4 /*yield*/, this.client.getMasterFingerprint()]; + case 1: + masterFp = _a.sent(); + accountType = accountTypeFromArg(arg, psbt, masterFp); + if (arg.lockTime != undefined) { + // The signer will assume locktime 0 if unset + psbt.setGlobalFallbackLocktime(arg.lockTime); + } + psbt.setGlobalInputCount(inputCount); + psbt.setGlobalPsbtVersion(2); + psbt.setGlobalTxVersion(2); + notifyCount = 0; + progress = function () { + if (!arg.onDeviceStreaming) + return; + arg.onDeviceStreaming({ + total: 2 * inputCount, + index: notifyCount, + progress: ++notifyCount / (2 * inputCount) + }); + }; + accountXpub = ""; + accountPath = []; + i = 0; + _a.label = 2; + case 2: + if (!(i < inputCount)) return [3 /*break*/, 7]; + progress(); + pathElems = pathStringToArray(arg.associatedKeysets[i]); + if (!(accountXpub == "")) return [3 /*break*/, 4]; + // We assume all inputs belong to the same account so we set + // the account xpub and path based on the first input. + accountPath = pathElems.slice(0, -2); + return [4 /*yield*/, this.client.getExtendedPubkey(false, accountPath)]; + case 3: + accountXpub = _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, this.setInput(psbt, i, arg.inputs[i], pathElems, accountType, masterFp, arg.sigHashType)]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + i++; + return [3 /*break*/, 2]; + case 7: + outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); + outputsBufferReader = new BufferReader(outputsConcat); + outputCount = outputsBufferReader.readVarInt(); + psbt.setGlobalOutputCount(outputCount); + return [4 /*yield*/, this.outputScriptAt(accountPath, accountType, arg.changePath)]; + case 8: + changeData = _a.sent(); + changeFound = !changeData; + for (i = 0; i < outputCount; i++) { + amount = Number(outputsBufferReader.readUInt64()); + outputScript = outputsBufferReader.readVarSlice(); + psbt.setOutputAmount(i, amount); + psbt.setOutputScript(i, outputScript); + isChange = changeData && outputScript.equals(changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey); + if (isChange) { + changeFound = true; + changePath = pathStringToArray(arg.changePath); + pubkey = changeData.pubkey; + accountType.setOwnOutput(i, changeData.cond, [pubkey], [changePath]); + } + } + if (!changeFound) { + throw new Error("Change script not found among outputs! " + + (changeData === null || changeData === void 0 ? void 0 : changeData.cond.scriptPubKey.toString("hex"))); + } + key = createKey$1(masterFp, accountPath, accountXpub); + p = new WalletPolicy(accountType.getDescriptorTemplate(), key); + // This is cheating, because it's not actually requested on the + // device yet, but it will be, soonish. + if (arg.onDeviceSignatureRequested) + arg.onDeviceSignatureRequested(); + firstSigned = false; + progressCallback = function () { + if (!firstSigned) { + firstSigned = true; + arg.onDeviceSignatureGranted && arg.onDeviceSignatureGranted(); + } + progress(); + }; + return [4 /*yield*/, this.signPsbt(psbt, p, progressCallback)]; + case 9: + _a.sent(); + finalize(psbt); + serializedTx = extract(psbt); + return [2 /*return*/, serializedTx.toString("hex")]; + } + }); + }); + }; + /** + * Calculates an output script along with public key and possible redeemScript + * from a path and accountType. The accountPath must be a prefix of path. + * + * @returns an object with output script (property "script"), redeemScript (if + * wrapped p2wpkh), and pubkey at provided path. The values of these three + * properties depend on the accountType used. + */ + BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { + return __awaiter$f(this, void 0, void 0, function () { + var pathElems, i, xpub, pubkey, cond; + return __generator$f(this, function (_a) { + switch (_a.label) { + case 0: + if (!path) + return [2 /*return*/, undefined]; + pathElems = pathStringToArray(path); + // Make sure path is in our account, otherwise something fishy is probably + // going on. + for (i = 0; i < accountPath.length; i++) { + if (accountPath[i] != pathElems[i]) { + throw new Error("Path " + path + " not in account " + pathArrayToString(accountPath)); + } + } + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElems)]; + case 1: + xpub = _a.sent(); + pubkey = pubkeyFromXpub(xpub); + cond = accountType.spendingCondition([pubkey]); + return [2 /*return*/, { cond: cond, pubkey: pubkey }]; + } + }); + }); + }; + /** + * Adds relevant data about an input to the psbt. This includes sequence, + * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, + * public key and its derivation path. + */ + BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { + return __awaiter$f(this, void 0, void 0, function () { + var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; + return __generator$f(this, function (_a) { + switch (_a.label) { + case 0: + inputTx = input[0]; + spentOutputIndex = input[1]; + redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; + sequence = input[3]; + if (sequence != undefined) { + psbt.setInputSequence(i, sequence); + } + if (sigHashType != undefined) { + psbt.setInputSighashType(i, sigHashType); + } + inputTxBuffer = serializeTransaction(inputTx, true); + inputTxid = crypto_1.hash256(inputTxBuffer); + return [4 /*yield*/, this.client.getExtendedPubkey(false, pathElements)]; + case 1: + xpubBase58 = _a.sent(); + pubkey = pubkeyFromXpub(xpubBase58); + if (!inputTx.outputs) + throw Error("Missing outputs array in transaction to sign"); + spentTxOutput = inputTx.outputs[spentOutputIndex]; + spendCondition = { + scriptPubKey: spentTxOutput.script, + redeemScript: redeemScript + }; + spentOutput = { cond: spendCondition, amount: spentTxOutput.amount }; + accountType.setInput(i, inputTxBuffer, spentOutput, [pubkey], [pathElements]); + psbt.setInputPreviousTxId(i, inputTxid); + psbt.setInputOutputIndex(i, spentOutputIndex); + return [2 /*return*/]; + } + }); + }); + }; + /** + * This implements the "Signer" role of the BIP370 transaction signing + * process. + * + * It ssks the hardware device to sign the a psbt using the specified wallet + * policy. This method assumes BIP32 derived keys are used for all inputs, see + * comment in-line. The signatures returned from the hardware device is added + * to the appropriate input fields of the PSBT. + */ + BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { + return __awaiter$f(this, void 0, void 0, function () { + var sigs; + return __generator$f(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; + case 1: + sigs = _a.sent(); + sigs.forEach(function (v, k) { + // Note: Looking at BIP32 derivation does not work in the generic case, + // since some inputs might not have a BIP32-derived pubkey. + var pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); + var pubkey; + if (pubkeys.length != 1) { + // No legacy BIP32_DERIVATION, assume we're using taproot. + pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); + if (pubkey.length == 0) { + throw Error("Missing pubkey derivation for input " + k); + } + psbt.setInputTapKeySig(k, v); + } + else { + pubkey = pubkeys[0]; + psbt.setInputPartialSig(k, pubkey, v); + } + }); + return [2 /*return*/]; + } + }); + }); + }; + return BtcNew; + }()); + function descrTemplFrom(addressFormat) { + if (addressFormat == "legacy") + return "pkh(@0)"; + if (addressFormat == "p2sh") + return "sh(wpkh(@0))"; + if (addressFormat == "bech32") + return "wpkh(@0)"; + if (addressFormat == "bech32m") + return "tr(@0)"; + throw new Error("Unsupported address format " + addressFormat); + } + function accountTypeFromArg(arg, psbt, masterFp) { + if (arg.additionals.includes("bech32m")) + return new p2tr(psbt, masterFp); + if (arg.additionals.includes("bech32")) + return new p2wpkh(psbt, masterFp); + if (arg.segwit) + return new p2wpkhWrapped(psbt, masterFp); + return new p2pkh(psbt, masterFp); + } + + var id$1 = 0; + var subscribers = []; + /** + * log something + * @param type a namespaced identifier of the log (it is not a level like "debug", "error" but more like "apdu-in", "apdu-out", etc...) + * @param message a clear message of the log associated to the type + */ + var log = function (type, message, data) { + var obj = { + type: type, + id: String(++id$1), + date: new Date() + }; + if (message) + obj.message = message; + if (data) + obj.data = data; + dispatch(obj); + }; + /** + * listen to logs. + * @param cb that is called for each future log() with the Log object + * @return a function that can be called to unsubscribe the listener + */ + var listen = function (cb) { + subscribers.push(cb); + return function () { + var i = subscribers.indexOf(cb); + if (i !== -1) { + // equivalent of subscribers.splice(i, 1) // https://twitter.com/Rich_Harris/status/1125850391155965952 + subscribers[i] = subscribers[subscribers.length - 1]; + subscribers.pop(); + } + }; + }; + function dispatch(log) { + for (var i = 0; i < subscribers.length; i++) { + try { + subscribers[i](log); + } + catch (e) { + console.error(e); + } + } + } + if (typeof window !== "undefined") { + window.__ledgerLogsListen = listen; + } + + var index = /*#__PURE__*/Object.freeze({ + __proto__: null, + log: log, + listen: listen + }); + + var __assign$4 = (undefined && undefined.__assign) || function () { + __assign$4 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$4.apply(this, arguments); + }; + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var addressFormatMap = { + legacy: 0, + p2sh: 1, + bech32: 2, + cashaddr: 3 + }; + function getWalletPublicKey(transport, options) { + return __awaiter$e(this, void 0, void 0, function () { + var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; + return __generator$e(this, function (_b) { + switch (_b.label) { + case 0: + _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; + if (!(format in addressFormatMap)) { + throw new Error("btc.getWalletPublicKey invalid format=" + format); + } + buffer = bip32asBuffer(path); + p1 = verify ? 1 : 0; + p2 = addressFormatMap[format]; + return [4 /*yield*/, transport.send(0xe0, 0x40, p1, p2, buffer)]; + case 1: + response = _b.sent(); + publicKeyLength = response[0]; + addressLength = response[1 + publicKeyLength]; + publicKey = response.slice(1, 1 + publicKeyLength).toString("hex"); + bitcoinAddress = response + .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength) + .toString("ascii"); + chainCode = response + .slice(1 + publicKeyLength + 1 + addressLength, 1 + publicKeyLength + 1 + addressLength + 32) + .toString("hex"); + return [2 /*return*/, { + publicKey: publicKey, + bitcoinAddress: bitcoinAddress, + chainCode: chainCode + }]; + } + }); + }); + } + + /** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var browser = invariant; + + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$7 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function getTrustedInputRaw(transport, transactionData, indexLookup) { + return __awaiter$d(this, void 0, void 0, function () { + var data, firstRound, prefix, trustedInput, res; + return __generator$d(this, function (_a) { + switch (_a.label) { + case 0: + firstRound = false; + if (typeof indexLookup === "number") { + firstRound = true; + prefix = Buffer$k.alloc(4); + prefix.writeUInt32BE(indexLookup, 0); + data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); + } + else { + data = transactionData; + } + return [4 /*yield*/, transport.send(0xe0, 0x42, firstRound ? 0x00 : 0x80, 0x00, data)]; + case 1: + trustedInput = _a.sent(); + res = trustedInput.slice(0, trustedInput.length - 2).toString("hex"); + return [2 /*return*/, res]; + } + }); + }); + } + function getTrustedInput(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$d(this, void 0, void 0, function () { + var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; + var e_1, _a, e_2, _b; + var _this = this; + return __generator$d(this, function (_c) { + switch (_c.label) { + case 0: + version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; + if (!outputs || !locktime) { + throw new Error("getTrustedInput: locktime & outputs is expected"); + } + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + processScriptBlocks = function (script, sequence) { return __awaiter$d(_this, void 0, void 0, function () { + var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; + var e_3, _a; + return __generator$d(this, function (_b) { + switch (_b.label) { + case 0: + seq = sequence || Buffer$k.alloc(0); + scriptBlocks = []; + offset = 0; + while (offset !== script.length) { + blockSize = script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : script.length - offset; + if (offset + blockSize !== script.length) { + scriptBlocks.push(script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); + } + offset += blockSize; + } + // Handle case when no script length: we still want to pass the sequence + // relatable: https://github.com/LedgerHQ/ledger-live-desktop/issues/1386 + if (script.length === 0) { + scriptBlocks.push(seq); + } + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + scriptBlocks_1 = __values$7(scriptBlocks), scriptBlocks_1_1 = scriptBlocks_1.next(); + _b.label = 2; + case 2: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 5]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, getTrustedInputRaw(transport, scriptBlock)]; + case 3: + res = _b.sent(); + _b.label = 4; + case 4: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 2]; + case 5: return [3 /*break*/, 8]; + case 6: + e_3_1 = _b.sent(); + e_3 = { error: e_3_1 }; + return [3 /*break*/, 8]; + case 7: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_a = scriptBlocks_1["return"])) _a.call(scriptBlocks_1); + } + finally { if (e_3) throw e_3.error; } + return [7 /*endfinally*/]; + case 8: return [2 /*return*/, res]; + } + }); + }); }; + processWholeScriptBlock = function (block) { + return getTrustedInputRaw(transport, block); + }; + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ + transaction.version, + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + createVarint(inputs.length), + ]), indexLookup)]; + case 1: + _c.sent(); + _c.label = 2; + case 2: + _c.trys.push([2, 8, 9, 10]); + inputs_1 = __values$7(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 3; + case 3: + if (!!inputs_1_1.done) return [3 /*break*/, 7]; + input = inputs_1_1.value; + isXSTV2 = isXST && + Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; + treeField = isDecred + ? input.tree || Buffer$k.from([0x00]) + : Buffer$k.alloc(0); + data = Buffer$k.concat([ + input.prevout, + treeField, + isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 4: + _c.sent(); + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + return [4 /*yield*/, (isDecred + ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) + : isXSTV2 + ? processWholeScriptBlock(input.sequence) + : processScriptBlocks(input.script, input.sequence))]; + case 5: + // iteration (eachSeries) ended + // TODO notify progress + // deferred.notify("input"); + // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 + _c.sent(); + _c.label = 6; + case 6: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 3]; + case 7: return [3 /*break*/, 10]; + case 8: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 10]; + case 9: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 10: return [4 /*yield*/, getTrustedInputRaw(transport, createVarint(outputs.length))]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + _c.trys.push([12, 17, 18, 19]); + outputs_1 = __values$7(outputs), outputs_1_1 = outputs_1.next(); + _c.label = 13; + case 13: + if (!!outputs_1_1.done) return [3 /*break*/, 16]; + output = outputs_1_1.value; + data = Buffer$k.concat([ + output.amount, + isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), + createVarint(output.script.length), + output.script, + ]); + return [4 /*yield*/, getTrustedInputRaw(transport, data)]; + case 14: + _c.sent(); + _c.label = 15; + case 15: + outputs_1_1 = outputs_1.next(); + return [3 /*break*/, 13]; + case 16: return [3 /*break*/, 19]; + case 17: + e_2_1 = _c.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 19]; + case 18: + try { + if (outputs_1_1 && !outputs_1_1.done && (_b = outputs_1["return"])) _b.call(outputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 19: + endData = []; + if (nExpiryHeight && nExpiryHeight.length > 0) { + endData.push(nExpiryHeight); + } + if (extraData && extraData.length > 0) { + endData.push(extraData); + } + if (endData.length) { + data = Buffer$k.concat(endData); + extraPart = isDecred + ? data + : Buffer$k.concat([createVarint(data.length), data]); + } + return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; + case 20: + res = _c.sent(); + browser(res, "missing result in processScriptBlocks"); + return [2 /*return*/, res]; + } + }); + }); + } + + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$6 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + function startUntrustedHashTransactionInputRaw(transport, newTransaction, firstRound, transactionData, bip143, overwinter, additionals) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + var p2 = additionals.includes("cashaddr") + ? 0x03 + : bip143 + ? additionals.includes("sapling") + ? 0x05 + : overwinter + ? 0x04 + : 0x02 + : 0x00; + return transport.send(0xe0, 0x44, firstRound ? 0x00 : 0x80, newTransaction ? p2 : 0x80, transactionData); + } + function startUntrustedHashTransactionInput(transport, newTransaction, transaction, inputs, bip143, overwinter, additionals, useTrustedInputForSegwit) { + if (bip143 === void 0) { bip143 = false; } + if (overwinter === void 0) { overwinter = false; } + if (additionals === void 0) { additionals = []; } + if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } + return __awaiter$c(this, void 0, void 0, function () { + var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; + var e_2, _c, e_1, _d; + return __generator$c(this, function (_e) { + switch (_e.label) { + case 0: + data = Buffer$k.concat([ + transaction.version, + transaction.timestamp || Buffer$k.alloc(0), + transaction.nVersionGroupId || Buffer$k.alloc(0), + createVarint(transaction.inputs.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; + case 1: + _e.sent(); + i = 0; + isDecred = additionals.includes("decred"); + _e.label = 2; + case 2: + _e.trys.push([2, 15, 16, 17]); + _a = __values$6(transaction.inputs), _b = _a.next(); + _e.label = 3; + case 3: + if (!!_b.done) return [3 /*break*/, 14]; + input = _b.value; + prefix = void 0; + inputValue = inputs[i].value; + if (bip143) { + if (useTrustedInputForSegwit && inputs[i].trustedInput) { + prefix = Buffer$k.from([0x01, inputValue.length]); + } + else { + prefix = Buffer$k.from([0x02]); + } + } + else { + if (inputs[i].trustedInput) { + prefix = Buffer$k.from([0x01, inputs[i].value.length]); + } + else { + prefix = Buffer$k.from([0x00]); + } + } + data = Buffer$k.concat([ + prefix, + inputValue, + isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), + createVarint(input.script.length), + ]); + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; + case 4: + _e.sent(); + scriptBlocks = []; + offset = 0; + if (input.script.length === 0) { + scriptBlocks.push(input.sequence); + } + else { + while (offset !== input.script.length) { + blockSize = input.script.length - offset > MAX_SCRIPT_BLOCK + ? MAX_SCRIPT_BLOCK + : input.script.length - offset; + if (offset + blockSize !== input.script.length) { + scriptBlocks.push(input.script.slice(offset, offset + blockSize)); + } + else { + scriptBlocks.push(Buffer$k.concat([ + input.script.slice(offset, offset + blockSize), + input.sequence, + ])); + } + offset += blockSize; + } + } + _e.label = 5; + case 5: + _e.trys.push([5, 10, 11, 12]); + scriptBlocks_1 = (e_1 = void 0, __values$6(scriptBlocks)), scriptBlocks_1_1 = scriptBlocks_1.next(); + _e.label = 6; + case 6: + if (!!scriptBlocks_1_1.done) return [3 /*break*/, 9]; + scriptBlock = scriptBlocks_1_1.value; + return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, scriptBlock, bip143, overwinter, additionals)]; + case 7: + _e.sent(); + _e.label = 8; + case 8: + scriptBlocks_1_1 = scriptBlocks_1.next(); + return [3 /*break*/, 6]; + case 9: return [3 /*break*/, 12]; + case 10: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 12]; + case 11: + try { + if (scriptBlocks_1_1 && !scriptBlocks_1_1.done && (_d = scriptBlocks_1["return"])) _d.call(scriptBlocks_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 12: + i++; + _e.label = 13; + case 13: + _b = _a.next(); + return [3 /*break*/, 3]; + case 14: return [3 /*break*/, 17]; + case 15: + e_2_1 = _e.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 17]; + case 16: + try { + if (_b && !_b.done && (_c = _a["return"])) _c.call(_a); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 17: return [2 /*return*/]; + } + }); + }); + } + + function getTrustedInputBIP143(transport, indexLookup, transaction, additionals) { + if (additionals === void 0) { additionals = []; } + if (!transaction) { + throw new Error("getTrustedInputBIP143: missing tx"); + } + var isDecred = additionals.includes("decred"); + if (isDecred) { + throw new Error("Decred does not implement BIP143"); + } + var hash = sha$3("sha256") + .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) + .digest(); + var data = Buffer$k.alloc(4); + data.writeUInt32LE(indexLookup, 0); + var outputs = transaction.outputs, locktime = transaction.locktime; + if (!outputs || !locktime) { + throw new Error("getTrustedInputBIP143: locktime & outputs is expected"); + } + if (!outputs[indexLookup]) { + throw new Error("getTrustedInputBIP143: wrong index"); + } + hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); + return hash.toString("hex"); + } + + function compressPublicKey(publicKey) { + var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; + var prefixBuffer = Buffer$k.alloc(1); + prefixBuffer[0] = prefix; + return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + } + + function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { + if (additionals === void 0) { additionals = []; } + var isDecred = additionals.includes("decred"); + var pathsBuffer = bip32asBuffer(path); + var lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer.writeUInt32BE(lockTime, 0); + var buffer = isDecred + ? Buffer$k.concat([ + pathsBuffer, + lockTimeBuffer, + expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([sigHashType]), + ]) + : Buffer$k.concat([ + pathsBuffer, + Buffer$k.from([0x00]), + lockTimeBuffer, + Buffer$k.from([sigHashType]), + ]); + if (expiryHeight && !isDecred) { + buffer = Buffer$k.concat([buffer, expiryHeight]); + } + return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { + if (result.length > 0) { + result[0] = 0x30; + return result.slice(0, result.length - 2); + } + return result; + }); + } + + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function provideOutputFullChangePath(transport, path) { + var buffer = bip32asBuffer(path); + return transport.send(0xe0, 0x4a, 0xff, 0x00, buffer); + } + function hashOutputFull(transport, outputScript, additionals) { + if (additionals === void 0) { additionals = []; } + return __awaiter$b(this, void 0, void 0, function () { + var offset, p1, isDecred, blockSize, p1_1, data; + return __generator$b(this, function (_a) { + switch (_a.label) { + case 0: + offset = 0; + p1 = Number(0x80); + isDecred = additionals.includes("decred"); + ///WARNING: Decred works only with one call (without chunking) + //TODO: test without this for Decred + if (isDecred) { + return [2 /*return*/, transport.send(0xe0, 0x4a, p1, 0x00, outputScript)]; + } + _a.label = 1; + case 1: + if (!(offset < outputScript.length)) return [3 /*break*/, 3]; + blockSize = offset + MAX_SCRIPT_BLOCK >= outputScript.length + ? outputScript.length - offset + : MAX_SCRIPT_BLOCK; + p1_1 = offset + blockSize === outputScript.length ? 0x80 : 0x00; + data = outputScript.slice(offset, offset + blockSize); + return [4 /*yield*/, transport.send(0xe0, 0x4a, p1_1, 0x00, data)]; + case 2: + _a.sent(); + offset += blockSize; + return [3 /*break*/, 1]; + case 3: return [2 /*return*/]; + } + }); + }); + } + + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var getAppAndVersion = function (transport) { return __awaiter$a(void 0, void 0, void 0, function () { + var r, i, format, nameLength, name, versionLength, version, flagLength, flags; + return __generator$a(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; + case 1: + r = _a.sent(); + i = 0; + format = r[i++]; + browser(format === 1, "getAppAndVersion: format not supported"); + nameLength = r[i++]; + name = r.slice(i, (i += nameLength)).toString("ascii"); + versionLength = r[i++]; + version = r.slice(i, (i += versionLength)).toString("ascii"); + flagLength = r[i++]; + flags = r.slice(i, (i += flagLength)); + return [2 /*return*/, { + name: name, + version: version, + flags: flags + }]; + } + }); + }); }; + + function shouldUseTrustedInputForSegwit(_a) { + var version = _a.version, name = _a.name; + if (name === "Decred") + return false; + if (name === "Exchange") + return true; + return semver.gte(version, "1.4.0"); + } + + var __assign$3 = (undefined && undefined.__assign) || function () { + __assign$3 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$3.apply(this, arguments); + }; + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$5 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultsSignTransaction = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + additionals: [], + onDeviceStreaming: function (_e) { }, + onDeviceSignatureGranted: function () { }, + onDeviceSignatureRequested: function () { } + }; + function createTransaction(transport, arg) { + return __awaiter$9(this, void 0, void 0, function () { + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var e_2, _a; + return __generator$9(this, function (_b) { + switch (_b.label) { + case 0: + signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); + inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; + useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; + if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, getAppAndVersion(transport)]; + case 2: + a = _b.sent(); + useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); + return [3 /*break*/, 4]; + case 3: + e_1 = _b.sent(); + if (e_1.statusCode === 0x6d00) { + useTrustedInputForSegwit = false; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + notify = function (loop, i) { + var length = inputs.length; + if (length < 3) + return; // there is not enough significant event to worth notifying (aka just use a spinner) + var index = length * loop + i; + var total = 2 * length; + var progress = index / total; + onDeviceStreaming({ + progress: progress, + total: total, + index: index + }); + }; + isDecred = additionals.includes("decred"); + isXST = additionals.includes("stealthcoin"); + startTime = Date.now(); + sapling = additionals.includes("sapling"); + bech32 = segwit && additionals.includes("bech32"); + useBip143 = segwit || + (!!additionals && + (additionals.includes("abc") || + additionals.includes("gold") || + additionals.includes("bip143"))) || + (!!expiryHeight && !isDecred); + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); + !!expiryHeight && !isDecred + ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) + : isXST + ? defaultVersion.writeUInt32LE(2, 0) + : defaultVersion.writeUInt32LE(1, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + publicKeys = []; + firstRun = true; + resuming = false; + targetTransaction = { + inputs: [], + version: defaultVersion, + timestamp: Buffer$k.alloc(0) + }; + getTrustedInputCall = useBip143 && !useTrustedInputForSegwit + ? getTrustedInputBIP143 + : getTrustedInput; + outputScript = Buffer$k.from(outputScriptHex, "hex"); + notify(0, 0); + _b.label = 5; + case 5: + _b.trys.push([5, 11, 12, 13]); + inputs_1 = __values$5(inputs), inputs_1_1 = inputs_1.next(); + _b.label = 6; + case 6: + if (!!inputs_1_1.done) return [3 /*break*/, 10]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 8]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; + case 7: + trustedInput = _b.sent(); + log("hw", "got trustedInput=" + trustedInput); + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: true, + value: Buffer$k.from(trustedInput, "hex"), + sequence: sequence + }); + _b.label = 8; + case 8: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + if (expiryHeight && !isDecred) { + targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nExpiryHeight = expiryHeight; + // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) + // Overwinter : use nJoinSplit (1) + targetTransaction.extraData = Buffer$k.from(sapling + ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + : [0x00]); + } + else if (isDecred) { + targetTransaction.nExpiryHeight = expiryHeight; + } + _b.label = 9; + case 9: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 6]; + case 10: return [3 /*break*/, 13]; + case 11: + e_2_1 = _b.sent(); + e_2 = { error: e_2_1 }; + return [3 /*break*/, 13]; + case 12: + try { + if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); + } + finally { if (e_2) throw e_2.error; } + return [7 /*endfinally*/]; + case 13: + targetTransaction.inputs = inputs.map(function (input) { + var sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + return { + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }; + }); + if (!!resuming) return [3 /*break*/, 18]; + result_1 = []; + i = 0; + _b.label = 14; + case 14: + if (!(i < inputs.length)) return [3 /*break*/, 17]; + return [4 /*yield*/, getWalletPublicKey(transport, { + path: associatedKeysets[i] + })]; + case 15: + r = _b.sent(); + notify(0, i + 1); + result_1.push(r); + _b.label = 16; + case 16: + i++; + return [3 /*break*/, 14]; + case 17: + for (i = 0; i < result_1.length; i++) { + publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); + } + _b.label = 18; + case 18: + if (initialTimestamp !== undefined) { + targetTransaction.timestamp = Buffer$k.alloc(4); + targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + onDeviceSignatureRequested(); + if (!useBip143) return [3 /*break*/, 23]; + // Do the first run with all inputs + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; + case 19: + // Do the first run with all inputs + _b.sent(); + if (!(!resuming && changePath)) return [3 /*break*/, 21]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 20: + _b.sent(); + _b.label = 21; + case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 22: + _b.sent(); + _b.label = 23; + case 23: + if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; + return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; + case 24: + _b.sent(); + _b.label = 25; + case 25: + i = 0; + _b.label = 26; + case 26: + if (!(i < inputs.length)) return [3 /*break*/, 34]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$k.from(input[2], "hex") + : !segwit + ? regularOutputs[i].script + : Buffer$k.concat([ + Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), + hashPublicKey(publicKeys[i]), + Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), + ]); + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; + if (useBip143) { + pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; + case 27: + _b.sent(); + if (!!useBip143) return [3 /*break*/, 31]; + if (!(!resuming && changePath)) return [3 /*break*/, 29]; + return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; + case 28: + _b.sent(); + _b.label = 29; + case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; + case 30: + _b.sent(); + _b.label = 31; + case 31: + if (firstRun) { + onDeviceSignatureGranted(); + notify(1, 0); + } + return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; + case 32: + signature = _b.sent(); + notify(1, i + 1); + signatures.push(signature); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _b.label = 33; + case 33: + i++; + return [3 /*break*/, 26]; + case 34: + // Populate the final input scripts + for (i = 0; i < inputs.length; i++) { + if (segwit) { + targetTransaction.witness = Buffer$k.alloc(0); + if (!bech32) { + targetTransaction.inputs[i].script = Buffer$k.concat([ + Buffer$k.from("160014", "hex"), + hashPublicKey(publicKeys[i]), + ]); + } + } + else { + signatureSize = Buffer$k.alloc(1); + keySize = Buffer$k.alloc(1); + signatureSize[0] = signatures[i].length; + keySize[0] = publicKeys[i].length; + targetTransaction.inputs[i].script = Buffer$k.concat([ + signatureSize, + signatures[i], + keySize, + publicKeys[i], + ]); + } + offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; + targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); + } + lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer.writeUInt32LE(lockTime, 0); + result = Buffer$k.concat([ + serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), + outputScript, + ]); + if (segwit && !isDecred) { + witness = Buffer$k.alloc(0); + for (i = 0; i < inputs.length; i++) { + tmpScriptData = Buffer$k.concat([ + Buffer$k.from("02", "hex"), + Buffer$k.from([signatures[i].length]), + signatures[i], + Buffer$k.from([publicKeys[i].length]), + publicKeys[i], + ]); + witness = Buffer$k.concat([witness, tmpScriptData]); + } + result = Buffer$k.concat([result, witness]); + } + // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. + // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here + // and it should not break other coins because expiryHeight is false for them. + // Don't know about Decred though. + result = Buffer$k.concat([result, lockTimeBuffer]); + if (expiryHeight) { + result = Buffer$k.concat([ + result, + targetTransaction.nExpiryHeight || Buffer$k.alloc(0), + targetTransaction.extraData || Buffer$k.alloc(0), + ]); + } + if (isDecred) { + decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); + inputs.forEach(function (input, inputIndex) { + decredWitness_1 = Buffer$k.concat([ + decredWitness_1, + Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0x00, 0x00, 0x00, 0x00]), + Buffer$k.from([0xff, 0xff, 0xff, 0xff]), + Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), + targetTransaction.inputs[inputIndex].script, + ]); + }); + result = Buffer$k.concat([result, decredWitness_1]); + } + return [2 /*return*/, result.toString("hex")]; + } + }); + }); + } + + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + function signMessage(transport, _a) { + var path = _a.path, messageHex = _a.messageHex; + return __awaiter$8(this, void 0, void 0, function () { + var paths, message, offset, _loop_1, res, v, r, s; + return __generator$8(this, function (_b) { + switch (_b.label) { + case 0: + paths = bip32Path.fromString(path).toPathArray(); + message = Buffer$k.from(messageHex, "hex"); + offset = 0; + _loop_1 = function () { + var maxChunkSize, chunkSize, buffer; + return __generator$8(this, function (_c) { + switch (_c.label) { + case 0: + maxChunkSize = offset === 0 + ? MAX_SCRIPT_BLOCK - 1 - paths.length * 4 - 4 + : MAX_SCRIPT_BLOCK; + chunkSize = offset + maxChunkSize > message.length + ? message.length - offset + : maxChunkSize; + buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + if (offset === 0) { + buffer[0] = paths.length; + paths.forEach(function (element, index) { + buffer.writeUInt32BE(element, 1 + 4 * index); + }); + buffer.writeUInt16BE(message.length, 1 + 4 * paths.length); + message.copy(buffer, 1 + 4 * paths.length + 2, offset, offset + chunkSize); + } + else { + message.copy(buffer, 0, offset, offset + chunkSize); + } + return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x00, offset === 0 ? 0x01 : 0x80, buffer)]; + case 1: + _c.sent(); + offset += chunkSize; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!(offset !== message.length)) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_1()]; + case 2: + _b.sent(); + return [3 /*break*/, 1]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; + case 4: + res = _b.sent(); + v = res[0] - 0x30; + r = res.slice(4, 4 + res[3]); + if (r[0] === 0) { + r = r.slice(1); + } + r = r.toString("hex"); + offset = 4 + res[3] + 2; + s = res.slice(offset, offset + res[offset - 1]); + if (s[0] === 0) { + s = s.slice(1); + } + s = s.toString("hex"); + return [2 /*return*/, { + v: v, + r: r, + s: s + }]; + } + }); + }); + } + + var __assign$2 = (undefined && undefined.__assign) || function () { + __assign$2 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$2.apply(this, arguments); + }; + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$7(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$7(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; + nullScript = Buffer$k.alloc(0); + nullPrevout = Buffer$k.alloc(0); + defaultVersion = Buffer$k.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + startTime = Date.now(); + targetTransaction = { + inputs: [], + timestamp: Buffer$k.alloc(0), + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$k.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$k.from(trustedInput, "hex") + : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$k.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$k.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$k.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } + + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -15132,6 +38272,385 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; + /** + * Bitcoin API. + * + * @example + * import Btc from "@ledgerhq/hw-app-btc"; + * const btc = new Btc(transport) + */ + var BtcOld = /** @class */ (function () { + function BtcOld(transport) { + this.transport = transport; + this.derivationsCache = {}; + } + BtcOld.prototype.derivatePath = function (path) { + return __awaiter$6(this, void 0, void 0, function () { + var res; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + if (this.derivationsCache[path]) + return [2 /*return*/, this.derivationsCache[path]]; + return [4 /*yield*/, getWalletPublicKey(this.transport, { + path: path + })]; + case 1: + res = _a.sent(); + this.derivationsCache[path] = res; + return [2 /*return*/, res]; + } + }); + }); + }; + BtcOld.prototype.getWalletXpub = function (_a) { + var path = _a.path, xpubVersion = _a.xpubVersion; + return __awaiter$6(this, void 0, void 0, function () { + var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; + return __generator$6(this, function (_b) { + switch (_b.label) { + case 0: + pathElements = pathStringToArray(path); + parentPath = pathElements.slice(0, -1); + return [4 /*yield*/, this.derivatePath(pathArrayToString(parentPath))]; + case 1: + parentDerivation = _b.sent(); + return [4 /*yield*/, this.derivatePath(path)]; + case 2: + accountDerivation = _b.sent(); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); + return [2 /*return*/, xpub]; + } + }); + }); + }; + /** + * @param path a BIP 32 path + * @param options an object with optional these fields: + * + * - verify (boolean) will ask user to confirm the address on the device + * + * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * + * NB The normal usage is to use: + * + * - legacy format with 44' paths + * + * - p2sh format with 49' paths + * + * - bech32 format with 173' paths + * + * - cashaddr in case of Bitcoin Cash + * + * @example + * btc.getWalletPublicKey("44'/0'/0'/0/0").then(o => o.bitcoinAddress) + * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) + */ + BtcOld.prototype.getWalletPublicKey = function (path, opts) { + if ((opts === null || opts === void 0 ? void 0 : opts.format) === "bech32m") { + throw new Error("Unsupported address format bech32m"); + } + return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, opts), { path: path })); + }; + /** + * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. + * @example + btc.signMessageNew_async("44'/60'/0'/0'/0", Buffer.from("test").toString("hex")).then(function(result) { + var v = result['v'] + 27 + 4; + var signature = Buffer.from(v.toString(16) + result['r'] + result['s'], 'hex').toString('base64'); + console.log("Signature : " + signature); + }).catch(function(ex) {console.log(ex);}); + */ + BtcOld.prototype.signMessageNew = function (path, messageHex) { + return signMessage(this.transport, { + path: path, + messageHex: messageHex + }); + }; + /** + * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters + * @param inputs is an array of [ transaction, output_index, optional redeem script, optional sequence ] where + * + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the optional redeem script to use when consuming a Segregated Witness input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @param segwit is an optional boolean indicating wether to use segwit or not + * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) + * @param additionals list of additionnal options + * + * - "bech32" for spending native segwit outputs + * - "abc" for bch + * - "gold" for btg + * - "bipxxx" for using BIPxxx + * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) + * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs + * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @return the signed transaction ready to be broadcast + * @example + btc.createTransaction({ + inputs: [ [tx1, 1] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(res => ...); + */ + BtcOld.prototype.createPaymentTransactionNew = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); + } + return createTransaction(this.transport, arg); + }; + /** + * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters + * @param inputs is an array of [ transaction, output_index, redeem script, optional sequence ] where + * * transaction is the previously computed transaction object for this UTXO + * * output_index is the output in the transaction used as input for this UTXO (counting from 0) + * * redeem script is the mandatory redeem script associated to the current P2SH input + * * sequence is the sequence number to use for this input (when using RBF), or non present + * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param lockTime is the optional lockTime of the transaction to sign, or default (0) + * @param sigHashType is the hash type of the transaction to sign, or default (all) + * @return the signed transaction ready to be broadcast + * @example + btc.signP2SHTransaction({ + inputs: [ [tx, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae"] ], + associatedKeysets: ["0'/0/0"], + outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac" + }).then(result => ...); + */ + BtcOld.prototype.signP2SHTransaction = function (arg) { + if (arguments.length > 1) { + console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); + } + return signP2SHTransaction(this.transport, arg); + }; + return BtcOld; + }()); + function makeFingerprint(compressedPubKey) { + return hash160(compressedPubKey).slice(0, 4); + } + function asBufferUInt32BE(n) { + var buf = Buffer$k.allocUnsafe(4); + buf.writeUInt32BE(n, 0); + return buf; + } + var compressPublicKeySECP256 = function (publicKey) { + return Buffer$k.concat([ + Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), + publicKey.slice(1, 33), + ]); + }; + function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { + var indexBuffer = asBufferUInt32BE(index); + indexBuffer[0] |= 0x80; + var extendedKeyBytes = Buffer$k.concat([ + asBufferUInt32BE(version), + Buffer$k.from([depth]), + parentFingerprint, + indexBuffer, + chainCode, + pubKey, + ]); + var checksum = hash256(extendedKeyBytes).slice(0, 4); + return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); + } + function sha256(buffer) { + return sha$3("sha256").update(buffer).digest(); + } + function hash256(buffer) { + return sha256(sha256(buffer)); + } + function ripemd160(buffer) { + return new ripemd160$2().update(buffer).digest(); + } + function hash160(buffer) { + return ripemd160(sha256(buffer)); + } + + /** + * This implements "Merkelized Maps", documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/merkle.md#merkleized-maps + * + * A merkelized map consist of two merkle trees, one for the keys of + * a map and one for the values of the same map, thus the two merkle + * trees have the same shape. The commitment is the number elements + * in the map followed by the keys' merkle root followed by the + * values' merkle root. + */ + var MerkleMap = /** @class */ (function () { + /** + * @param keys Sorted list of (unhashed) keys + * @param values values, in corresponding order as the keys, and of equal length + */ + function MerkleMap(keys, values) { + if (keys.length != values.length) { + throw new Error("keys and values should have the same length"); + } + // Sanity check: verify that keys are actually sorted and with no duplicates + for (var i = 0; i < keys.length - 1; i++) { + if (keys[i].toString("hex") >= keys[i + 1].toString("hex")) { + throw new Error("keys must be in strictly increasing order"); + } + } + this.keys = keys; + this.keysTree = new Merkle(keys.map(function (k) { return hashLeaf(k); })); + this.values = values; + this.valuesTree = new Merkle(values.map(function (v) { return hashLeaf(v); })); + } + MerkleMap.prototype.commitment = function () { + // returns a buffer between 65 and 73 (included) bytes long + return Buffer$k.concat([ + createVarint(this.keys.length), + this.keysTree.getRoot(), + this.valuesTree.getRoot(), + ]); + }; + return MerkleMap; + }()); + + var __extends$4 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$2 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$2 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + /** + * This class merkelizes a PSBTv2, by merkelizing the different + * maps of the psbt. This is used during the transaction signing process, + * where the hardware app can request specific parts of the psbt from the + * client code and be sure that the response data actually belong to the psbt. + * The reason for this is the limited amount of memory available to the app, + * so it can't always store the full psbt in memory. + * + * The signing process is documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt + */ + var MerkelizedPsbt = /** @class */ (function (_super) { + __extends$4(MerkelizedPsbt, _super); + function MerkelizedPsbt(psbt) { + var _this = _super.call(this) || this; + _this.inputMerkleMaps = []; + _this.outputMerkleMaps = []; + psbt.copy(_this); + _this.globalMerkleMap = MerkelizedPsbt.createMerkleMap(_this.globalMap); + for (var i = 0; i < _this.getGlobalInputCount(); i++) { + _this.inputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.inputMaps[i])); + } + _this.inputMapCommitments = __spreadArray$2([], __read$2(_this.inputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + for (var i = 0; i < _this.getGlobalOutputCount(); i++) { + _this.outputMerkleMaps.push(MerkelizedPsbt.createMerkleMap(_this.outputMaps[i])); + } + _this.outputMapCommitments = __spreadArray$2([], __read$2(_this.outputMerkleMaps.values()), false).map(function (v) { + return v.commitment(); + }); + return _this; + } + // These public functions are for MerkelizedPsbt. + MerkelizedPsbt.prototype.getGlobalSize = function () { + return this.globalMap.size; + }; + MerkelizedPsbt.prototype.getGlobalKeysValuesRoot = function () { + return this.globalMerkleMap.commitment(); + }; + MerkelizedPsbt.createMerkleMap = function (map) { + var sortedKeysStrings = __spreadArray$2([], __read$2(map.keys()), false).sort(); + var values = sortedKeysStrings.map(function (k) { + var v = map.get(k); + if (!v) { + throw new Error("No value for key " + k); + } + return v; + }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); + var merkleMap = new MerkleMap(sortedKeys, values); + return merkleMap; + }; + return MerkelizedPsbt; + }(PsbtV2)); + + var __extends$3 = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __read$1 = (undefined && undefined.__read) || function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; var __values$3 = (undefined && undefined.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); @@ -15141,356 +38660,707 @@ return { value: o && o[i++], done: !o }; } }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultsSignTransaction = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - additionals: [], - onDeviceStreaming: function (_e) { }, - onDeviceSignatureGranted: function () { }, - onDeviceSignatureRequested: function () { } - }; - function createTransaction(transport, arg) { - return __awaiter$4(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; - var e_2, _a; - return __generator$4(this, function (_b) { - switch (_b.label) { - case 0: - signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); - inputs = signTx.inputs, associatedKeysets = signTx.associatedKeysets, changePath = signTx.changePath, outputScriptHex = signTx.outputScriptHex, lockTime = signTx.lockTime, sigHashType = signTx.sigHashType, segwit = signTx.segwit, initialTimestamp = signTx.initialTimestamp, additionals = signTx.additionals, expiryHeight = signTx.expiryHeight, onDeviceStreaming = signTx.onDeviceStreaming, onDeviceSignatureGranted = signTx.onDeviceSignatureGranted, onDeviceSignatureRequested = signTx.onDeviceSignatureRequested; - useTrustedInputForSegwit = signTx.useTrustedInputForSegwit; - if (!(useTrustedInputForSegwit === undefined)) return [3 /*break*/, 4]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAppAndVersion(transport)]; - case 2: - a = _b.sent(); - useTrustedInputForSegwit = shouldUseTrustedInputForSegwit(a); - return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - if (e_1.statusCode === 0x6d00) { - useTrustedInputForSegwit = false; - } - else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - notify = function (loop, i) { - var length = inputs.length; - if (length < 3) - return; // there is not enough significant event to worth notifying (aka just use a spinner) - var index = length * loop + i; - var total = 2 * length; - var progress = index / total; - onDeviceStreaming({ - progress: progress, - total: total, - index: index - }); - }; - isDecred = additionals.includes("decred"); - isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); - sapling = additionals.includes("sapling"); - bech32 = segwit && additionals.includes("bech32"); - useBip143 = segwit || - (!!additionals && - (additionals.includes("abc") || - additionals.includes("gold") || - additionals.includes("bip143"))) || - (!!expiryHeight && !isDecred); - nullScript = Buffer$e.alloc(0); - nullPrevout = Buffer$e.alloc(0); - defaultVersion = Buffer$e.alloc(4); - !!expiryHeight && !isDecred - ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) - : isXST - ? defaultVersion.writeUInt32LE(2, 0) - : defaultVersion.writeUInt32LE(1, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - publicKeys = []; - firstRun = true; - resuming = false; - targetTransaction = { - inputs: [], - version: defaultVersion, - timestamp: Buffer$e.alloc(0) - }; - getTrustedInputCall = useBip143 && !useTrustedInputForSegwit - ? getTrustedInputBIP143 - : getTrustedInput; - outputScript = Buffer$e.from(outputScriptHex, "hex"); - notify(0, 0); - _b.label = 5; - case 5: - _b.trys.push([5, 11, 12, 13]); - inputs_1 = __values$3(inputs), inputs_1_1 = inputs_1.next(); - _b.label = 6; - case 6: - if (!!inputs_1_1.done) return [3 /*break*/, 10]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 8]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0], additionals)]; - case 7: - trustedInput = _b.sent(); - log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$e.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: true, - value: Buffer$e.from(trustedInput, "hex"), - sequence: sequence - }); - _b.label = 8; - case 8: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$e.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); - targetTransaction.nExpiryHeight = expiryHeight; - // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) - // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$e.from(sapling - ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] - : [0x00]); - } - else if (isDecred) { - targetTransaction.nExpiryHeight = expiryHeight; - } - _b.label = 9; - case 9: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 6]; - case 10: return [3 /*break*/, 13]; - case 11: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 13]; - case 12: - try { - if (inputs_1_1 && !inputs_1_1.done && (_a = inputs_1["return"])) _a.call(inputs_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 13: - targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$e.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - return { - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }; - }); - if (!!resuming) return [3 /*break*/, 18]; - result_1 = []; - i = 0; - _b.label = 14; - case 14: - if (!(i < inputs.length)) return [3 /*break*/, 17]; - return [4 /*yield*/, getWalletPublicKey(transport, { - path: associatedKeysets[i] - })]; - case 15: - r = _b.sent(); - notify(0, i + 1); - result_1.push(r); - _b.label = 16; - case 16: - i++; - return [3 /*break*/, 14]; - case 17: - for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$e.from(result_1[i].publicKey, "hex"))); - } - _b.label = 18; - case 18: - if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$e.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - onDeviceSignatureRequested(); - if (!useBip143) return [3 /*break*/, 23]; - // Do the first run with all inputs - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true, !!expiryHeight, additionals, useTrustedInputForSegwit)]; - case 19: - // Do the first run with all inputs - _b.sent(); - if (!(!resuming && changePath)) return [3 /*break*/, 21]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 20: - _b.sent(); - _b.label = 21; - case 21: return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 22: - _b.sent(); - _b.label = 23; - case 23: - if (!(!!expiryHeight && !isDecred)) return [3 /*break*/, 25]; - return [4 /*yield*/, signTransaction(transport, "", lockTime, SIGHASH_ALL, expiryHeight)]; - case 24: - _b.sent(); - _b.label = 25; - case 25: - i = 0; - _b.label = 26; - case 26: - if (!(i < inputs.length)) return [3 /*break*/, 34]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$e.from(input[2], "hex") - : !segwit - ? regularOutputs[i].script - : Buffer$e.concat([ - Buffer$e.from([OP_DUP, OP_HASH160, HASH_SIZE]), - hashPublicKey(publicKeys[i]), - Buffer$e.from([OP_EQUALVERIFY, OP_CHECKSIG]), - ]); - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; - if (useBip143) { - pseudoTX.inputs = [__assign$3(__assign$3({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, !useBip143 && firstRun, pseudoTX, pseudoTrustedInputs, useBip143, !!expiryHeight && !isDecred, additionals, useTrustedInputForSegwit)]; - case 27: - _b.sent(); - if (!!useBip143) return [3 /*break*/, 31]; - if (!(!resuming && changePath)) return [3 /*break*/, 29]; - return [4 /*yield*/, provideOutputFullChangePath(transport, changePath)]; - case 28: - _b.sent(); - _b.label = 29; - case 29: return [4 /*yield*/, hashOutputFull(transport, outputScript, additionals)]; - case 30: - _b.sent(); - _b.label = 31; - case 31: - if (firstRun) { - onDeviceSignatureGranted(); - notify(1, 0); - } - return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType, expiryHeight, additionals)]; - case 32: - signature = _b.sent(); - notify(1, i + 1); - signatures.push(signature); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _b.label = 33; - case 33: - i++; - return [3 /*break*/, 26]; - case 34: - // Populate the final input scripts - for (i = 0; i < inputs.length; i++) { - if (segwit) { - targetTransaction.witness = Buffer$e.alloc(0); - if (!bech32) { - targetTransaction.inputs[i].script = Buffer$e.concat([ - Buffer$e.from("160014", "hex"), - hashPublicKey(publicKeys[i]), - ]); + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var ClientCommandCode; + (function (ClientCommandCode) { + ClientCommandCode[ClientCommandCode["YIELD"] = 16] = "YIELD"; + ClientCommandCode[ClientCommandCode["GET_PREIMAGE"] = 64] = "GET_PREIMAGE"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_PROOF"] = 65] = "GET_MERKLE_LEAF_PROOF"; + ClientCommandCode[ClientCommandCode["GET_MERKLE_LEAF_INDEX"] = 66] = "GET_MERKLE_LEAF_INDEX"; + ClientCommandCode[ClientCommandCode["GET_MORE_ELEMENTS"] = 160] = "GET_MORE_ELEMENTS"; + })(ClientCommandCode || (ClientCommandCode = {})); + var ClientCommand = /** @class */ (function () { + function ClientCommand() { + } + return ClientCommand; + }()); + var YieldCommand = /** @class */ (function (_super) { + __extends$3(YieldCommand, _super); + function YieldCommand(results, progressCallback) { + var _this = _super.call(this) || this; + _this.progressCallback = progressCallback; + _this.code = ClientCommandCode.YIELD; + _this.results = results; + return _this; + } + YieldCommand.prototype.execute = function (request) { + this.results.push(Buffer$k.from(request.subarray(1))); + this.progressCallback(); + return Buffer$k.from(""); + }; + return YieldCommand; + }(ClientCommand)); + var GetPreimageCommand = /** @class */ (function (_super) { + __extends$3(GetPreimageCommand, _super); + function GetPreimageCommand(known_preimages, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_PREIMAGE; + _this.known_preimages = known_preimages; + _this.queue = queue; + return _this; + } + GetPreimageCommand.prototype.execute = function (request) { + var req = Buffer$k.from(request.subarray(1)); + // we expect no more data to read + if (req.length != 1 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (req[0] != 0) { + throw new Error("Unsupported request, the first byte should be 0"); + } + // read the hash + var hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + hash[i] = req[1 + i]; + } + var req_hash_hex = hash.toString("hex"); + var known_preimage = this.known_preimages.get(req_hash_hex); + if (known_preimage != undefined) { + var preimage_len_varint = createVarint(known_preimage.length); + // We can send at most 255 - len(preimage_len_out) - 1 bytes in a single message; + // the rest will be stored in the queue for GET_MORE_ELEMENTS + var max_payload_size = 255 - preimage_len_varint.length - 1; + var payload_size = Math.min(max_payload_size, known_preimage.length); + if (payload_size < known_preimage.length) { + for (var i = payload_size; i < known_preimage.length; i++) { + this.queue.push(Buffer$k.from([known_preimage[i]])); + } + } + return Buffer$k.concat([ + preimage_len_varint, + Buffer$k.from([payload_size]), + Buffer$k.from(known_preimage.subarray(0, payload_size)), + ]); + } + throw Error("Requested unknown preimage for: " + req_hash_hex); + }; + return GetPreimageCommand; + }(ClientCommand)); + var GetMerkleLeafProofCommand = /** @class */ (function (_super) { + __extends$3(GetMerkleLeafProofCommand, _super); + function GetMerkleLeafProofCommand(known_trees, queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; + _this.known_trees = known_trees; + _this.queue = queue; + return _this; + } + GetMerkleLeafProofCommand.prototype.execute = function (request) { + var _a; + var req = Buffer$k.from(request.subarray(1)); + if (req.length < 32 + 1 + 1) { + throw new Error("Invalid request, expected at least 34 bytes"); + } + var reqBuf = new BufferReader(req); + var hash = reqBuf.readSlice(32); + var hash_hex = hash.toString("hex"); + var tree_size; + var leaf_index; + try { + tree_size = reqBuf.readVarInt(); + leaf_index = reqBuf.readVarInt(); + } + catch (e) { + throw new Error("Invalid request, couldn't parse tree_size or leaf_index"); + } + var mt = this.known_trees.get(hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf proof for unknown tree: " + hash_hex); + } + if (leaf_index >= tree_size || mt.size() != tree_size) { + throw Error("Invalid index or tree size."); + } + if (this.queue.length != 0) { + throw Error("This command should not execute when the queue is not empty."); + } + var proof = mt.getProof(leaf_index); + var n_response_elements = Math.min(Math.floor((255 - 32 - 1 - 1) / 32), proof.length); + var n_leftover_elements = proof.length - n_response_elements; + // Add to the queue any proof elements that do not fit the response + if (n_leftover_elements > 0) { + (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); + } + return Buffer$k.concat(__spreadArray$1([ + mt.getLeafHash(leaf_index), + Buffer$k.from([proof.length]), + Buffer$k.from([n_response_elements]) + ], __read$1(proof.slice(0, n_response_elements)), false)); + }; + return GetMerkleLeafProofCommand; + }(ClientCommand)); + var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { + __extends$3(GetMerkleLeafIndexCommand, _super); + function GetMerkleLeafIndexCommand(known_trees) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; + _this.known_trees = known_trees; + return _this; + } + GetMerkleLeafIndexCommand.prototype.execute = function (request) { + var req = Buffer$k.from(request.subarray(1)); + if (req.length != 32 + 32) { + throw new Error("Invalid request, unexpected trailing data"); + } + // read the root hash + var root_hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + root_hash[i] = req.readUInt8(i); + } + var root_hash_hex = root_hash.toString("hex"); + // read the leaf hash + var leef_hash = Buffer$k.alloc(32); + for (var i = 0; i < 32; i++) { + leef_hash[i] = req.readUInt8(32 + i); + } + var leef_hash_hex = leef_hash.toString("hex"); + var mt = this.known_trees.get(root_hash_hex); + if (!mt) { + throw Error("Requested Merkle leaf index for unknown root: " + root_hash_hex); + } + var leaf_index = 0; + var found = 0; + for (var i = 0; i < mt.size(); i++) { + if (mt.getLeafHash(i).toString("hex") == leef_hash_hex) { + found = 1; + leaf_index = i; + break; + } + } + return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); + }; + return GetMerkleLeafIndexCommand; + }(ClientCommand)); + var GetMoreElementsCommand = /** @class */ (function (_super) { + __extends$3(GetMoreElementsCommand, _super); + function GetMoreElementsCommand(queue) { + var _this = _super.call(this) || this; + _this.code = ClientCommandCode.GET_MORE_ELEMENTS; + _this.queue = queue; + return _this; + } + GetMoreElementsCommand.prototype.execute = function (request) { + if (request.length != 1) { + throw new Error("Invalid request, unexpected trailing data"); + } + if (this.queue.length === 0) { + throw new Error("No elements to get"); + } + // all elements should have the same length + var element_len = this.queue[0].length; + if (this.queue.some(function (el) { return el.length != element_len; })) { + throw new Error("The queue contains elements with different byte length, which is not expected"); + } + var max_elements = Math.floor(253 / element_len); + var n_returned_elements = Math.min(max_elements, this.queue.length); + var returned_elements = this.queue.splice(0, n_returned_elements); + return Buffer$k.concat(__spreadArray$1([ + Buffer$k.from([n_returned_elements]), + Buffer$k.from([element_len]) + ], __read$1(returned_elements), false)); + }; + return GetMoreElementsCommand; + }(ClientCommand)); + /** + * This class will dispatch a client command coming from the hardware device to + * the appropriate client command implementation. Those client commands + * typically requests data from a merkle tree or merkelized maps. + * + * A ClientCommandInterpreter is prepared by adding the merkle trees and + * merkelized maps it should be able to serve to the hardware device. This class + * doesn't know anything about the semantics of the data it holds, it just + * serves merkle data. It doesn't even know in what context it is being + * executed, ie SignPsbt, getWalletAddress, etc. + * + * If the command yelds results to the client, as signPsbt does, the yielded + * data will be accessible after the command completed by calling getYielded(), + * which will return the yields in the same order as they came in. + */ + var ClientCommandInterpreter = /** @class */ (function () { + function ClientCommandInterpreter(progressCallback) { + var e_1, _a; + this.roots = new Map(); + this.preimages = new Map(); + this.yielded = []; + this.queue = []; + this.commands = new Map(); + var commands = [ + new YieldCommand(this.yielded, progressCallback), + new GetPreimageCommand(this.preimages, this.queue), + new GetMerkleLeafIndexCommand(this.roots), + new GetMerkleLeafProofCommand(this.roots, this.queue), + new GetMoreElementsCommand(this.queue), + ]; + try { + for (var commands_1 = __values$3(commands), commands_1_1 = commands_1.next(); !commands_1_1.done; commands_1_1 = commands_1.next()) { + var cmd = commands_1_1.value; + if (this.commands.has(cmd.code)) { + throw new Error("Multiple commands with code " + cmd.code); + } + this.commands.set(cmd.code, cmd); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (commands_1_1 && !commands_1_1.done && (_a = commands_1["return"])) _a.call(commands_1); + } + finally { if (e_1) throw e_1.error; } + } + } + ClientCommandInterpreter.prototype.getYielded = function () { + return this.yielded; + }; + ClientCommandInterpreter.prototype.addKnownPreimage = function (preimage) { + this.preimages.set(crypto_1.sha256(preimage).toString("hex"), preimage); + }; + ClientCommandInterpreter.prototype.addKnownList = function (elements) { + var e_2, _a; + try { + for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { + var el = elements_1_1.value; + var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); + this.addKnownPreimage(preimage); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (elements_1_1 && !elements_1_1.done && (_a = elements_1["return"])) _a.call(elements_1); + } + finally { if (e_2) throw e_2.error; } + } + var mt = new Merkle(elements.map(function (el) { return hashLeaf(el); })); + this.roots.set(mt.getRoot().toString("hex"), mt); + }; + ClientCommandInterpreter.prototype.addKnownMapping = function (mm) { + this.addKnownList(mm.keys); + this.addKnownList(mm.values); + }; + ClientCommandInterpreter.prototype.execute = function (request) { + if (request.length == 0) { + throw new Error("Unexpected empty command"); + } + var cmdCode = request[0]; + var cmd = this.commands.get(cmdCode); + if (!cmd) { + throw new Error("Unexpected command code " + cmdCode); + } + return cmd.execute(request); + }; + return ClientCommandInterpreter; + }()); + + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var __values$2 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var CLA_BTC = 0xe1; + var CLA_FRAMEWORK = 0xf8; + var BitcoinIns; + (function (BitcoinIns) { + BitcoinIns[BitcoinIns["GET_PUBKEY"] = 0] = "GET_PUBKEY"; + // GET_ADDRESS = 0x01, // Removed from app + BitcoinIns[BitcoinIns["REGISTER_WALLET"] = 2] = "REGISTER_WALLET"; + BitcoinIns[BitcoinIns["GET_WALLET_ADDRESS"] = 3] = "GET_WALLET_ADDRESS"; + BitcoinIns[BitcoinIns["SIGN_PSBT"] = 4] = "SIGN_PSBT"; + BitcoinIns[BitcoinIns["GET_MASTER_FINGERPRINT"] = 5] = "GET_MASTER_FINGERPRINT"; + })(BitcoinIns || (BitcoinIns = {})); + var FrameworkIns; + (function (FrameworkIns) { + FrameworkIns[FrameworkIns["CONTINUE_INTERRUPTED"] = 1] = "CONTINUE_INTERRUPTED"; + })(FrameworkIns || (FrameworkIns = {})); + /** + * This class encapsulates the APDU protocol documented at + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md + */ + var AppClient = /** @class */ (function () { + function AppClient(transport) { + this.transport = transport; + } + AppClient.prototype.makeRequest = function (ins, data, cci) { + return __awaiter$5(this, void 0, void 0, function () { + var response, hwRequest, commandResponse; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ + 0x9000, + 0xe000, + ])]; + case 1: + response = _a.sent(); + _a.label = 2; + case 2: + if (!(response.readUInt16BE(response.length - 2) === 0xe000)) return [3 /*break*/, 4]; + if (!cci) { + throw new Error("Unexpected SW_INTERRUPTED_EXECUTION"); + } + hwRequest = response.slice(0, -2); + commandResponse = cci.execute(hwRequest); + return [4 /*yield*/, this.transport.send(CLA_FRAMEWORK, FrameworkIns.CONTINUE_INTERRUPTED, 0, 0, commandResponse, [0x9000, 0xe000])]; + case 3: + response = _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/, response.slice(0, -2)]; // drop the status word (can only be 0x9000 at this point) + } + }); + }); + }; + AppClient.prototype.getExtendedPubkey = function (display, pathElements) { + return __awaiter$5(this, void 0, void 0, function () { + var response; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (pathElements.length > 6) { + throw new Error("Path too long. At most 6 levels allowed."); + } + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), + pathElementsToBuffer(pathElements), + ]))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { + return __awaiter$5(this, void 0, void 0, function () { + var clientInterpreter, addressIndexBuffer, response; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + if (change !== 0 && change !== 1) + throw new Error("Change can only be 0 or 1"); + if (addressIndex < 0 || !Number.isInteger(addressIndex)) + throw new Error("Invalid address index"); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(function () { }); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + addressIndexBuffer = Buffer$k.alloc(4); + addressIndexBuffer.writeUInt32BE(addressIndex, 0); + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ + Buffer$k.from(display ? [1] : [0]), + walletPolicy.getWalletId(), + walletHMAC || Buffer$k.alloc(32, 0), + Buffer$k.from([change]), + addressIndexBuffer, + ]), clientInterpreter)]; + case 1: + response = _a.sent(); + return [2 /*return*/, response.toString("ascii")]; + } + }); + }); + }; + AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { + return __awaiter$5(this, void 0, void 0, function () { + var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; + var e_1, _e, e_2, _f, e_3, _g; + return __generator$5(this, function (_h) { + switch (_h.label) { + case 0: + merkelizedPsbt = new MerkelizedPsbt(psbt); + if (walletHMAC != null && walletHMAC.length != 32) { + throw new Error("Invalid HMAC length"); + } + clientInterpreter = new ClientCommandInterpreter(progressCallback); + // prepare ClientCommandInterpreter + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownPreimage(walletPolicy.serialize()); + clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); + try { + for (_a = __values$2(merkelizedPsbt.inputMerkleMaps), _b = _a.next(); !_b.done; _b = _a.next()) { + map = _b.value; + clientInterpreter.addKnownMapping(map); } } - else { - signatureSize = Buffer$e.alloc(1); - keySize = Buffer$e.alloc(1); - signatureSize[0] = signatures[i].length; - keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$e.concat([ - signatureSize, - signatures[i], - keySize, - publicKeys[i], - ]); + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_b && !_b.done && (_e = _a["return"])) _e.call(_a); + } + finally { if (e_1) throw e_1.error; } } - offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; - targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); - } - lockTimeBuffer = Buffer$e.alloc(4); - lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$e.concat([ - serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), - outputScript, - ]); - if (segwit && !isDecred) { - witness = Buffer$e.alloc(0); - for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$e.concat([ - Buffer$e.from("02", "hex"), - Buffer$e.from([signatures[i].length]), - signatures[i], - Buffer$e.from([publicKeys[i].length]), - publicKeys[i], - ]); - witness = Buffer$e.concat([witness, tmpScriptData]); + try { + for (_c = __values$2(merkelizedPsbt.outputMerkleMaps), _d = _c.next(); !_d.done; _d = _c.next()) { + map = _d.value; + clientInterpreter.addKnownMapping(map); + } } - result = Buffer$e.concat([result, witness]); - } - // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. - // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here - // and it should not break other coins because expiryHeight is false for them. - // Don't know about Decred though. - result = Buffer$e.concat([result, lockTimeBuffer]); - if (expiryHeight) { - result = Buffer$e.concat([ - result, - targetTransaction.nExpiryHeight || Buffer$e.alloc(0), - targetTransaction.extraData || Buffer$e.alloc(0), - ]); - } - if (isDecred) { - decredWitness_1 = Buffer$e.from([targetTransaction.inputs.length]); - inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$e.concat([ - decredWitness_1, - Buffer$e.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$e.from([0x00, 0x00, 0x00, 0x00]), - Buffer$e.from([0xff, 0xff, 0xff, 0xff]), - Buffer$e.from([targetTransaction.inputs[inputIndex].script.length]), - targetTransaction.inputs[inputIndex].script, - ]); - }); - result = Buffer$e.concat([result, decredWitness_1]); - } - return [2 /*return*/, result.toString("hex")]; - } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_f = _c["return"])) _f.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + clientInterpreter.addKnownList(merkelizedPsbt.inputMapCommitments); + inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); + outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ + merkelizedPsbt.getGlobalKeysValuesRoot(), + createVarint(merkelizedPsbt.getGlobalInputCount()), + inputMapsRoot, + createVarint(merkelizedPsbt.getGlobalOutputCount()), + outputMapsRoot, + walletPolicy.getWalletId(), + walletHMAC || Buffer$k.alloc(32, 0), + ]), clientInterpreter)]; + case 1: + _h.sent(); + yielded = clientInterpreter.getYielded(); + ret = new Map(); + try { + for (yielded_1 = __values$2(yielded), yielded_1_1 = yielded_1.next(); !yielded_1_1.done; yielded_1_1 = yielded_1.next()) { + inputAndSig = yielded_1_1.value; + ret.set(inputAndSig[0], inputAndSig.slice(1)); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (yielded_1_1 && !yielded_1_1.done && (_g = yielded_1["return"])) _g.call(yielded_1); + } + finally { if (e_3) throw e_3.error; } + } + return [2 /*return*/, ret]; + } + }); + }); + }; + AppClient.prototype.getMasterFingerprint = function () { + return __awaiter$5(this, void 0, void 0, function () { + return __generator$5(this, function (_a) { + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; + }); + }); + }; + return AppClient; + }()); + + function formatTransactionDebug(transaction) { + var str = "TX"; + str += " version " + transaction.version.toString("hex"); + if (transaction.locktime) { + str += " locktime " + transaction.locktime.toString("hex"); + } + if (transaction.witness) { + str += " witness " + transaction.witness.toString("hex"); + } + if (transaction.timestamp) { + str += " timestamp " + transaction.timestamp.toString("hex"); + } + if (transaction.nVersionGroupId) { + str += " nVersionGroupId " + transaction.nVersionGroupId.toString("hex"); + } + if (transaction.nExpiryHeight) { + str += " nExpiryHeight " + transaction.nExpiryHeight.toString("hex"); + } + if (transaction.extraData) { + str += " extraData " + transaction.extraData.toString("hex"); + } + transaction.inputs.forEach(function (_a, i) { + var prevout = _a.prevout, script = _a.script, sequence = _a.sequence; + str += "\ninput " + i + ":"; + str += " prevout " + prevout.toString("hex"); + str += " script " + script.toString("hex"); + str += " sequence " + sequence.toString("hex"); + }); + (transaction.outputs || []).forEach(function (_a, i) { + var amount = _a.amount, script = _a.script; + str += "\noutput " + i + ":"; + str += " amount " + amount.toString("hex"); + str += " script " + script.toString("hex"); + }); + return str; + } + + function splitTransaction(transactionHex, isSegwitSupported, hasTimestamp, hasExtraData, additionals) { + if (isSegwitSupported === void 0) { isSegwitSupported = false; } + if (hasTimestamp === void 0) { hasTimestamp = false; } + if (hasExtraData === void 0) { hasExtraData = false; } + if (additionals === void 0) { additionals = []; } + var inputs = []; + var outputs = []; + var witness = false; + var offset = 0; + var timestamp = Buffer$k.alloc(0); + var nExpiryHeight = Buffer$k.alloc(0); + var nVersionGroupId = Buffer$k.alloc(0); + var extraData = Buffer$k.alloc(0); + var isDecred = additionals.includes("decred"); + var transaction = Buffer$k.from(transactionHex, "hex"); + var version = transaction.slice(offset, offset + 4); + var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); + offset += 4; + if (!hasTimestamp && + isSegwitSupported && + transaction[offset] === 0 && + transaction[offset + 1] !== 0) { + offset += 2; + witness = true; + } + if (hasTimestamp) { + timestamp = transaction.slice(offset, 4 + offset); + offset += 4; + } + if (overwinter) { + nVersionGroupId = transaction.slice(offset, 4 + offset); + offset += 4; + } + var varint = getVarint(transaction, offset); + var numberInputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberInputs; i++) { + var prevout = transaction.slice(offset, offset + 36); + offset += 36; + var script = Buffer$k.alloc(0); + var tree = Buffer$k.alloc(0); + //No script for decred, it has a witness + if (!isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + } + else { + //Tree field + tree = transaction.slice(offset, offset + 1); + offset += 1; + } + var sequence = transaction.slice(offset, offset + 4); + offset += 4; + inputs.push({ + prevout: prevout, + script: script, + sequence: sequence, + tree: tree }); - }); - } - - var __assign$2 = (undefined && undefined.__assign) || function () { - __assign$2 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + } + varint = getVarint(transaction, offset); + var numberOutputs = varint[0]; + offset += varint[1]; + for (var i = 0; i < numberOutputs; i++) { + var amount = transaction.slice(offset, offset + 8); + offset += 8; + if (isDecred) { + //Script version + offset += 2; } - return t; + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + outputs.push({ + amount: amount, + script: script + }); + } + var witnessScript, locktime; + if (witness) { + witnessScript = transaction.slice(offset, -4); + locktime = transaction.slice(transaction.length - 4); + } + else { + locktime = transaction.slice(offset, offset + 4); + } + offset += 4; + if (overwinter || isDecred) { + nExpiryHeight = transaction.slice(offset, offset + 4); + offset += 4; + } + if (hasExtraData) { + extraData = transaction.slice(offset); + } + //Get witnesses for Decred + if (isDecred) { + varint = getVarint(transaction, offset); + offset += varint[1]; + if (varint[0] !== numberInputs) { + throw new Error("splitTransaction: incoherent number of witnesses"); + } + for (var i = 0; i < numberInputs; i++) { + //amount + offset += 8; + //block height + offset += 4; + //block index + offset += 4; + //Script size + varint = getVarint(transaction, offset); + offset += varint[1]; + var script = transaction.slice(offset, offset + varint[0]); + offset += varint[0]; + inputs[i].script = script; + } + } + var t = { + version: version, + inputs: inputs, + outputs: outputs, + locktime: locktime, + witness: witnessScript, + timestamp: timestamp, + nVersionGroupId: nVersionGroupId, + nExpiryHeight: nExpiryHeight, + extraData: extraData }; - return __assign$2.apply(this, arguments); - }; - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + log("btc", "splitTransaction " + transactionHex + ":\n" + formatTransactionDebug(t)); + return t; + } + + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -15499,7 +39369,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -15513,186 +39383,18 @@ case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$2 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$3(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$3(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$e.alloc(0); - nullPrevout = Buffer$e.alloc(0); - defaultVersion = Buffer$e.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - startTime = Date.now(); - targetTransaction = { - inputs: [], - timestamp: Buffer$e.alloc(0), - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$e.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$2(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$e.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$e.from(trustedInput, "hex") - : Buffer$e.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$e.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$e.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$e.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } }; /** * Bitcoin API. @@ -15704,8 +39406,11 @@ var Btc = /** @class */ (function () { function Btc(transport, scrambleKey) { if (scrambleKey === void 0) { scrambleKey = "BTC"; } + // cache the underlying implementation (only once) + this._lazyImpl = null; this.transport = transport; transport.decorateAppAPIMethods(this, [ + "getWalletXpub", "getWalletPublicKey", "signP2SHTransaction", "signMessageNew", @@ -15714,13 +39419,23 @@ "getTrustedInputBIP143", ], scrambleKey); } + /** + * Get an XPUB with a ledger device + * @param arg derivation parameter + * - path: a BIP 32 path of the account level. e.g. `84'/0'/0'` + * - xpubVersion: the XPUBVersion of the coin used. (use @ledgerhq/currencies if needed) + * @returns XPUB of the account + */ + Btc.prototype.getWalletXpub = function (arg) { + return this.getCorrectImpl().then(function (impl) { return impl.getWalletXpub(arg); }); + }; /** * @param path a BIP 32 path * @param options an object with optional these fields: * * - verify (boolean) will ask user to confirm the address on the device * - * - format ("legacy" | "p2sh" | "bech32" | "cashaddr") to use different bitcoin address formatter. + * - format ("legacy" | "p2sh" | "bech32" | "bech32m" | "cashaddr") to use different bitcoin address formatter. * * NB The normal usage is to use: * @@ -15728,7 +39443,7 @@ * * - p2sh format with 49' paths * - * - bech32 format with 173' paths + * - bech32 format with 84' paths * * - cashaddr in case of Bitcoin Cash * @@ -15737,6 +39452,7 @@ * btc.getWalletPublicKey("49'/0'/0'/0/0", { format: "p2sh" }).then(o => o.bitcoinAddress) */ Btc.prototype.getWalletPublicKey = function (path, opts) { + var _this = this; var options; if (arguments.length > 2 || typeof opts === "boolean") { console.warn("btc.getWalletPublicKey deprecated signature used. Please switch to getWalletPublicKey(path, { format, verify })"); @@ -15749,7 +39465,41 @@ else { options = opts || {}; } - return getWalletPublicKey(this.transport, __assign$1(__assign$1({}, options), { path: path })); + return this.getCorrectImpl().then(function (impl) { + /** + * Definition: A "normal path" is a prefix of a standard path where all + * the hardened steps of the standard path are included. For example, the + * paths m/44'/1'/17' and m/44'/1'/17'/1 are normal paths, but m/44'/1' + * is not. m/'199/1'/17'/0/1 is not a normal path either. + * + * There's a compatiblity issue between old and new app: When exporting + * the key of a non-normal path with verify=false, the new app would + * return an error, whereas the old app would return the key. + * + * See + * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#get_extended_pubkey + * + * If format bech32m is used, we'll not use old, because it doesn't + * support it. + * + * When to use new (given the app supports it) + * * format is bech32m or + * * path is normal or + * * verify is true + * + * Otherwise use old. + */ + if (impl instanceof BtcNew && + options.format != "bech32m" && + (!options.verify || options.verify == false) && + !isPathNormal(path)) { + console.warn("WARNING: Using deprecated device protocol to get the public key because\n \n * a non-standard path is requested, and\n * verify flag is false\n \n The new protocol only allows export of non-standard paths if the \n verify flag is true. Standard paths are (currently):\n\n M/44'/(1|0)'/X'\n M/49'/(1|0)'/X'\n M/84'/(1|0)'/X'\n M/86'/(1|0)'/X'\n M/48'/(1|0)'/X'/Y'\n\n followed by \"\", \"(0|1)\", or \"(0|1)/b\", where a and b are \n non-hardened. For example, the following paths are standard\n \n M/48'/1'/99'/7'\n M/86'/1'/99'/0\n M/48'/0'/99'/7'/1/17\n\n The following paths are non-standard\n\n M/48'/0'/99' // Not deepest hardened path\n M/48'/0'/99'/7'/1/17/2 // Too many non-hardened derivation steps\n M/199'/0'/1'/0/88 // Not a known purpose 199\n M/86'/1'/99'/2 // Change path item must be 0 or 1\n\n This compatibility safeguard will be removed in the future.\n Please consider calling Btc.getWalletXpub() instead."); + return _this.old().getWalletPublicKey(path, options); + } + else { + return impl.getWalletPublicKey(path, options); + } + }); }; /** * You can sign a message according to the Bitcoin Signature format and retrieve v, r, s given the message and the BIP 32 path of the account to sign. @@ -15761,10 +39511,7 @@ }).catch(function(ex) {console.log(ex);}); */ Btc.prototype.signMessageNew = function (path, messageHex) { - return signMessage(this.transport, { - path: path, - messageHex: messageHex - }); + return this.old().signMessageNew(path, messageHex); }; /** * To sign a transaction involving standard (P2PKH) inputs, call createTransaction with the following parameters @@ -15776,20 +39523,21 @@ * * sequence is the sequence number to use for this input (when using RBF), or non present * @param associatedKeysets is an array of BIP 32 paths pointing to the path to the private key used for each UTXO * @param changePath is an optional BIP 32 path pointing to the path to the public key used to compute the change address - * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign + * @param outputScriptHex is the hexadecimal serialized outputs of the transaction to sign, including leading vararg voutCount * @param lockTime is the optional lockTime of the transaction to sign, or default (0) * @param sigHashType is the hash type of the transaction to sign, or default (all) - * @param segwit is an optional boolean indicating wether to use segwit or not + * @param segwit is an optional boolean indicating wether to use segwit or not. This includes wrapped segwit. * @param initialTimestamp is an optional timestamp of the function call to use for coins that necessitate timestamps only, (not the one that the tx will include) * @param additionals list of additionnal options * * - "bech32" for spending native segwit outputs + * - "bech32m" for spending segwit v1+ outputs * - "abc" for bch * - "gold" for btg * - "bipxxx" for using BIPxxx * - "sapling" to indicate a zec transaction is supporting sapling (to be set over block 419200) * @param expiryHeight is an optional Buffer for zec overwinter / sapling Txs - * @param useTrustedInputForSegwit trust inputs for segwit transactions + * @param useTrustedInputForSegwit trust inputs for segwit transactions. If app version >= 1.4.0 this should be true. * @return the signed transaction ready to be broadcast * @example btc.createTransaction({ @@ -15802,7 +39550,9 @@ if (arguments.length > 1) { console.warn("@ledgerhq/hw-app-btc: createPaymentTransactionNew multi argument signature is deprecated. please switch to named parameters."); } - return createTransaction(this.transport, arg); + return this.getCorrectImpl().then(function (impl) { + return impl.createPaymentTransactionNew(arg); + }); }; /** * To obtain the signature of multisignature (P2SH) inputs, call signP2SHTransaction_async with the folowing parameters @@ -15824,10 +39574,7 @@ }).then(result => ...); */ Btc.prototype.signP2SHTransaction = function (arg) { - if (arguments.length > 1) { - console.warn("@ledgerhq/hw-app-btc: signP2SHTransaction multi argument signature is deprecated. please switch to named parameters."); - } - return signP2SHTransaction(this.transport, arg); + return this.old().signP2SHTransaction(arg); }; /** * For each UTXO included in your transaction, create a transaction object from the raw serialized version of the transaction used in this UTXO. @@ -15857,8 +39604,79 @@ if (additionals === void 0) { additionals = []; } return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); }; + Btc.prototype.getCorrectImpl = function () { + return __awaiter$4(this, void 0, void 0, function () { + var _lazyImpl, impl; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + _lazyImpl = this._lazyImpl; + if (_lazyImpl) + return [2 /*return*/, _lazyImpl]; + return [4 /*yield*/, this.inferCorrectImpl()]; + case 1: + impl = _a.sent(); + this._lazyImpl = impl; + return [2 /*return*/, impl]; + } + }); + }); + }; + Btc.prototype.inferCorrectImpl = function () { + return __awaiter$4(this, void 0, void 0, function () { + var appAndVersion, canUseNewImplementation; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; + case 1: + appAndVersion = _a.sent(); + canUseNewImplementation = canSupportApp(appAndVersion); + if (!canUseNewImplementation) { + return [2 /*return*/, this.old()]; + } + else { + return [2 /*return*/, this["new"]()]; + } + } + }); + }); + }; + Btc.prototype.old = function () { + return new BtcOld(this.transport); + }; + Btc.prototype["new"] = function () { + return new BtcNew(new AppClient(this.transport)); + }; return Btc; }()); + function isPathNormal(path) { + //path is not deepest hardened node of a standard path or deeper, use BtcOld + var h = 0x80000000; + var pathElems = pathStringToArray(path); + var hard = function (n) { return n >= h; }; + var soft = function (n) { return !n || n < h; }; + var change = function (n) { return !n || n == 0 || n == 1; }; + if (pathElems.length >= 3 && + pathElems.length <= 5 && + [44 + h, 49 + h, 84 + h, 86 + h].some(function (v) { return v == pathElems[0]; }) && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + change(pathElems[3]) && + soft(pathElems[4])) { + return true; + } + if (pathElems.length >= 4 && + pathElems.length <= 6 && + 48 + h == pathElems[0] && + [0 + h, 1 + h].some(function (v) { return v == pathElems[1]; }) && + hard(pathElems[2]) && + hard(pathElems[3]) && + change(pathElems[4]) && + soft(pathElems[5])) { + return true; + } + return false; + } var Btc$1 = /*#__PURE__*/Object.freeze({ __proto__: null, @@ -16283,7 +40101,7 @@ TransportStatusError: TransportStatusError }); - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -16292,7 +40110,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -16378,19 +40196,19 @@ * @return a Promise of response buffer */ this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$e.alloc(0); } + if (data === void 0) { data = Buffer$k.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { + return __awaiter$3(_this, void 0, void 0, function () { var response, sw; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - return [4 /*yield*/, this.exchange(Buffer$e.concat([ - Buffer$e.from([cla, ins, p1, p2]), - Buffer$e.from([data.length]), + return [4 /*yield*/, this.exchange(Buffer$k.concat([ + Buffer$k.from([cla, ins, p1, p2]), + Buffer$k.from([data.length]), data, ]))]; case 1: @@ -16404,10 +40222,10 @@ }); }); }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + this.exchangeAtomicImpl = function (f) { return __awaiter$3(_this, void 0, void 0, function () { var resolveBusy, busyPromise, unresponsiveReached, timeout, res; var _this = this; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: if (this.exchangeBusyPromise) { @@ -16572,9 +40390,9 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return __awaiter$2(_this, void 0, void 0, function () { + return __awaiter$3(_this, void 0, void 0, function () { var _appAPIlock; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: _appAPIlock = this._appAPIlock; @@ -16611,12 +40429,12 @@ var errors_1 = require$$0; var Tag = 0x05; function asUInt16BE(value) { - var b = Buffer$e.alloc(2); + var b = Buffer$k.alloc(2); b.writeUInt16BE(value, 0); return b; } var initialAcc = { - data: Buffer$e.alloc(0), + data: Buffer$k.alloc(0), dataLength: 0, sequence: 0 }; @@ -16626,21 +40444,21 @@ var createHIDframing = function (channel, packetSize) { return { makeBlocks: function (apdu) { - var data = Buffer$e.concat([asUInt16BE(apdu.length), apdu]); + var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); var blockSize = packetSize - 5; var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$e.concat([ + data = Buffer$k.concat([ data, - Buffer$e.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), ]); var blocks = []; for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$e.alloc(5); + var head = Buffer$k.alloc(5); head.writeUInt16BE(channel, 0); head.writeUInt8(Tag, 2); head.writeUInt16BE(i, 3); var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$e.concat([head, chunk])); + blocks.push(Buffer$k.concat([head, chunk])); } return blocks; }, @@ -16660,7 +40478,7 @@ } sequence++; var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$e.concat([data, chunkData]); + data = Buffer$k.concat([data, chunkData]); if (data.length > dataLength) { data = data.slice(0, dataLength); } @@ -16799,7 +40617,7 @@ } } - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -16808,7 +40626,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -16841,9 +40659,9 @@ }, ]; function requestLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var device; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.requestDevice({ filters: ledgerDevices @@ -16856,9 +40674,9 @@ }); } function getLedgerDevices() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var devices; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.getDevices()]; case 1: @@ -16869,9 +40687,9 @@ }); } function getFirstLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var existingDevices; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -16889,7 +40707,7 @@ typeof navigator.usb.getDevices === "function"); }; - var __extends = (undefined && undefined.__extends) || (function () { + var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -16904,7 +40722,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -16913,7 +40731,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -16950,7 +40768,7 @@ * TransportWebUSB.create().then(transport => ...) */ var TransportWebUSB = /** @class */ (function (_super) { - __extends(TransportWebUSB, _super); + __extends$2(TransportWebUSB, _super); function TransportWebUSB(device, interfaceNumber) { var _this = _super.call(this) || this; _this.channel = Math.floor(Math.random() * 0xffff); @@ -16971,9 +40789,9 @@ * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ TransportWebUSB.request = function () { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var device; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, requestLedgerDevice()]; case 1: @@ -16987,9 +40805,9 @@ * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). */ TransportWebUSB.openConnected = function () { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var devices; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -17005,9 +40823,9 @@ * Create a Ledger transport with a USBDevice */ TransportWebUSB.open = function (device) { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var iface, interfaceNumber, e_1, transport, onDisconnect; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, device.open()]; case 1: @@ -17061,8 +40879,8 @@ * Release the transport device */ TransportWebUSB.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { + return __awaiter$1(this, void 0, void 0, function () { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.exchangeBusyPromise]; case 1: @@ -17087,14 +40905,14 @@ * @returns a promise of apdu response */ TransportWebUSB.prototype.exchange = function (apdu) { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var b; var _this = this; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter$1(_this, void 0, void 0, function () { var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return __generator(this, function (_b) { + return __generator$1(this, function (_b) { switch (_b.label) { case 0: _a = this, channel = _a.channel, packetSize = _a.packetSize; @@ -17117,7 +40935,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$e.from(r.data.buffer); + buffer = Buffer$k.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -17158,344 +40976,1088 @@ var unsubscribed = false; getFirstLedgerDevice().then(function (device) { if (!unsubscribed) { - var deviceModel = identifyUSBProductId(device.productId); - observer.next({ - type: "add", - descriptor: device, - deviceModel: deviceModel - }); - observer.complete(); - } - }, function (error) { - if (window.DOMException && - error instanceof window.DOMException && - error.code === 18) { - observer.error(new TransportWebUSBGestureRequired(error.message)); - } - else { - observer.error(new TransportOpenUserCancelled(error.message)); - } - }); - function unsubscribe() { - unsubscribed = true; - } - return { - unsubscribe: unsubscribe - }; - }; - return TransportWebUSB; - }(Transport)); - function gracefullyResetDevice(device) { - return __awaiter(this, void 0, void 0, function () { - var err_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - return [4 /*yield*/, device.reset()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - err_1 = _a.sent(); - console.warn(err_1); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); - } - - var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': TransportWebUSB - }); - - var inherits$2 = inherits_browser.exports; - var HashBase = hashBase; - var Buffer$1 = safeBuffer.exports.Buffer; - - var ARRAY16 = new Array(16); - - function MD5$1 () { - HashBase.call(this, 64); - - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } - - inherits$2(MD5$1, HashBase); - - MD5$1.prototype._update = function () { - var M = ARRAY16; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; - }; - - MD5$1.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + var deviceModel = identifyUSBProductId(device.productId); + observer.next({ + type: "add", + descriptor: device, + deviceModel: deviceModel + }); + observer.complete(); + } + }, function (error) { + if (window.DOMException && + error instanceof window.DOMException && + error.code === 18) { + observer.error(new TransportWebUSBGestureRequired(error.message)); + } + else { + observer.error(new TransportOpenUserCancelled(error.message)); + } + }); + function unsubscribe() { + unsubscribed = true; + } + return { + unsubscribe: unsubscribe + }; + }; + return TransportWebUSB; + }(Transport)); + function gracefullyResetDevice(device) { + return __awaiter$1(this, void 0, void 0, function () { + var err_1; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, device.reset()]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + err_1 = _a.sent(); + console.warn(err_1); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); + } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + var TransportWebUSB$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': TransportWebUSB + }); - // produce result - var buffer = Buffer$1.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends$1(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isFunction(x) { + return typeof x === 'function'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var _enable_super_gross_mode_that_will_cause_bad_things = false; + var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, }; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) - } - - function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function hostReportError(err) { + setTimeout(function () { throw err; }, 0); } - function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 - } + /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ + var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + }, + complete: function () { } + }; - function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 - } + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); - function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isObject(x) { + return x !== null && typeof x === 'object'; } - var md5_js = MD5$1; - - var Buffer = safeBuffer.exports.Buffer; - var Transform = require$$1.Transform; - var StringDecoder = string_decoder.StringDecoder; - var inherits$1 = inherits_browser.exports; - - function CipherBase (hashMode) { - Transform.call(this); - this.hashMode = typeof hashMode === 'string'; - if (this.hashMode) { - this[hashMode] = this._finalOrDigest; - } else { - this.final = this._finalOrDigest; - } - if (this._final) { - this.__final = this._final; - this._final = null; - } - this._decoder = null; - this._encoding = null; + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; + })(); + var UnsubscriptionError = UnsubscriptionErrorImpl; + + /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ + var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._ctorUnsubscribe = true; + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (isFunction(_unsubscribe)) { + if (_ctorUnsubscribe) { + this._unsubscribe = undefined; + } + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (isArray(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof UnsubscriptionError) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } + } + } + } + if (errors) { + throw new UnsubscriptionError(errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + } + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; + }()); + function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); } - inherits$1(CipherBase, Transform); - - CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer.from(data, inputEnc); - } - - var outData = this._update(data); - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc); - } - - return outData - }; - - CipherBase.prototype.setAutoPadding = function () {}; - CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') - }; - - CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') - }; - CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') - }; + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); + })(); - CipherBase.prototype._transform = function (data, _, next) { - var err; - try { - if (this.hashMode) { - this._update(data); - } else { - this.push(this._update(data)); + /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + var Subscriber = /*@__PURE__*/ (function (_super) { + __extends$1(Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = empty; + break; + case 1: + if (!destinationOrNext) { + _this.destination = empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; } - } catch (e) { - err = e; - } finally { - next(err); - } - }; - CipherBase.prototype._flush = function (done) { - var err; - try { - this.push(this.__final()); - } catch (e) { - err = e; - } - - done(err); - }; - CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer.alloc(0); - if (outputEnc) { - outData = this._toString(outData, outputEnc, true); - } - return outData - }; - - CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc); - this._encoding = enc; - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value); - if (fin) { - out += this._decoder.end(); - } - - return out - }; + Subscriber.prototype[rxSubscriber] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; + }(Subscription)); + var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __extends$1(SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (isFunction(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== empty) { + context = Object.create(observerOrNext); + if (isFunction(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + hostReportError(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + hostReportError(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!config.useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + hostReportError(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ + function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof Subscriber) { + observer = destination; + } + else { + observer = null; + } + } + return true; + } - var cipherBase = CipherBase; + /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ + function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber]) { + return nextOrObserver[rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber(empty); + } + return new Subscriber(nextOrObserver, error, complete); + } - var inherits = inherits_browser.exports; - var MD5 = md5_js; - var RIPEMD160 = ripemd160; - var sha = sha_js.exports; - var Base = cipherBase; + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); - function Hash (hash) { - Base.call(this, 'digest'); + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function identity(x) { + return x; + } - this._hash = hash; + /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ + function pipeFromArray(fns) { + if (fns.length === 0) { + return identity; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; } - inherits(Hash, Base); + /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = toSubscriber(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (config.useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (canReportError(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[observable] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipeFromArray(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; + }()); + function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = config.Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; + } - Hash.prototype._update = function (data) { - this._hash.update(data); - }; + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { + function ObjectUnsubscribedErrorImpl() { + Error.call(this); + this.message = 'object unsubscribed'; + this.name = 'ObjectUnsubscribedError'; + return this; + } + ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ObjectUnsubscribedErrorImpl; + })(); + var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - Hash.prototype._final = function () { - return this._hash.digest() - }; + /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ + var SubjectSubscription = /*@__PURE__*/ (function (_super) { + __extends$1(SubjectSubscription, _super); + function SubjectSubscription(subject, subscriber) { + var _this = _super.call(this) || this; + _this.subject = subject; + _this.subscriber = subscriber; + _this.closed = false; + return _this; + } + SubjectSubscription.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.closed = true; + var subject = this.subject; + var observers = subject.observers; + this.subject = null; + if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { + return; + } + var subscriberIndex = observers.indexOf(this.subscriber); + if (subscriberIndex !== -1) { + observers.splice(subscriberIndex, 1); + } + }; + return SubjectSubscription; + }(Subscription)); + + /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ + var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + __extends$1(SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; + }(Subscriber)); + var Subject = /*@__PURE__*/ (function (_super) { + __extends$1(Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[rxSubscriber] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); + } + } + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return Subscription.EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return Subscription.EMPTY; + } + else { + this.observers.push(subscriber); + return new SubjectSubscription(this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new Observable(); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; + }(Observable)); + var AnonymousSubject = /*@__PURE__*/ (function (_super) { + __extends$1(AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return Subscription.EMPTY; + } + }; + return AnonymousSubject; + }(Subject)); - var browser = function createHash (alg) { - alg = alg.toLowerCase(); - if (alg === 'md5') return new MD5() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + var net = {}; - return new Hash(sha(alg)) + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - var browser$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({ - __proto__: null, - 'default': browser - }, [browser])); + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Speculos TCP transport implementation + * + * @example + * import SpeculosTransport from "@ledgerhq/hw-transport-node-speculos"; + * const transport = await SpeculosTransport.open({ apduPort }); + * const res = await transport.send(0xE0, 0x01, 0, 0); + */ + var SpeculosTransport = /** @class */ (function (_super) { + __extends(SpeculosTransport, _super); + function SpeculosTransport(apduSocket, opts) { + var _this = _super.call(this) || this; + _this.rejectExchange = function (_e) { }; + _this.resolveExchange = function (_b) { }; + _this.automationEvents = new Subject(); + /** + * Send a speculos button command + * typically "Ll" would press and release the left button + * typically "Rr" would press and release the right button + * @param {*} command + */ + _this.button = function (command) { + return new Promise(function (resolve, reject) { + log("speculos-button", command); + var _a = _this.opts, buttonPort = _a.buttonPort, host = _a.host; + if (!buttonPort) + throw new Error("buttonPort is missing"); + var socket = new net.Socket(); + socket.on("error", function (e) { + socket.destroy(); + reject(e); + }); + socket.connect(buttonPort, host || "127.0.0.1", function () { + socket.write(Buffer$k.from(command, "ascii")); + socket.destroy(); + resolve(); + }); + }); + }; + _this.opts = opts; + _this.apduSocket = apduSocket; + apduSocket.on("error", function (e) { + _this.emit("disconnect", new DisconnectedDevice(e.message)); + _this.rejectExchange(e); + _this.apduSocket.destroy(); + }); + apduSocket.on("end", function () { + _this.emit("disconnect", new DisconnectedDevice()); + _this.rejectExchange(new DisconnectedDeviceDuringOperation()); + }); + apduSocket.on("data", function (data) { + try { + _this.resolveExchange(decodeAPDUPayload(data)); + } + catch (e) { + _this.rejectExchange(e); + } + }); + var automationPort = opts.automationPort; + if (automationPort) { + var socket_1 = new net.Socket(); + _this.automationSocket = socket_1; + socket_1.on("error", function (e) { + log("speculos-automation-error", String(e)); + socket_1.destroy(); + }); + socket_1.on("data", function (data) { + log("speculos-automation-data", data.toString("ascii")); + var split = data.toString("ascii").split("\n"); + split + .filter(function (ascii) { return !!ascii; }) + .forEach(function (ascii) { + var json = JSON.parse(ascii); + _this.automationEvents.next(json); + }); + }); + socket_1.connect(automationPort, opts.host || "127.0.0.1"); + } + return _this; + } + SpeculosTransport.prototype.exchange = function (apdu) { + return __awaiter(this, void 0, void 0, function () { + var hex, encoded, res; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + hex = apdu.toString("hex"); + log("apdu", "=> " + hex); + encoded = encodeAPDU(apdu); + return [4 /*yield*/, new Promise(function (resolve, reject) { + _this.rejectExchange = reject; + _this.resolveExchange = resolve; + _this.apduSocket.write(encoded); + })]; + case 1: + res = _a.sent(); + log("apdu", "<= " + res.toString("hex")); + return [2 /*return*/, res]; + } + }); + }); + }; + SpeculosTransport.prototype.setScrambleKey = function () { }; + SpeculosTransport.prototype.close = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + if (this.automationSocket) + this.automationSocket.destroy(); + this.apduSocket.destroy(); + return [2 /*return*/, Promise.resolve()]; + }); + }); + }; + SpeculosTransport.isSupported = function () { return Promise.resolve(true); }; + // this transport is not discoverable + SpeculosTransport.list = function () { return Promise.resolve([]); }; + SpeculosTransport.listen = function (_observer) { return ({ + unsubscribe: function () { } + }); }; + /** + * + */ + SpeculosTransport.open = function (opts) { + return new Promise(function (resolve, reject) { + var socket = new net.Socket(); + socket.on("error", function (e) { + socket.destroy(); + reject(e); + }); + socket.on("end", function () { + reject(new DisconnectedDevice("tcp closed")); + }); + socket.connect(opts.apduPort, opts.host || "127.0.0.1", function () { + // we delay a bit the transport creation to make sure the tcp does not hang up + setTimeout(function () { + resolve(new SpeculosTransport(socket, opts)); + }, 100); + }); + }); + }; + return SpeculosTransport; + }(Transport)); + function encodeAPDU(apdu) { + var size = Buffer$k.allocUnsafe(4); + size.writeUIntBE(apdu.length, 0, 4); + return Buffer$k.concat([size, apdu]); + } + function decodeAPDUPayload(data) { + var dataLength = data.readUIntBE(0, 4); // 4 bytes tells the data length + var size = dataLength + 2; // size does not include the status code so we add 2 + var payload = data.slice(4); + if (payload.length !== size) { + throw new TransportError("Expected payload of length ".concat(size, " but got ").concat(payload.length), ""); + } + return payload; + } exports.Btc = Btc$1; exports.Log = index; + exports.SpeculosTransport = SpeculosTransport; exports.TransportWebUSB = TransportWebUSB$1; - exports.createHash = browser$1; + exports.createHash = browser$4; Object.defineProperty(exports, '__esModule', { value: true }); @@ -17503,5 +42065,6 @@ window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; +window.TransportSpeculos = NewLedger.SpeculosTransport.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From f6332e8c25189f89c8775843854e8bfcbc10c669 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 09:59:26 +1100 Subject: [PATCH 59/78] speculos transport --- js/cointoolkit.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index f16b53b3..36d6b249 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -704,7 +704,8 @@ $(document).ready(function() { async function getLedgerSignatures(currenttransaction, hashType, callback) { try { - const transport = await window.TransportWebUSB.create(); + //const transport = await window.TransportWebUSB.create(); + const transport = await window.SpeculosTransport.open({ 40000 }); const appBtc = new window.Btc(transport); var isPeercoin = true; From 4eeb650cad39c655298061114c9c39bb2a9fcd49 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 10:04:21 +1100 Subject: [PATCH 60/78] apduPort config --- js/cointoolkit.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 36d6b249..3e1eb7f2 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -705,7 +705,8 @@ $(document).ready(function() { async function getLedgerSignatures(currenttransaction, hashType, callback) { try { //const transport = await window.TransportWebUSB.create(); - const transport = await window.SpeculosTransport.open({ 40000 }); + const apduPort = 40000; + const transport = await window.SpeculosTransport.open({ apduPort }); const appBtc = new window.Btc(transport); var isPeercoin = true; From 34804d869147094178336ca7b447241d90343a99 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 10:11:11 +1100 Subject: [PATCH 61/78] wtf --- js/ledger.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/js/ledger.js b/js/ledger.js index 39ba1f91..d266397b 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -42053,9 +42053,14 @@ return payload; } + var SpeculosTransport$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': SpeculosTransport + }); + exports.Btc = Btc$1; exports.Log = index; - exports.SpeculosTransport = SpeculosTransport; + exports.SpeculosTransport = SpeculosTransport$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; From 9e8939d1d1f2150772366467bdc3eb9f0a9717af Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 10:16:23 +1100 Subject: [PATCH 62/78] wtf --- js/ledger.js | 1336 ++++++-------------------------------------------- 1 file changed, 153 insertions(+), 1183 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index d266397b..6187df29 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -999,7 +999,7 @@ var toString = {}.toString; - var isArray$4 = Array.isArray || function (arr) { + var isArray$3 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$4(obj.data)) { + if (obj.type === 'Buffer' && isArray$3(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1332,7 +1332,7 @@ }; Buffer$k.concat = function concat (list, length) { - if (!isArray$4(list)) { + if (!isArray$3(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -5162,7 +5162,7 @@ var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config$1 = {}; + var config = {}; function noop() {} @@ -5239,7 +5239,7 @@ hrtime: hrtime, platform: platform, release: release, - config: config$1, + config: config, uptime: uptime }; @@ -5778,7 +5778,7 @@ } }); for (var x = args[i]; i < len; x = args[++i]) { - if (isNull$1(x) || !isObject$2(x)) { + if (isNull$1(x) || !isObject$1(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); @@ -5929,7 +5929,7 @@ // Check that value is an object with an inspect function on it if (ctx.customInspect && value && - isFunction$2(value.inspect) && + isFunction$1(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== inspect && // Also filter out any prototype objects using the circular check. @@ -5964,7 +5964,7 @@ // Some type of object without properties can be shortcutted. if (keys.length === 0) { - if (isFunction$2(value)) { + if (isFunction$1(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } @@ -5982,13 +5982,13 @@ var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array - if (isArray$3(value)) { + if (isArray$2(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions - if (isFunction$2(value)) { + if (isFunction$1(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } @@ -6161,7 +6161,7 @@ // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. - function isArray$3(ar) { + function isArray$2(ar) { return Array.isArray(ar); } @@ -6186,23 +6186,23 @@ } function isRegExp$1(re) { - return isObject$2(re) && objectToString$1(re) === '[object RegExp]'; + return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; } - function isObject$2(arg) { + function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isDate$1(d) { - return isObject$2(d) && objectToString$1(d) === '[object Date]'; + return isObject$1(d) && objectToString$1(d) === '[object Date]'; } function isError$1(e) { - return isObject$2(e) && + return isObject$1(e) && (objectToString$1(e) === '[object Error]' || e instanceof Error); } - function isFunction$2(arg) { + function isFunction$1(arg) { return typeof arg === 'function'; } @@ -6212,7 +6212,7 @@ function _extend(origin, add) { // Don't do anything if add isn't an object - if (!add || !isObject$2(add)) return origin; + if (!add || !isObject$1(add)) return origin; var keys = Object.keys(add); var i = keys.length; @@ -8186,13 +8186,13 @@ // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. - function isArray$2(arg) { + function isArray$1(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } - util$5.isArray = isArray$2; + util$5.isArray = isArray$1; function isBoolean(arg) { return typeof arg === 'boolean'; @@ -8234,10 +8234,10 @@ } util$5.isRegExp = isRegExp; - function isObject$1(arg) { + function isObject(arg) { return typeof arg === 'object' && arg !== null; } - util$5.isObject = isObject$1; + util$5.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; @@ -8249,10 +8249,10 @@ } util$5.isError = isError; - function isFunction$1(arg) { + function isFunction(arg) { return typeof arg === 'function'; } - util$5.isFunction = isFunction$1; + util$5.isFunction = isFunction; function isPrimitive(arg) { return arg === null || @@ -8294,7 +8294,7 @@ var _stream_readable = Readable$1; /**/ - var isArray$1 = isarray; + var isArray = isarray; /**/ @@ -8833,7 +8833,7 @@ // is attached before any userland ones. NEVER DO THIS. if (!dest._events || !dest._events.error) dest.on('error', onerror); - else if (isArray$1(dest._events.error)) + else if (isArray(dest._events.error)) dest._events.error.unshift(onerror); else dest._events.error = [onerror, dest._events.error]; @@ -35076,7 +35076,7 @@ return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } - var __extends$6 = (undefined && undefined.__extends) || (function () { + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -35104,7 +35104,7 @@ * and calls an abstract method to do the actual work. */ var SingleKeyAccount = /** @class */ (function (_super) { - __extends$6(SingleKeyAccount, _super); + __extends$4(SingleKeyAccount, _super); function SingleKeyAccount() { return _super !== null && _super.apply(this, arguments) || this; } @@ -35135,7 +35135,7 @@ return SingleKeyAccount; }(BaseAccount)); var p2pkh = /** @class */ (function (_super) { - __extends$6(p2pkh, _super); + __extends$4(p2pkh, _super); function p2pkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -35163,7 +35163,7 @@ return p2pkh; }(SingleKeyAccount)); var p2tr = /** @class */ (function (_super) { - __extends$6(p2tr, _super); + __extends$4(p2tr, _super); function p2tr() { return _super !== null && _super.apply(this, arguments) || this; } @@ -35229,7 +35229,7 @@ return p2tr; }(SingleKeyAccount)); var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$6(p2wpkhWrapped, _super); + __extends$4(p2wpkhWrapped, _super); function p2wpkhWrapped() { return _super !== null && _super.apply(this, arguments) || this; } @@ -35272,7 +35272,7 @@ return p2wpkhWrapped; }(SingleKeyAccount)); var p2wpkh = /** @class */ (function (_super) { - __extends$6(p2wpkh, _super); + __extends$4(p2wpkh, _super); function p2wpkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -35508,7 +35508,7 @@ return tx.buffer(); } - var __extends$5 = (undefined && undefined.__extends) || (function () { + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -35569,7 +35569,7 @@ })(psbtOut || (psbtOut = {})); var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { - __extends$5(NoSuchEntry, _super); + __extends$3(NoSuchEntry, _super); function NoSuchEntry() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36241,7 +36241,7 @@ ]); } - var __awaiter$f = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -36250,7 +36250,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$f = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -36331,9 +36331,9 @@ */ BtcNew.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, xpubComponents; - return __generator$f(this, function (_b) { + return __generator$e(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -36358,9 +36358,9 @@ */ BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$f(this, function (_c) { + return __generator$e(this, function (_c) { switch (_c.label) { case 0: pathElements = pathStringToArray(path); @@ -36398,9 +36398,9 @@ * ourselves, but we don't at this time, and instead return an empty ("") address. */ BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: accountPath = hardenedPathOf(pathElements); @@ -36429,9 +36429,9 @@ * transaction is returned. */ BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputCount = arg.inputs.length; @@ -36542,9 +36542,9 @@ * properties depend on the accountType used. */ BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElems, i, xpub, pubkey, cond; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: if (!path) @@ -36573,9 +36573,9 @@ * public key and its derivation path. */ BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputTx = input[0]; @@ -36620,9 +36620,9 @@ * to the appropriate input fields of the PSBT. */ BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var sigs; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; case 1: @@ -36739,7 +36739,7 @@ }; return __assign$4.apply(this, arguments); }; - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -36748,7 +36748,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -36782,9 +36782,9 @@ cashaddr: 3 }; function getWalletPublicKey(transport, options) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$d(this, void 0, void 0, function () { var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$e(this, function (_b) { + return __generator$d(this, function (_b) { switch (_b.label) { case 0: _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; @@ -36857,7 +36857,7 @@ var browser = invariant; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -36866,7 +36866,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -36905,9 +36905,9 @@ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$d(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var data, firstRound, prefix, trustedInput, res; - return __generator$d(this, function (_a) { + return __generator$c(this, function (_a) { switch (_a.label) { case 0: firstRound = false; @@ -36931,11 +36931,11 @@ } function getTrustedInput(transport, indexLookup, transaction, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$d(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; var e_1, _a, e_2, _b; var _this = this; - return __generator$d(this, function (_c) { + return __generator$c(this, function (_c) { switch (_c.label) { case 0: version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; @@ -36944,10 +36944,10 @@ } isDecred = additionals.includes("decred"); isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$d(_this, void 0, void 0, function () { + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; var e_3, _a; - return __generator$d(this, function (_b) { + return __generator$c(this, function (_b) { switch (_b.label) { case 0: seq = sequence || Buffer$k.alloc(0); @@ -37121,7 +37121,7 @@ }); } - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37130,7 +37130,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37188,10 +37188,10 @@ if (overwinter === void 0) { overwinter = false; } if (additionals === void 0) { additionals = []; } if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$c(this, void 0, void 0, function () { + return __awaiter$b(this, void 0, void 0, function () { var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; var e_2, _c, e_1, _d; - return __generator$c(this, function (_e) { + return __generator$b(this, function (_e) { switch (_e.label) { case 0: data = Buffer$k.concat([ @@ -37374,7 +37374,7 @@ }); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37383,7 +37383,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37416,9 +37416,9 @@ } function hashOutputFull(transport, outputScript, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$a(this, void 0, void 0, function () { var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$b(this, function (_a) { + return __generator$a(this, function (_a) { switch (_a.label) { case 0: offset = 0; @@ -37448,7 +37448,7 @@ }); } - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37457,7 +37457,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37484,9 +37484,9 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$a(void 0, void 0, void 0, function () { + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$a(this, function (_a) { + return __generator$9(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; case 1: @@ -37529,7 +37529,7 @@ }; return __assign$3.apply(this, arguments); }; - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37538,7 +37538,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37586,10 +37586,10 @@ onDeviceSignatureRequested: function () { } }; function createTransaction(transport, arg) { - return __awaiter$9(this, void 0, void 0, function () { + return __awaiter$8(this, void 0, void 0, function () { var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; var e_2, _a; - return __generator$9(this, function (_b) { + return __generator$8(this, function (_b) { switch (_b.label) { case 0: signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); @@ -37912,7 +37912,7 @@ }); } - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37921,7 +37921,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37950,9 +37950,9 @@ }; function signMessage(transport, _a) { var path = _a.path, messageHex = _a.messageHex; - return __awaiter$8(this, void 0, void 0, function () { + return __awaiter$7(this, void 0, void 0, function () { var paths, message, offset, _loop_1, res, v, r, s; - return __generator$8(this, function (_b) { + return __generator$7(this, function (_b) { switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); @@ -37960,7 +37960,7 @@ offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; - return __generator$8(this, function (_c) { + return __generator$7(this, function (_c) { switch (_c.label) { case 0: maxChunkSize = offset === 0 @@ -38032,7 +38032,7 @@ }; return __assign$2.apply(this, arguments); }; - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38041,7 +38041,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38086,10 +38086,10 @@ transactionVersion: DEFAULT_VERSION }; function signP2SHTransaction(transport, arg) { - return __awaiter$7(this, void 0, void 0, function () { + return __awaiter$6(this, void 0, void 0, function () { var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; - return __generator$7(this, function (_c) { + return __generator$6(this, function (_c) { switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; @@ -38236,7 +38236,7 @@ }; return __assign$1.apply(this, arguments); }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38245,7 +38245,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38285,9 +38285,9 @@ this.derivationsCache = {}; } BtcOld.prototype.derivatePath = function (path) { - return __awaiter$6(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var res; - return __generator$6(this, function (_a) { + return __generator$5(this, function (_a) { switch (_a.label) { case 0: if (this.derivationsCache[path]) @@ -38305,9 +38305,9 @@ }; BtcOld.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$6(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$6(this, function (_b) { + return __generator$5(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -38515,7 +38515,7 @@ return MerkleMap; }()); - var __extends$4 = (undefined && undefined.__extends) || (function () { + var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -38567,7 +38567,7 @@ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt */ var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$4(MerkelizedPsbt, _super); + __extends$2(MerkelizedPsbt, _super); function MerkelizedPsbt(psbt) { var _this = _super.call(this) || this; _this.inputMerkleMaps = []; @@ -38611,7 +38611,7 @@ return MerkelizedPsbt; }(PsbtV2)); - var __extends$3 = (undefined && undefined.__extends) || (function () { + var __extends$1 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -38676,7 +38676,7 @@ return ClientCommand; }()); var YieldCommand = /** @class */ (function (_super) { - __extends$3(YieldCommand, _super); + __extends$1(YieldCommand, _super); function YieldCommand(results, progressCallback) { var _this = _super.call(this) || this; _this.progressCallback = progressCallback; @@ -38692,7 +38692,7 @@ return YieldCommand; }(ClientCommand)); var GetPreimageCommand = /** @class */ (function (_super) { - __extends$3(GetPreimageCommand, _super); + __extends$1(GetPreimageCommand, _super); function GetPreimageCommand(known_preimages, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_PREIMAGE; @@ -38738,7 +38738,7 @@ return GetPreimageCommand; }(ClientCommand)); var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$3(GetMerkleLeafProofCommand, _super); + __extends$1(GetMerkleLeafProofCommand, _super); function GetMerkleLeafProofCommand(known_trees, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; @@ -38790,7 +38790,7 @@ return GetMerkleLeafProofCommand; }(ClientCommand)); var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$3(GetMerkleLeafIndexCommand, _super); + __extends$1(GetMerkleLeafIndexCommand, _super); function GetMerkleLeafIndexCommand(known_trees) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; @@ -38832,7 +38832,7 @@ return GetMerkleLeafIndexCommand; }(ClientCommand)); var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$3(GetMoreElementsCommand, _super); + __extends$1(GetMoreElementsCommand, _super); function GetMoreElementsCommand(queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MORE_ELEMENTS; @@ -38951,7 +38951,7 @@ return ClientCommandInterpreter; }()); - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38960,7 +38960,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39022,9 +39022,9 @@ this.transport = transport; } AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var response, hwRequest, commandResponse; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ 0x9000, @@ -39050,9 +39050,9 @@ }); }; AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var response; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: if (pathElements.length > 6) { @@ -39070,9 +39070,9 @@ }); }; AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var clientInterpreter, addressIndexBuffer, response; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: if (change !== 0 && change !== 1) @@ -39102,10 +39102,10 @@ }); }; AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; var e_1, _e, e_2, _f, e_3, _g; - return __generator$5(this, function (_h) { + return __generator$4(this, function (_h) { switch (_h.label) { case 0: merkelizedPsbt = new MerkelizedPsbt(psbt); @@ -39179,8 +39179,8 @@ }); }; AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$5(this, void 0, void 0, function () { - return __generator$5(this, function (_a) { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; }); }); @@ -39360,7 +39360,7 @@ return t; } - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39369,7 +39369,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39605,9 +39605,9 @@ return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); }; Btc.prototype.getCorrectImpl = function () { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$3(this, void 0, void 0, function () { var _lazyImpl, impl; - return __generator$4(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: _lazyImpl = this._lazyImpl; @@ -39623,9 +39623,9 @@ }); }; Btc.prototype.inferCorrectImpl = function () { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$3(this, void 0, void 0, function () { var appAndVersion, canUseNewImplementation; - return __generator$4(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; case 1: @@ -40101,7 +40101,7 @@ TransportStatusError: TransportStatusError }); - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40110,7 +40110,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40198,9 +40198,9 @@ this.send = function (cla, ins, p1, p2, data, statusList) { if (data === void 0) { data = Buffer$k.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$3(_this, void 0, void 0, function () { + return __awaiter$2(_this, void 0, void 0, function () { var response, sw; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: if (data.length >= 256) { @@ -40222,10 +40222,10 @@ }); }); }; - this.exchangeAtomicImpl = function (f) { return __awaiter$3(_this, void 0, void 0, function () { + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { var resolveBusy, busyPromise, unresponsiveReached, timeout, res; var _this = this; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: if (this.exchangeBusyPromise) { @@ -40390,9 +40390,9 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return __awaiter$3(_this, void 0, void 0, function () { + return __awaiter$2(_this, void 0, void 0, function () { var _appAPIlock; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: _appAPIlock = this._appAPIlock; @@ -40617,7 +40617,7 @@ } } - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40626,7 +40626,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40659,9 +40659,9 @@ }, ]; function requestLedgerDevice() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var device; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.requestDevice({ filters: ledgerDevices @@ -40674,9 +40674,9 @@ }); } function getLedgerDevices() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var devices; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.getDevices()]; case 1: @@ -40687,9 +40687,9 @@ }); } function getFirstLedgerDevice() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var existingDevices; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -40707,7 +40707,7 @@ typeof navigator.usb.getDevices === "function"); }; - var __extends$2 = (undefined && undefined.__extends) || (function () { + var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -40722,7 +40722,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40731,7 +40731,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40768,7 +40768,7 @@ * TransportWebUSB.create().then(transport => ...) */ var TransportWebUSB = /** @class */ (function (_super) { - __extends$2(TransportWebUSB, _super); + __extends(TransportWebUSB, _super); function TransportWebUSB(device, interfaceNumber) { var _this = _super.call(this) || this; _this.channel = Math.floor(Math.random() * 0xffff); @@ -40789,9 +40789,9 @@ * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ TransportWebUSB.request = function () { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var device; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, requestLedgerDevice()]; case 1: @@ -40805,9 +40805,9 @@ * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). */ TransportWebUSB.openConnected = function () { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var devices; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -40823,9 +40823,9 @@ * Create a Ledger transport with a USBDevice */ TransportWebUSB.open = function (device) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var iface, interfaceNumber, e_1, transport, onDisconnect; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, device.open()]; case 1: @@ -40879,8 +40879,8 @@ * Release the transport device */ TransportWebUSB.prototype.close = function () { - return __awaiter$1(this, void 0, void 0, function () { - return __generator$1(this, function (_a) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.exchangeBusyPromise]; case 1: @@ -40905,14 +40905,14 @@ * @returns a promise of apdu response */ TransportWebUSB.prototype.exchange = function (apdu) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var b; var _this = this; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter$1(_this, void 0, void 0, function () { + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return __generator$1(this, function (_b) { + return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, channel = _a.channel, packetSize = _a.packetSize; @@ -41004,9 +41004,9 @@ return TransportWebUSB; }(Transport)); function gracefullyResetDevice(device) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var err_1; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); @@ -41029,1038 +41029,8 @@ 'default': TransportWebUSB }); - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends$1(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isFunction(x) { - return typeof x === 'function'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var _enable_super_gross_mode_that_will_cause_bad_things = false; - var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); - } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function hostReportError(err) { - setTimeout(function () { throw err; }, 0); - } - - /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ - var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - }, - complete: function () { } - }; - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isObject(x) { - return x !== null && typeof x === 'object'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; - } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; - })(); - var UnsubscriptionError = UnsubscriptionErrorImpl; - - /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ - var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._ctorUnsubscribe = true; - this._unsubscribe = unsubscribe; - } - } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; - } - var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (isFunction(_unsubscribe)) { - if (_ctorUnsubscribe) { - this._unsubscribe = undefined; - } - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (isArray(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (isObject(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof UnsubscriptionError) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; - } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; - } - subscription._parentOrParents = [_parentOrParents, this]; - } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); - } - else { - return subscription; - } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; - } - else { - subscriptions.push(subscription); - } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } - } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; - }()); - function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); - })(); - - /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ - var Subscriber = /*@__PURE__*/ (function (_super) { - __extends$1(Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = empty; - break; - case 1: - if (!destinationOrNext) { - _this.destination = empty; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[rxSubscriber] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; - }(Subscription)); - var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __extends$1(SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (isFunction(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== empty) { - context = Object.create(observerOrNext); - if (isFunction(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; - } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - hostReportError(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - hostReportError(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!config.useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - hostReportError(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; - }(Subscriber)); - - /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ - function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; - } - else if (destination && destination instanceof Subscriber) { - observer = destination; - } - else { - observer = null; - } - } - return true; - } - - /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ - function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber) { - return nextOrObserver; - } - if (nextOrObserver[rxSubscriber]) { - return nextOrObserver[rxSubscriber](); - } - } - if (!nextOrObserver && !error && !complete) { - return new Subscriber(empty); - } - return new Subscriber(nextOrObserver, error, complete); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function identity(x) { - return x; - } - - /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ - function pipeFromArray(fns) { - if (fns.length === 0) { - return identity; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; - } - - /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ - var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = toSubscriber(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); - } - else { - sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (config.useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (canReportError(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; - }()); - function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = config.Promise || Promise; - } - if (!promiseCtor) { - throw new Error('no Promise impl found'); - } - return promiseCtor; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; - } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; - })(); - var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - - /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ - var SubjectSubscription = /*@__PURE__*/ (function (_super) { - __extends$1(SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; - } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; - }(Subscription)); - - /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __extends$1(SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; - }(Subscriber)); - var Subject = /*@__PURE__*/ (function (_super) { - __extends$1(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype[rxSubscriber] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - return new SubjectSubscription(this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; - }(Observable)); - var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __extends$1(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return Subscription.EMPTY; - } - }; - return AnonymousSubject; - }(Subject)); - - var net = {}; - - var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Speculos TCP transport implementation - * - * @example - * import SpeculosTransport from "@ledgerhq/hw-transport-node-speculos"; - * const transport = await SpeculosTransport.open({ apduPort }); - * const res = await transport.send(0xE0, 0x01, 0, 0); - */ - var SpeculosTransport = /** @class */ (function (_super) { - __extends(SpeculosTransport, _super); - function SpeculosTransport(apduSocket, opts) { - var _this = _super.call(this) || this; - _this.rejectExchange = function (_e) { }; - _this.resolveExchange = function (_b) { }; - _this.automationEvents = new Subject(); - /** - * Send a speculos button command - * typically "Ll" would press and release the left button - * typically "Rr" would press and release the right button - * @param {*} command - */ - _this.button = function (command) { - return new Promise(function (resolve, reject) { - log("speculos-button", command); - var _a = _this.opts, buttonPort = _a.buttonPort, host = _a.host; - if (!buttonPort) - throw new Error("buttonPort is missing"); - var socket = new net.Socket(); - socket.on("error", function (e) { - socket.destroy(); - reject(e); - }); - socket.connect(buttonPort, host || "127.0.0.1", function () { - socket.write(Buffer$k.from(command, "ascii")); - socket.destroy(); - resolve(); - }); - }); - }; - _this.opts = opts; - _this.apduSocket = apduSocket; - apduSocket.on("error", function (e) { - _this.emit("disconnect", new DisconnectedDevice(e.message)); - _this.rejectExchange(e); - _this.apduSocket.destroy(); - }); - apduSocket.on("end", function () { - _this.emit("disconnect", new DisconnectedDevice()); - _this.rejectExchange(new DisconnectedDeviceDuringOperation()); - }); - apduSocket.on("data", function (data) { - try { - _this.resolveExchange(decodeAPDUPayload(data)); - } - catch (e) { - _this.rejectExchange(e); - } - }); - var automationPort = opts.automationPort; - if (automationPort) { - var socket_1 = new net.Socket(); - _this.automationSocket = socket_1; - socket_1.on("error", function (e) { - log("speculos-automation-error", String(e)); - socket_1.destroy(); - }); - socket_1.on("data", function (data) { - log("speculos-automation-data", data.toString("ascii")); - var split = data.toString("ascii").split("\n"); - split - .filter(function (ascii) { return !!ascii; }) - .forEach(function (ascii) { - var json = JSON.parse(ascii); - _this.automationEvents.next(json); - }); - }); - socket_1.connect(automationPort, opts.host || "127.0.0.1"); - } - return _this; - } - SpeculosTransport.prototype.exchange = function (apdu) { - return __awaiter(this, void 0, void 0, function () { - var hex, encoded, res; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - hex = apdu.toString("hex"); - log("apdu", "=> " + hex); - encoded = encodeAPDU(apdu); - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.rejectExchange = reject; - _this.resolveExchange = resolve; - _this.apduSocket.write(encoded); - })]; - case 1: - res = _a.sent(); - log("apdu", "<= " + res.toString("hex")); - return [2 /*return*/, res]; - } - }); - }); - }; - SpeculosTransport.prototype.setScrambleKey = function () { }; - SpeculosTransport.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (this.automationSocket) - this.automationSocket.destroy(); - this.apduSocket.destroy(); - return [2 /*return*/, Promise.resolve()]; - }); - }); - }; - SpeculosTransport.isSupported = function () { return Promise.resolve(true); }; - // this transport is not discoverable - SpeculosTransport.list = function () { return Promise.resolve([]); }; - SpeculosTransport.listen = function (_observer) { return ({ - unsubscribe: function () { } - }); }; - /** - * - */ - SpeculosTransport.open = function (opts) { - return new Promise(function (resolve, reject) { - var socket = new net.Socket(); - socket.on("error", function (e) { - socket.destroy(); - reject(e); - }); - socket.on("end", function () { - reject(new DisconnectedDevice("tcp closed")); - }); - socket.connect(opts.apduPort, opts.host || "127.0.0.1", function () { - // we delay a bit the transport creation to make sure the tcp does not hang up - setTimeout(function () { - resolve(new SpeculosTransport(socket, opts)); - }, 100); - }); - }); - }; - return SpeculosTransport; - }(Transport)); - function encodeAPDU(apdu) { - var size = Buffer$k.allocUnsafe(4); - size.writeUIntBE(apdu.length, 0, 4); - return Buffer$k.concat([size, apdu]); - } - function decodeAPDUPayload(data) { - var dataLength = data.readUIntBE(0, 4); // 4 bytes tells the data length - var size = dataLength + 2; // size does not include the status code so we add 2 - var payload = data.slice(4); - if (payload.length !== size) { - throw new TransportError("Expected payload of length ".concat(size, " but got ").concat(payload.length), ""); - } - return payload; - } - - var SpeculosTransport$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': SpeculosTransport - }); - exports.Btc = Btc$1; exports.Log = index; - exports.SpeculosTransport = SpeculosTransport$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; @@ -42070,6 +41040,6 @@ window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; -window.TransportSpeculos = NewLedger.SpeculosTransport.default; +//window.TransportSpeculos = NewLedger.SpeculosTransport.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From bf0f31dd51bffe430ab8f098ebd053aca5a7f39a Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 10:54:27 +1100 Subject: [PATCH 63/78] wtf --- js/ledger.js | 10805 +++++++++++++++++++++++++++---------------------- 1 file changed, 6005 insertions(+), 4800 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 6187df29..94409683 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -999,7 +999,7 @@ var toString = {}.toString; - var isArray$3 = Array.isArray || function (arr) { + var isArray$1 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1029,12 +1029,12 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$k.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$l.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength () { - return Buffer$k.TYPED_ARRAY_SUPPORT + return Buffer$l.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1043,14 +1043,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer$k(length); + that = new Buffer$l(length); } that.length = length; } @@ -1068,9 +1068,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer$k (arg, encodingOrOffset, length) { - if (!Buffer$k.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$k)) { - return new Buffer$k(arg, encodingOrOffset, length) + function Buffer$l (arg, encodingOrOffset, length) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$l)) { + return new Buffer$l(arg, encodingOrOffset, length) } // Common case. @@ -1082,18 +1082,18 @@ } return allocUnsafe(this, arg) } - return from(this, arg, encodingOrOffset, length) + return from$1(this, arg, encodingOrOffset, length) } - Buffer$k.poolSize = 8192; // not used by this implementation + Buffer$l.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$k._augment = function (arr) { - arr.__proto__ = Buffer$k.prototype; + Buffer$l._augment = function (arr) { + arr.__proto__ = Buffer$l.prototype; return arr }; - function from (that, value, encodingOrOffset, length) { + function from$1 (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } @@ -1117,13 +1117,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$k.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) + Buffer$l.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) }; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { - Buffer$k.prototype.__proto__ = Uint8Array.prototype; - Buffer$k.__proto__ = Uint8Array; + if (Buffer$l.TYPED_ARRAY_SUPPORT) { + Buffer$l.prototype.__proto__ = Uint8Array.prototype; + Buffer$l.__proto__ = Uint8Array; } function assertSize (size) { @@ -1154,14 +1154,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$k.alloc = function (size, fill, encoding) { + Buffer$l.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) { + if (!Buffer$l.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1172,13 +1172,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$k.allocUnsafe = function (size) { + Buffer$l.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$k.allocUnsafeSlow = function (size) { + Buffer$l.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1187,7 +1187,7 @@ encoding = 'utf8'; } - if (!Buffer$k.isEncoding(encoding)) { + if (!Buffer$l.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1234,10 +1234,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer$k.prototype; + that.__proto__ = Buffer$l.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$3(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1284,12 +1284,12 @@ } return length | 0 } - Buffer$k.isBuffer = isBuffer; + Buffer$l.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer$k.compare = function compare (a, b) { + Buffer$l.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1312,7 +1312,7 @@ return 0 }; - Buffer$k.isEncoding = function isEncoding (encoding) { + Buffer$l.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1331,13 +1331,13 @@ } }; - Buffer$k.concat = function concat (list, length) { - if (!isArray$3(list)) { + Buffer$l.concat = function concat (list, length) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer$k.alloc(0) + return Buffer$l.alloc(0) } var i; @@ -1348,7 +1348,7 @@ } } - var buffer = Buffer$k.allocUnsafe(length); + var buffer = Buffer$l.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1404,7 +1404,7 @@ } } } - Buffer$k.byteLength = byteLength$1; + Buffer$l.byteLength = byteLength$1; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1478,7 +1478,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$k.prototype._isBuffer = true; + Buffer$l.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1486,7 +1486,7 @@ b[m] = i; } - Buffer$k.prototype.swap16 = function swap16 () { + Buffer$l.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1497,7 +1497,7 @@ return this }; - Buffer$k.prototype.swap32 = function swap32 () { + Buffer$l.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1509,7 +1509,7 @@ return this }; - Buffer$k.prototype.swap64 = function swap64 () { + Buffer$l.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1523,20 +1523,20 @@ return this }; - Buffer$k.prototype.toString = function toString () { + Buffer$l.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer$k.prototype.equals = function equals (b) { + Buffer$l.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer$k.compare(this, b) === 0 + return Buffer$l.compare(this, b) === 0 }; - Buffer$k.prototype.inspect = function inspect () { + Buffer$l.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1546,7 +1546,7 @@ return '' }; - Buffer$k.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$l.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -1645,7 +1645,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer$k.from(val, encoding); + val = Buffer$l.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -1657,7 +1657,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$k.TYPED_ARRAY_SUPPORT && + if (Buffer$l.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -1727,15 +1727,15 @@ return -1 } - Buffer$k.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$l.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer$k.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$l.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer$k.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$l.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -1786,7 +1786,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer$k.prototype.write = function write (string, offset, length, encoding) { + Buffer$l.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -1858,7 +1858,7 @@ } }; - Buffer$k.prototype.toJSON = function toJSON () { + Buffer$l.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2011,7 +2011,7 @@ return res } - Buffer$k.prototype.slice = function slice (start, end) { + Buffer$l.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2033,12 +2033,12 @@ if (end < start) end = start; var newBuf; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$k.prototype; + newBuf.__proto__ = Buffer$l.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer$k(sliceLen, undefined); + newBuf = new Buffer$l(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2055,7 +2055,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer$k.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2070,7 +2070,7 @@ return val }; - Buffer$k.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2086,22 +2086,22 @@ return val }; - Buffer$k.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$l.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer$k.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$l.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer$k.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$l.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer$k.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$l.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2110,7 +2110,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer$k.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$l.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2119,7 +2119,7 @@ this[offset + 3]) }; - Buffer$k.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2137,7 +2137,7 @@ return val }; - Buffer$k.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$l.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2155,25 +2155,25 @@ return val }; - Buffer$k.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$l.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer$k.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$l.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$l.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer$k.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$l.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2182,7 +2182,7 @@ (this[offset + 3] << 24) }; - Buffer$k.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$l.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2191,22 +2191,22 @@ (this[offset + 3]) }; - Buffer$k.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$l.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; - Buffer$k.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$l.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; - Buffer$k.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$l.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; - Buffer$k.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$l.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; @@ -2217,7 +2217,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer$k.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2236,7 +2236,7 @@ return offset + byteLength }; - Buffer$k.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2255,11 +2255,11 @@ return offset + byteLength }; - Buffer$k.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2272,11 +2272,11 @@ } } - Buffer$k.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2285,11 +2285,11 @@ return offset + 2 }; - Buffer$k.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2305,11 +2305,11 @@ } } - Buffer$k.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2320,11 +2320,11 @@ return offset + 4 }; - Buffer$k.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$l.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2335,7 +2335,7 @@ return offset + 4 }; - Buffer$k.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2358,7 +2358,7 @@ return offset + byteLength }; - Buffer$k.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$l.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2381,21 +2381,21 @@ return offset + byteLength }; - Buffer$k.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$l.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$k.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$l.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer$k.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2404,11 +2404,11 @@ return offset + 2 }; - Buffer$k.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$l.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2417,11 +2417,11 @@ return offset + 2 }; - Buffer$k.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$l.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2432,12 +2432,12 @@ return offset + 4 }; - Buffer$k.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$l.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; - if (Buffer$k.TYPED_ARRAY_SUPPORT) { + if (Buffer$l.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2461,11 +2461,11 @@ return offset + 4 } - Buffer$k.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$l.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2477,16 +2477,16 @@ return offset + 8 } - Buffer$k.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer$k.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$l.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$k.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$l.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2518,7 +2518,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer$k.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$l.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2538,7 +2538,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$k.prototype.fill = function fill (val, start, end, encoding) { + Buffer$l.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2558,7 +2558,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer$k.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$l.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -2587,7 +2587,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer$k(val, encoding).toString()); + : utf8ToBytes(new Buffer$l(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -5021,6 +5021,8 @@ }; }(safeBuffer, safeBuffer.exports)); + var readableBrowser = {exports: {}}; + // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5156,23 +5158,23 @@ }; var title = 'browser'; var platform = 'browser'; - var browser$5 = true; + var browser$6 = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config = {}; + var config$1 = {}; - function noop() {} + function noop$2() {} - var on = noop; - var addListener = noop; - var once$1 = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; + var on = noop$2; + var addListener = noop$2; + var once$3 = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; function binding(name) { throw new Error('process.binding is not supported'); @@ -5220,14 +5222,14 @@ var process = { nextTick: nextTick, title: title, - browser: browser$5, + browser: browser$6, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, - once: once$1, + once: once$3, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, @@ -5239,12 +5241,10 @@ hrtime: hrtime, platform: platform, release: release, - config: config, + config: config$1, uptime: uptime }; - var readable = {exports: {}}; - var events = {exports: {}}; var R = typeof Reflect === 'object' ? Reflect : null; @@ -5280,7 +5280,7 @@ EventEmitter.init.call(this); } events.exports = EventEmitter; - events.exports.once = once; + events.exports.once = once$2; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; @@ -5672,7 +5672,7 @@ return ret; } - function once(emitter, name) { + function once$2(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); @@ -5723,5490 +5723,6696 @@ var EventEmitter$1 = events.exports; - var inherits$h; - if (typeof Object.create === 'function'){ - inherits$h = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits$h = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + var streamBrowser = events.exports.EventEmitter; + + var _nodeResolve_empty = {}; + + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); + + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + + 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else 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; } + + function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + + var _require$2 = buffer, + Buffer$k = _require$2.Buffer; + + var _require2 = require$$3, + inspect$1 = _require2.inspect; + + var custom = inspect$1 && inspect$1.custom || 'inspect'; + + function copyBuffer(src, target, offset) { + Buffer$k.prototype.copy.call(src, target, offset); } - var inherits$i = inherits$h; - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString$1(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); + var buffer_list = + /*#__PURE__*/ + function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; } - 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]'; + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + + while (p = p.next) { + ret += s + p.data; + } + + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer$k.alloc(0); + var ret = Buffer$k.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull$1(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer$k.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect$1(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); } - } - 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. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined$1(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } + return BufferList; + }(); - var warned = false; - function deprecated() { - if (!warned) { - { - console.error(msg); + function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + nextTick(emitErrorNT, this, err); } - warned = true; } - return fn.apply(this, arguments); - } - return deprecated; - } + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined$1(debugEnviron)) - debugEnviron = ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + nextTick(emitErrorAndCloseNT, _this, err); + } else { + nextTick(emitCloseNT, _this); + } + } else if (cb) { + nextTick(emitCloseNT, _this); + cb(err); } else { - debugs[set] = function() {}; + nextTick(emitCloseNT, _this); } - } - 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$1(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined$1(ctx.depth)) ctx.depth = 2; - if (isUndefined$1(ctx.colors)) ctx.colors = false; - if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); + return this; } - // 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 emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); + } - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + 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(self, err) { + self.emit('error', err); + } - function stylizeNoColor(str, styleType) { - return str; + function errorOrDestroy$2(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } + var destroy_1 = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy$2 + }; - function arrayToHash(array) { - var hash = {}; + var errorsBrowser = {}; - array.forEach(function(val, idx) { - hash[val] = true; - }); + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - return hash; - } + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } - 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$1(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== 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$1(ret)) { - ret = formatValue(ctx, ret, recurseTimes); + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); } - return ret; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + return NodeError; + }(Base); - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError$1(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction$1(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate$1(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError$1(value)) { - return formatError(value); + + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); } + } else { + return "of ".concat(thing, " ").concat(String(expected)); } + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - var base = '', array = false, braces = ['{', '}']; - // Make Array say that they are Array - if (isArray$2(value)) { - array = true; - braces = ['[', ']']; - } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - // Make functions say that they are functions - if (isFunction$1(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - // Make RegExps say that they are RegExps - if (isRegExp$1(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; } - // Make dates with properties first say the date - if (isDate$1(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + return str.substring(this_len - search.length, this_len) === search; + } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - // Make error with message first say the error - if (isError$1(value)) { - base = ' ' + formatError(value); + + function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; } + } - if (recurseTimes < 0) { - if (isRegExp$1(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } + createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; } - ctx.seen.push(value); + var msg; - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } - ctx.seen.pop(); + msg += ". Received type ".concat(typeof actual); + return msg; + }, TypeError); + createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); + createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; + }); + createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); + createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' 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 (arg) { + return 'Unknown encoding: ' + arg; + }, TypeError); + createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + errorsBrowser.codes = codes; - return reduceToSingleString(output, base, braces); + var ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE; + + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } + function getHighWaterMark$2(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - function formatPrimitive(ctx, value) { - if (isUndefined$1(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber$1(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean$1(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull$1(value)) - return ctx.stylize('null', 'null'); - } + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } // Default value - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + + return state.objectMode ? 16 : 16 * 1024; } + var state = { + getHighWaterMark: getHighWaterMark$2 + }; - 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; - } + /** + * Module exports. + */ + var browser$5 = deprecate$1; - 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 + ']'; + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + + function deprecate$1 (fn, msg) { + if (config('noDeprecation')) { + return fn; } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull$1(recurseTimes)) { - str = formatValue(ctx, desc.value, null); + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); } 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'); - } + console.warn(msg); } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined$1(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'); + warned = true; } + return fn.apply(this, arguments); } - return name + ': ' + str; + return deprecated; } + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - 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]; + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } + var _stream_writable = Writable$2; + // there will be only 2 of these for each stream - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$2(ar) { - return Array.isArray(ar); - } - function isBoolean$1(arg) { - return typeof arg === 'boolean'; - } + function CorkedRequest$1(state) { + var _this = this; - function isNull$1(arg) { - return arg === null; - } + this.next = null; + this.entry = null; - function isNumber$1(arg) { - return typeof arg === 'number'; + this.finish = function () { + onCorkedFinish(_this, state); + }; } + /* */ - function isString$1(arg) { - return typeof arg === 'string'; - } + /**/ - function isUndefined$1(arg) { - return arg === void 0; - } - function isRegExp$1(re) { - return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; - } + var Duplex$4; + /**/ - function isObject$1(arg) { - return typeof arg === 'object' && arg !== null; - } + Writable$2.WritableState = WritableState$1; + /**/ - function isDate$1(d) { - return isObject$1(d) && objectToString$1(d) === '[object Date]'; - } + var internalUtil = { + deprecate: browser$5 + }; + /**/ - function isError$1(e) { - return isObject$1(e) && - (objectToString$1(e) === '[object Error]' || e instanceof Error); - } + /**/ - function isFunction$1(arg) { - return typeof arg === 'function'; - } + var Stream$2 = streamBrowser; + /**/ - function objectToString$1(o) { - return Object.prototype.toString.call(o); - } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; + var Buffer$j = buffer.Buffer; - 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 OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$j.from(chunk); } - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; + function _isUint8Array$1(obj) { + return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; } - BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + var destroyImpl$1 = destroy_1; - BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + inherits_browser.exports(Writable$2, Stream$2); - BufferList.prototype.concat = function (n) { - if (this.length === 0) return buffer.Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = buffer.Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; + function nop$1() {} - var string_decoder = {}; + function WritableState$1(options, stream, isDuplex) { + Duplex$4 = Duplex$4 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - var StringDecoder_1; - // 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. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - var Buffer$j = buffer.Buffer; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - var isBufferEncoding = Buffer$j.isEncoding - || function(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; - } - }; + this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + this.finalCalled = false; // drain event flag. - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } + this.needDrain = false; // at the start of calling end() - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder$2 = StringDecoder_1 = string_decoder.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + this.ending = false; // when end() has been called, and returned - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$j(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; + this.ended = false; // when 'finish' is emitted + this.finished = false; // has it been destroyed - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder$2.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + this.length = 0; // a flag to see when we're in the middle of a write. - charStr += buffer.toString(this.encoding, 0, end); + this.writing = false; // when true all writes will be buffered until .uncork() call - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - // or just emit the charStr - return charStr; - }; + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder$2.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - // See http://en.wikipedia.org/wiki/UTF-8#Description - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + this.writecb = null; // the amount that is being written when _write is called. - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - StringDecoder$2.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + this.prefinished = false; // True if the error was already emitted and should not be thrown again - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - return res; - }; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } + this.autoDestroy = !!options.autoDestroy; // count buffered requests - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; + this.corkedRequestsFree = new CorkedRequest$1(this); } - Readable$2.ReadableState = ReadableState$1; - - var debug$4 = debuglog('stream'); - inherits$i(Readable$2, EventEmitter$1); + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) - emitter.on(event, fn); - else if (Array.isArray(emitter._events[event])) - emitter._events[event].unshift(fn); - else - emitter._events[event] = [fn, emitter._events[event]]; + while (current) { + out.push(current); + current = current.next; } - } - function listenerCount (emitter, type) { - return emitter.listeners(type).length; - } - function ReadableState$1(options, stream) { - options = options || {}; + return out; + }; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + (function () { + try { + Object.defineProperty(WritableState$1.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.readableObjectMode; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + var realHasInstance; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$2, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$2) return false; + return object && object._writableState instanceof WritableState$1; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; + } - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + function Writable$2(options) { + Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex$4; + if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); + this._writableState = new WritableState$1(options, this, isDuplex); // legacy. - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + this.writable = true; - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + Stream$2.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + Writable$2.prototype.pipe = function () { + errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); + }; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - this.decoder = null; - this.encoding = null; - if (options.encoding) { - this.decoder = new StringDecoder_1(options.encoding); - this.encoding = options.encoding; - } - } - function Readable$2(options) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. - if (!(this instanceof Readable$2)) return new Readable$2(options); - this._readableState = new ReadableState$1(options, this); + function validChunk$1(stream, state, chunk, cb) { + var er; - // legacy - this.readable = true; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); + } - if (options && typeof options.read === 'function') this._read = options.read; + if (er) { + errorOrDestroy$1(stream, er); + nextTick(cb, er); + return false; + } - EventEmitter$1.call(this); + return true; } - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$2.prototype.push = function (chunk, encoding) { - var state = this._readableState; + Writable$2.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer$k.from(chunk, encoding); - encoding = ''; - } + var isBuf = !state.objectMode && _isUint8Array$1(chunk); + + if (isBuf && !Buffer$j.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return readableAddChunk$1(this, state, chunk, encoding, false); + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop$1; + if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); + } + return ret; }; - // Unshift should *always* be something directly out of read() - Readable$2.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk$1(this, state, chunk, '', true); + Writable$2.prototype.cork = function () { + this._writableState.corked++; }; - Readable$2.prototype.isPaused = function () { - return this._readableState.flowing === false; + Writable$2.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } }; - function readableAddChunk$1(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid$1(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } + Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - if (!addToFront) state.reading = false; + Object.defineProperty(Writable$2.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$j.from(chunk, encoding); + } - if (state.needReadable) emitReadable$1(stream); - } - } + return chunk; + } - maybeReadMore$1(stream, state); + Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + + function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk$1(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - } else if (!addToFront) { - state.reading = false; } - return needMoreData$1(state); + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); + } + + return ret; } - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData$1(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - // backwards compatibility. - Readable$2.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder_1(enc); - this._readableState.encoding = enc; - return this; - }; + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; - // Don't raise the hwm > 8MB - var MAX_HWM$1 = 0x800000; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM$1) { - n = MAX_HWM$1; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + nextTick(finishMaybe$1, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy$1(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe$1(stream, state); } - return n; } - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - // you can override either this method, or the async _read(n) below. - Readable$2.prototype.read = function (n) { - debug$4('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate$1(state); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state) || stream.destroyed; - if (n !== 0) state.emittedReadable = false; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug$4('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; + if (sync) { + nextTick(afterWrite$1, stream, state, finished, cb); + } else { + afterWrite$1(stream, state, finished, cb); + } } + } + + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. - n = howMuchToRead$1(n, state); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } + } // if there's something in the buffer waiting, then process it - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug$4('need readable', doRead); + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$4('length less than watermark', doRead); - } + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug$4('reading or ended', doRead); - } else if (doRead) { - debug$4('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead$1(nOrig, state); - } + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + buffer.allBuffers = allBuffers; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - if (ret === null) { - state.needReadable = true; - n = 0; + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } + + state.bufferedRequestCount = 0; } else { - state.length -= n; - } + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + if (state.writing) { + break; + } + } - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable$1(this); + if (entry === null) state.lastBufferedRequest = null; } - if (ret !== null) this.emit('data', ret); + state.bufferedRequest = entry; + state.bufferProcessing = false; + } - return ret; + Writable$2.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); }; - function chunkInvalid$1(state, chunk) { - var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); + Writable$2.prototype._writev = null; + + Writable$2.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return er; + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable$1(this, state, cb); + return this; + }; + + Object.defineProperty(Writable$2.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - function onEofChunk$1(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy$1(stream, err); } - } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable$1(stream); + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable$1(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug$4('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick(emitReadable_$1, stream);else emitReadable_$1(stream); + function prefinish$2(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } } - function emitReadable_$1(stream) { - debug$4('emit readable'); - stream.emit('readable'); - flow$1(stream); - } + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); + if (need) { + prefinish$2(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } } + + return need; } - function maybeReadMore_$1(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug$4('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); + + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } - state.readingMore = false; - } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$2.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; + state.ended = true; + stream.writable = false; + } - Readable$2.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - var doEnd = (!pipeOpts || pipeOpts.end !== false); - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + state.corkedRequestsFree.next = corkReq; + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug$4('onunpipe'); - if (readable === src) { - cleanup(); + Object.defineProperty(Writable$2.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; } - } - function onend() { - debug$4('onend'); - dest.end(); + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; } + }); + Writable$2.prototype.destroy = destroyImpl$1.destroy; + Writable$2.prototype._undestroy = destroyImpl$1.undestroy; - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); + Writable$2.prototype._destroy = function (err, cb) { + cb(err); + }; - var cleanedUp = false; - function cleanup() { - debug$4('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + /**/ - cleanedUp = true; + var objectKeys = Object.keys || function (obj) { + var keys = []; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + for (var key in obj) { + keys.push(key); } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug$4('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$4('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + return keys; + }; + /**/ - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug$4('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount(dest, 'error') === 0) dest.emit('error', er); - } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); + var _stream_duplex = Duplex$3; - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug$4('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + var Readable$2 = _stream_readable; - function unpipe() { - debug$4('unpipe'); - src.unpipe(dest); - } + var Writable$1 = _stream_writable; - // tell the dest that it's being piped to - dest.emit('pipe', src); + inherits_browser.exports(Duplex$3, Readable$2); - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug$4('pipe resume'); - src.resume(); + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Writable$1.prototype); + + for (var v$1 = 0; v$1 < keys$1.length; v$1++) { + var method$1 = keys$1[v$1]; + if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; } + } - return dest; - }; + function Duplex$3(options) { + if (!(this instanceof Duplex$3)) return new Duplex$3(options); + Readable$2.call(this, options); + Writable$1.call(this, options); + this.allowHalfOpen = true; - function pipeOnDrain$1(src) { - return function () { - var state = src._readableState; - debug$4('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow$1(src); + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend$1); } - }; + } } - Readable$2.prototype.unpipe = function (dest) { - var state = this._readableState; + Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex$3.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); // the no-half-open enforcer - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + function onend$1() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + nextTick(onEndNT$1, this); + } - if (!dest) dest = state.pipes; + function onEndNT$1(self) { + self.end(); + } - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; + Object.defineProperty(Duplex$3.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; } + }); - // slow case. multiple pipe destinations. + var string_decoder = {}; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + /**/ - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - }return this; + var Buffer$i = safeBuffer.exports.Buffer; + /**/ + + var isEncoding = Buffer$i.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; } + }; - // try to find the right one. - var i = indexOf$1(state.pipes, dest); - if (i === -1) return this; + 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$i.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$i.allocUnsafe(nb); + } - dest.emit('unpipe', this); + StringDecoder$2.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 || ''; + }; - return this; + StringDecoder$2.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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; }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$2.prototype.on = function (ev, fn) { - var res = EventEmitter$1.prototype.on.call(this, ev, fn); + // 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; + } - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable$1(this); + // 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'; } } } + } - return res; - }; - Readable$2.prototype.addListener = Readable$2.prototype.on; + // 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); + 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; + } - function nReadingNextTick(self) { - debug$4('readable nexttick read 0'); - self.read(0); + // 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); } - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$2.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug$4('resume'); - state.flowing = true; - resume(this, state); + // 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; } - return this; - }; + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_, stream, state); + // 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 resume_(stream, state) { - if (!state.reading) { - debug$4('resume read 0'); - stream.read(0); + 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); + } - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); + 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; } - Readable$2.prototype.pause = function () { - debug$4('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug$4('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; - }; + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } - function flow$1(stream) { - var state = stream._readableState; - debug$4('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$2.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - var self = this; - stream.on('end', function () { - debug$4('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - self.push(null); - }); + callback.apply(this, args); + }; + } - stream.on('data', function (chunk) { - debug$4('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + function noop$1() {} - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$2(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + var writableEnded = stream._writableState && stream._writableState.finished; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug$4('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); }; - return self; - }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // exposed for testing purposes only. - Readable$2._fromList = fromList$1; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; + var onerror = function onerror(err) { + callback.call(stream, err); + }; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - return ret; + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; } - // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; + var endOfStream = eos$1; + + var _Object$setPrototypeO; + + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + + var finished = endOfStream; + + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; } - // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } - ++c; } - list.length -= c; - return ret; } - // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - function copyFromBuffer(n, list) { - var ret = Buffer$k.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } + + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; } - break; - } - ++c; - } - list.length -= c; - return ret; + + iter[kHandlePromise](resolve, reject); + }, reject); + }; } - function endReadable$1(stream) { - var state = stream._readableState; + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + next: function next() { + var _this = this; - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT, state, stream); - } - } + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } + if (error !== null) { + return Promise.reject(error); + } - function forEach$2(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; - } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - // A bit simpler than readable streams. - Writable$2.WritableState = WritableState$1; - inherits$i(Writable$2, events.exports.EventEmitter); - function nop() {} + var lastPromise = this[kLastPromise]; + var promise; - function WriteReq$1(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); - function WritableState$1(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); }); - options = options || {}; + }), _Object$setPrototypeO), AsyncIteratorPrototype); + + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var resolve = iterator[kLastResolve]; - if (stream instanceof Duplex$2) this.objectMode = this.objectMode || !!options.writableObjectMode; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; + }; - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + var async_iterator = createReadableStreamAsyncIterator$1; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') + }; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + var _stream_readable = Readable$1; + /**/ - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + var Duplex$2; + /**/ - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + Readable$1.ReadableState = ReadableState$1; + /**/ - // a flag to see when we're in the middle of a write. - this.writing = false; + events.exports.EventEmitter; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + /**/ - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite$1(stream, er); - }; + var Stream$1 = streamBrowser; + /**/ - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - // the amount that is being written when _write is called. - this.writelen = 0; + var Buffer$h = buffer.Buffer; - this.bufferedRequest = null; - this.lastBufferedRequest = null; + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); + } - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + } + /**/ - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - // count buffered requests - this.bufferedRequestCount = 0; + var debugUtil = require$$3; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + var debug$5; + + if (debugUtil && debugUtil.debuglog) { + debug$5 = debugUtil.debuglog('stream'); + } else { + debug$5 = function debug() {}; } + /**/ - WritableState$1.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - function Writable$2(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable$2) && !(this instanceof Duplex$2)) return new Writable$2(options); + var BufferList$1 = buffer_list; - this._writableState = new WritableState$1(options, this); + var destroyImpl = destroy_1; - // legacy. - this.writable = true; + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - if (typeof options.writev === 'function') this._writev = options.writev; - } - events.exports.EventEmitter.call(this); - } + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable$2.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; + inherits_browser.exports(Readable$1, Stream$1); - function writeAfterEnd$1(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(cb, er); - } + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk$1(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - nextTick(cb, er); - valid = false; - } - return valid; + function prependListener$1(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + function ReadableState$1(options, stream, isDuplex) { + Duplex$2 = Duplex$2 || _stream_duplex; + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" - if (typeof cb !== 'function') cb = nop; + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - if (state.ended) writeAfterEnd$1(this, cb);else if (validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, chunk, encoding, cb); - } + this.buffer = new BufferList$1(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - return ret; - }; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - Writable$2.prototype.cork = function () { - var state = this._writableState; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - state.corked++; - }; + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - Writable$2.prototype.uncork = function () { - var state = this._writableState; + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - if (state.corked) { - state.corked--; + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } - }; + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = buffer.Buffer.from(chunk, encoding); + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; } - return chunk; } - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer$1(stream, state, chunk, encoding, cb) { - chunk = decodeChunk$1(state, chunk, encoding); - - if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + function Readable$1(options) { + Duplex$2 = Duplex$2 || _stream_duplex; + if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - state.length += len; + var isDuplex = this instanceof Duplex$2; + this._readableState = new ReadableState$1(options, this, isDuplex); // legacy - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + this.readable = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq$1(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - return ret; + Stream$1.call(this); } - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + Object.defineProperty(Readable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick(cb, er);else cb(er); + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + this._readableState.destroyed = value; + } + }); + Readable$1.prototype.destroy = destroyImpl.destroy; + Readable$1.prototype._undestroy = destroyImpl.undestroy; - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + Readable$1.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state); + Readable$1.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; - if (sync) { - /**/ - nextTick(afterWrite$1, stream, state, finished, cb); - /**/ - } else { - afterWrite$1(stream, state, finished, cb); + if (encoding !== state.encoding) { + chunk = Buffer$h.from(chunk, encoding); + encoding = ''; } - } - } - - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; } - } - // if there's something in the buffer waiting, then process it - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); + }; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$5('readableAddChunk', chunk); + var state = stream._readableState; - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + var er; + if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); + } else { + addChunk(stream, state, chunk, false); + } } + } else if (!addToFront) { + state.reading = false; + maybeReadMore$1(stream, state); } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - if (entry === null) state.lastBufferedRequest = null; + + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable$1(stream); } - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; + maybeReadMore$1(stream, state); } - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + function chunkInvalid$1(state, chunk) { + var er; - Writable$2.prototype._writev = null; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + return er; + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable$1(this, state, cb); - }; + Readable$1.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } + var p = this._readableState.buffer.head; + var content = ''; - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } + while (p !== null) { + content += decoder.write(p.data); + p = p.next; } - return need; - } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; - } + this._readableState.buffer.clear(); - // It seems a linked list but it is not - // there will be only 2 of these for each stream - function CorkedRequest(state) { - var _this = this; + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } + var MAX_HWM$1 = 0x40000000; - inherits$i(Duplex$2, Readable$2); + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } - var keys = Object.keys(Writable$2.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex$2.prototype[method]) Duplex$2.prototype[method] = Writable$2.prototype[method]; - } - function Duplex$2(options) { - if (!(this instanceof Duplex$2)) return new Duplex$2(options); + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - Readable$2.call(this, options); - Writable$2.call(this, options); - if (options && options.readable === false) this.readable = false; + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - if (options && options.writable === false) this.writable = false; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend$1); - } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); + if (n <= state.length) return n; // Don't have enough - // the no-half-open enforcer - function onend$1() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + if (!state.ended) { + state.needReadable = true; + return 0; + } - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(onEndNT, this); - } + return state.length; + } // you can override either this method, or the async _read(n) below. - function onEndNT(self) { - self.end(); - } - // a transform stream is a readable/writable stream where you do - inherits$i(Transform$4, Duplex$2); + Readable$1.prototype.read = function (n) { + debug$5('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - function TransformState$1(stream) { - this.afterTransform = function (er, data) { - return afterTransform$1(stream, er, data); - }; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$5('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - function afterTransform$1(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + var doRead = state.needReadable; + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - ts.writechunk = null; - ts.writecb = null; + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$5('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - if (data !== null && data !== undefined) stream.push(data); - cb(er); + if (state.ended || state.reading) { + doRead = false; + debug$5('reading or ended', doRead); + } else if (doRead) { + debug$5('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform$4(options) { - if (!(this instanceof Transform$4)) return new Transform$4(options); + if (state.length === 0) state.needReadable = true; // call internal read method - Duplex$2.call(this, options); + this._read(state.highWaterMark); - this._transformState = new TransformState$1(this); + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - // when the writable side finishes, then flush out anything remaining. - var stream = this; + if (!state.reading) n = howMuchToRead$1(nOrig, state); + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - if (typeof options.flush === 'function') this._flush = options.flush; + if (nOrig !== n && state.ended) endReadable$1(this); } - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done$1(stream, er); - });else done$1(stream); - }); - } - - Transform$4.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex$2.prototype.push.call(this, chunk, encoding); + if (ret !== null) this.emit('data', ret); + return ret; }; - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$4.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; + function onEofChunk$1(stream, state) { + debug$5('onEofChunk'); + if (state.ended) return; - Transform$4.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + if (state.decoder) { + var chunk = state.decoder.end(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } - }; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$4.prototype._read = function (n) { - var ts = this._transformState; + state.ended = true; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable$1(stream); } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_$1(stream); + } } - }; + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. - function done$1(stream, er) { - if (er) return stream.emit('error', er); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + function emitReadable$1(stream) { + var state = stream._readableState; + debug$5('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (!state.emittedReadable) { + debug$5('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); + } + } - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + function emitReadable_$1(stream) { + var state = stream._readableState; + debug$5('emitReadable_', state.destroyed, state.length, state.ended); - return stream.push(null); - } + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - inherits$i(PassThrough$1, Transform$4); - function PassThrough$1(options) { - if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$4.call(this, options); + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow$1(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + + + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } } - PassThrough$1.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); + function maybeReadMore_$1(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$5('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; + } + + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + + + Readable$1.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); }; - inherits$i(Stream$2, EventEmitter$1); - Stream$2.Readable = Readable$2; - Stream$2.Writable = Writable$2; - Stream$2.Duplex = Duplex$2; - Stream$2.Transform = Transform$4; - Stream$2.PassThrough = PassThrough$1; + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - // Backwards-compat with node 0.4.x - Stream$2.Stream = Stream$2; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + case 1: + state.pipes = [state.pipes, dest]; + break; - function Stream$2() { - EventEmitter$1.call(this); - } + default: + state.pipes.push(dest); + break; + } - Stream$2.prototype.pipe = function(dest, options) { - var source = this; + state.pipesCount += 1; + debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); + function onunpipe(readable, unpipeInfo) { + debug$5('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); } } } - source.on('data', ondata); + function onend() { + debug$5('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } + var ondrain = pipeOnDrain$1(src); dest.on('drain', ondrain); + var cleanedUp = false; - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } + function cleanup() { + debug$5('cleanup'); // cleanup event handlers once the pipe is broken - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - dest.end(); + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } + src.on('data', ondata); - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + function ondata(chunk) { + debug$5('ondata'); + var ret = dest.write(chunk); + debug$5('dest.write', ret); - if (typeof dest.destroy === 'function') dest.destroy(); - } + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$5('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EventEmitter$1.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + src.pause(); } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - source.removeListener('end', onend); - source.removeListener('close', onclose); - source.removeListener('error', onerror); + function onerror(er) { + debug$5('onerror', er); + unpipe(); dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - dest.removeListener('close', cleanup); + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - source.on('end', cleanup); - source.on('close', cleanup); + dest.once('close', onclose); - dest.on('close', cleanup); + function onfinish() { + debug$5('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } - dest.emit('pipe', source); + dest.once('finish', onfinish); - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; + function unpipe() { + debug$5('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - var stream = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': Stream$2, - Readable: Readable$2, - Writable: Writable$2, - Duplex: Duplex$2, - Transform: Transform$4, - PassThrough: PassThrough$1, - Stream: Stream$2 - }); - var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug$5('pipe resume'); + src.resume(); + } - var isarray = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; + return dest; }; - var util$5 = {}; + function pipeOnDrain$1(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$5('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; - // 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. + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow$1(src); + } + }; + } - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - function isArray$1(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; - } - util$5.isArray = isArray$1; + if (state.pipesCount === 0) return this; // just one destination. most common case. - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - util$5.isBoolean = isBoolean; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - function isNull(arg) { - return arg === null; - } - util$5.isNull = isNull; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - function isNullOrUndefined(arg) { - return arg == null; - } - util$5.isNullOrUndefined = isNullOrUndefined; - function isNumber(arg) { - return typeof arg === 'number'; - } - util$5.isNumber = isNumber; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - function isString(arg) { - return typeof arg === 'string'; - } - util$5.isString = isString; + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - util$5.isSymbol = isSymbol; + return this; + } // try to find the right one. - function isUndefined(arg) { - return arg === void 0; - } - util$5.isUndefined = isUndefined; - function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; - } - util$5.isRegExp = isRegExp; + var index = indexOf$1(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - util$5.isObject = isObject; - function isDate(d) { - return objectToString(d) === '[object Date]'; - } - util$5.isDate = isDate; + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$1.prototype.on.call(this, ev, fn); + var state = this._readableState; - function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); - } - util$5.isError = isError; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - function isFunction(arg) { - return typeof arg === 'function'; - } - util$5.isFunction = isFunction; + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$5('on readable', state.length, state.reading); - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - util$5.isPrimitive = isPrimitive; + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } + } - util$5.isBuffer = buffer.Buffer.isBuffer; + return res; + }; - function objectToString(o) { - return Object.prototype.toString.call(o); - } + Readable$1.prototype.addListener = Readable$1.prototype.on; - // 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. + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$1.prototype.removeListener.call(this, ev, fn); - var _stream_readable = Readable$1; + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - /**/ - var isArray = isarray; - /**/ + return res; + }; + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); - /**/ - var Buffer$i = buffer.Buffer; - /**/ + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - Readable$1.ReadableState = ReadableState; + return res; + }; - var EE = events.exports.EventEmitter; + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - /**/ - if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } + } - var Stream$1 = require$$1; + function nReadingNextTick$1(self) { + debug$5('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. - /**/ - var util$4 = util$5; - util$4.inherits = inherits_browser.exports; - /**/ - var StringDecoder$1; + Readable$1.prototype.resume = function () { + var state = this._readableState; - util$4.inherits(Readable$1, Stream$1); + if (!state.flowing) { + debug$5('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - function ReadableState(options, stream) { - options = options || {}; + state.flowing = !state.readableListening; + resume$1(this, state); + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + state.paused = false; + return this; + }; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); + } + } - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; + function resume_$1(stream, state) { + debug$5('resume', state.reading); - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; + if (!state.reading) { + stream.read(0); + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; + Readable$1.prototype.pause = function () { + debug$5('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug$5('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + this._readableState.paused = true; + return this; + }; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function flow$1(stream) { + var state = stream._readableState; + debug$5('flow', state.flowing); - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + Readable$1.prototype.wrap = function (stream) { + var _this = this; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$5('wrapped end'); - function Readable$1(options) { - if (!(this instanceof Readable$1)) - return new Readable$1(options); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - this._readableState = new ReadableState(options, this); + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$5('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - // legacy - this.readable = true; + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - Stream$1.call(this); - } + var ret = _this.push(chunk); - // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - Readable$1.prototype.push = function(chunk, encoding) { - var state = this._readableState; + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer$i(chunk, encoding); - encoding = ''; + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); } - } + } // proxy certain important events. - return readableAddChunk(this, state, chunk, encoding, false); - }; - // Unshift should *always* be something directly out of read() - Readable$1.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } + this._read = function (n) { + debug$5('wrapped _read', n); + + if (paused) { + paused = false; + stream.resume(); + } + }; - if (state.needReadable) - emitReadable(stream); + return this; + }; - maybeReadMore(stream, state); + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; } - } else if (!addToFront) { - state.reading = false; - } - return needMoreData(state); + return createReadableStreamAsyncIterator(this); + }; } + Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + Readable$1._fromList = fromList$1; + Object.defineProperty(Readable$1.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. - // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; } - // backwards compatibility. - Readable$1.prototype.setEncoding = function(enc) { - if (!StringDecoder$1) - StringDecoder$1 = string_decoder.StringDecoder; - this._readableState.decoder = new StringDecoder$1(enc); - this._readableState.encoding = enc; - }; + function endReadable$1(stream) { + var state = stream._readableState; + debug$5('endReadable', state.endEmitted); - // Don't raise the hwm > 128MB - var MAX_HWM = 0x800000; - function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); } - return n; } - function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; + function endReadableNT$1(state, stream) { + debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. + + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); - if (state.objectMode) - return n === 0 ? 0 : 1; + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } } + } - if (n <= 0) - return 0; + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); + return from(Readable$1, iterable, opts); + }; + } - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - return n; + return -1; } - // you can override either this method, or the async _read(n) below. - Readable$1.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; + var _stream_transform = Transform$4; - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; + var _require$codes$1 = errorsBrowser.codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes$1.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } + var Duplex$1 = _stream_duplex; - n = howMuchToRead(n, state); + inherits_browser.exports(Transform$4, Duplex$1); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } + function afterTransform$1(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - if (state.length === 0) - endReadable(this); + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } - return ret; + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } + } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + function Transform$4(options) { + if (!(this instanceof Transform$4)) return new Transform$4(options); + Duplex$1.call(this, options); + this._transformState = { + afterTransform: afterTransform$1.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; + this._readableState.sync = false; - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; + this.on('prefinish', prefinish$1); + } + + function prefinish$1() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done$1(_this, er, data); + }); + } else { + done$1(this, null, null); } + } + + Transform$4.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$1.prototype.push.call(this, chunk, encoding); + }; // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - if (n > 0) - ret = fromList(n, state); - else - ret = null; + Transform$4.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); + }; - if (ret === null) { - state.needReadable = true; - n = 0; + Transform$4.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } + }; // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. - state.length -= n; - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; + Transform$4.prototype._read = function (n) { + var ts = this._transformState; - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; - return ret; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } }; - function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer$i.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; + Transform$4.prototype._destroy = function (err, cb) { + Duplex$1.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); + }; + + function done$1(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); } + var _stream_passthrough = PassThrough$1; - function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; + var Transform$3 = _stream_transform; - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); + inherits_browser.exports(PassThrough$1, Transform$3); + + function PassThrough$1(options) { + if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); + Transform$3.call(this, options); } - // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; + PassThrough$1.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - state.emittedReadable = true; - if (state.sync) - nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } + var eos; - function emitReadable_(stream) { - stream.emit('readable'); + function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; } + var _require$codes = errorsBrowser.codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(function() { - maybeReadMore_(stream, state); - }); - } + function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; } - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } - // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - Readable$1.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); - }; + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = endOfStream; + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want - Readable$1.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; + } - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; + function call(fn) { + fn(); + } - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + function pipe(from, to) { + return from.pipe(to); + } - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - nextTick(endFn); - else - src.once('end', endFn); + function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); + } - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; } - function onend() { - dest.end(); + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); + } - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); + var pipeline_1 = pipeline; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); + (function (module, exports) { + exports = module.exports = _stream_readable; + exports.Stream = exports; + exports.Readable = exports; + exports.Writable = _stream_writable; + exports.Duplex = _stream_duplex; + exports.Transform = _stream_transform; + exports.PassThrough = _stream_passthrough; + exports.finished = endOfStream; + exports.pipeline = pipeline_1; + }(readableBrowser, readableBrowser.exports)); + + var Buffer$g = safeBuffer.exports.Buffer; + var Transform$2 = readableBrowser.exports.Transform; + var inherits$i = inherits_browser.exports; + + function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } + } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; + function HashBase$2 (blockSize) { + Transform$2.call(this); + this._block = Buffer$g.allocUnsafe(blockSize); + this._blockSize = blockSize; + this._blockOffset = 0; + this._length = [0, 0, 0, 0]; + this._finalized = false; + } - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + inherits$i(HashBase$2, Transform$2); - function unpipe() { - src.unpipe(dest); + HashBase$2.prototype._transform = function (chunk, encoding, callback) { + var error = null; + try { + this.update(chunk, encoding); + } catch (err) { + error = err; } - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); + callback(error); + }; - state.flowing = true; - nextTick(function() { - flow(src); - }); + HashBase$2.prototype._flush = function (callback) { + var error = null; + try { + this.push(this.digest()); + } catch (err) { + error = err; } - return dest; + callback(error); }; - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; - } - - function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; + HashBase$2.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data'); + if (this._finalized) throw new Error('Digest already called') + if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } + // consume data + var block = this._block; + var offset = 0; + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; + this._update(); + this._blockOffset = 0; } + while (offset < data.length) block[this._blockOffset++] = data[offset++]; - while (state.pipesCount && null !== (chunk = src.read())) { + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry; + carry = (this._length[j] / 0x0100000000) | 0; + if (carry > 0) this._length[j] -= 0x0100000000 * carry; + } - if (state.pipesCount === 1) - write(state.pipes); - else - forEach$1(state.pipes, write); + return this + }; - src.emit('data', chunk); + HashBase$2.prototype._update = function () { + throw new Error('_update is not implemented') + }; - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } + HashBase$2.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true; - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; + var digest = this._digest(); + if (encoding !== undefined) digest = digest.toString(encoding); - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } + // reset state + this._block.fill(0); + this._blockOffset = 0; + for (var i = 0; i < 4; ++i) this._length[i] = 0; - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; - } + return digest + }; - function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } - } + HashBase$2.prototype._digest = function () { + throw new Error('_digest is not implemented') + }; + var hashBase = HashBase$2; - Readable$1.prototype.unpipe = function(dest) { - var state = this._readableState; + var inherits$h = inherits_browser.exports; + var HashBase$1 = hashBase; + var Buffer$f = safeBuffer.exports.Buffer; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; + var ARRAY16$1 = new Array(16); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; + function MD5$2 () { + HashBase$1.call(this, 64); - if (!dest) - dest = state.pipes; + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + } - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } + inherits$h(MD5$2, HashBase$1); - // slow case. multiple pipe destinations. + MD5$2.prototype._update = function () { + var M = ARRAY16$1; + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; + var a = this._a; + var b = this._b; + var c = this._c; + var d = this._d; - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); + c = fnF(c, d, a, b, M[2], 0x242070db, 17); + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); + c = fnF(c, d, a, b, M[6], 0xa8304613, 17); + b = fnF(b, c, d, a, M[7], 0xfd469501, 22); + a = fnF(a, b, c, d, M[8], 0x698098d8, 7); + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); + a = fnF(a, b, c, d, M[12], 0x6b901122, 7); + d = fnF(d, a, b, c, M[13], 0xfd987193, 12); + c = fnF(c, d, a, b, M[14], 0xa679438e, 17); + b = fnF(b, c, d, a, M[15], 0x49b40821, 22); - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); + d = fnG(d, a, b, c, M[6], 0xc040b340, 9); + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); + d = fnG(d, a, b, c, M[10], 0x02441453, 9); + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); + d = fnH(d, a, b, c, M[8], 0x8771f681, 11); + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); + b = fnH(b, c, d, a, M[6], 0x04881d05, 23); + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); - dest.emit('unpipe', this); + a = fnI(a, b, c, d, M[0], 0xf4292244, 6); + d = fnI(d, a, b, c, M[7], 0x432aff97, 10); + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); + c = fnI(c, d, a, b, M[6], 0xa3014314, 15); + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); - return this; + this._a = (this._a + a) | 0; + this._b = (this._b + b) | 0; + this._c = (this._c + c) | 0; + this._d = (this._d + d) | 0; }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable$1.prototype.on = function(ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this); - } - } + MD5$2.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; } - return res; - }; - Readable$1.prototype.addListener = Readable$1.prototype.on; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable$1.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); + // produce result + var buffer = Buffer$f.allocUnsafe(16); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + return buffer }; - Readable$1.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); - }; + function rotl$1 (x, n) { + return (x << n) | (x >>> (32 - n)) + } - function emitDataEvents(stream, startPaused) { - var state = stream._readableState; + function fnF (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } + function fnG (a, b, c, d, m, k, s) { + return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } - var paused = startPaused || false; - var readable = false; + function fnH (a, b, c, d, m, k, s) { + return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream$1.prototype.pipe; - stream.on = stream.addListener = Stream$1.prototype.on; + function fnI (a, b, c, d, m, k, s) { + return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } - stream.on('readable', function() { - readable = true; + var md5_js = MD5$2; - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); + var Buffer$e = buffer.Buffer; + var inherits$g = inherits_browser.exports; + var HashBase = hashBase; - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); + var ARRAY16 = new Array(16); - stream.pause = function() { - paused = true; - this.emit('pause'); - }; + var zl = [ + 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 + ]; - stream.resume = function() { - paused = false; - if (readable) - nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; + var zr = [ + 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 + ]; - // now make it start, just in case it hadn't already. - stream.emit('readable'); - } + var sl = [ + 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 + ]; - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable$1.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; + var sr = [ + 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 + ]; - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } + var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; + var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; - self.push(null); - }); + function RIPEMD160$3 () { + HashBase.call(this, 64); - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); + // state + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; + } - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; + inherits$g(RIPEMD160$3, HashBase); - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + RIPEMD160$3.prototype._update = function () { + var words = ARRAY16; + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } + var al = this._a | 0; + var bl = this._b | 0; + var cl = this._c | 0; + var dl = this._d | 0; + var el = this._e | 0; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$1(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + var ar = this._a | 0; + var br = this._b | 0; + var cr = this._c | 0; + var dr = this._d | 0; + var er = this._e | 0; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); + // computation + for (var i = 0; i < 80; i += 1) { + var tl; + var tr; + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); } - }; - return self; - }; + al = el; + el = dl; + dl = rotl(cl, 10); + cl = bl; + bl = tl; + ar = er; + er = dr; + dr = rotl(cr, 10); + cr = br; + br = tr; + } + // update state + var t = (this._b + cl + dr) | 0; + this._b = (this._c + dl + er) | 0; + this._c = (this._d + el + ar) | 0; + this._d = (this._e + al + br) | 0; + this._e = (this._a + bl + cr) | 0; + this._a = t; + }; - // exposed for testing purposes only. - Readable$1._fromList = fromList; + RIPEMD160$3.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80; + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64); + this._update(); + this._blockOffset = 0; + } - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; + this._block.fill(0, this._blockOffset, 56); + this._block.writeUInt32LE(this._length[0], 56); + this._block.writeUInt32LE(this._length[1], 60); + this._update(); - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + // produce result + var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); + buffer.writeInt32LE(this._a, 0); + buffer.writeInt32LE(this._b, 4); + buffer.writeInt32LE(this._c, 8); + buffer.writeInt32LE(this._d, 12); + buffer.writeInt32LE(this._e, 16); + return buffer + }; - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer$i.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer$i(n); + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } - c += cpy; - } - } - } + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } - return ret; + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } - function endReadable(stream) { - var state = stream._readableState; + var ripemd160$2 = RIPEMD160$3; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); + var sha_js = {exports: {}}; - if (!state.endEmitted && state.calledRead) { - state.ended = true; - nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } - } + var Buffer$d = safeBuffer.exports.Buffer; - function forEach$1 (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } + // prototype class for hash functions + function Hash$7 (blockSize, finalSize) { + this._block = Buffer$d.alloc(blockSize); + this._finalSize = finalSize; + this._blockSize = blockSize; + this._len = 0; } - function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + Hash$7.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8'; + data = Buffer$d.from(data, enc); } - return -1; - } - // 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 block = this._block; + var blockSize = this._blockSize; + var length = data.length; + var accum = this._len; - // a duplex stream is just a stream that is both readable and writable. - // Since JS doesn't have multiple prototypal inheritance, this class - // prototypally inherits from Readable, and then parasitically from - // Writable. + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize; + var remainder = Math.min(length - offset, blockSize - assigned); - var _stream_duplex = Duplex$1; + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i]; + } - /**/ - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; - }; - /**/ + accum += remainder; + offset += remainder; + if ((accum % blockSize) === 0) { + this._update(block); + } + } - /**/ - var util$3 = util$5; - util$3.inherits = inherits_browser.exports; - /**/ + this._len += length; + return this + }; - var Readable = _stream_readable; - var Writable$1 = _stream_writable; + Hash$7.prototype.digest = function (enc) { + var rem = this._len % this._blockSize; - util$3.inherits(Duplex$1, Readable); + this._block[rem] = 0x80; - forEach(objectKeys(Writable$1.prototype), function(method) { - if (!Duplex$1.prototype[method]) - Duplex$1.prototype[method] = Writable$1.prototype[method]; - }); + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1); - function Duplex$1(options) { - if (!(this instanceof Duplex$1)) - return new Duplex$1(options); + if (rem >= this._finalSize) { + this._update(this._block); + this._block.fill(0); + } - Readable.call(this, options); - Writable$1.call(this, options); + var bits = this._len * 8; - if (options && options.readable === false) - this.readable = false; + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4); - if (options && options.writable === false) - this.writable = false; + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0; + var highBits = (bits - lowBits) / 0x100000000; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; + this._block.writeUInt32BE(highBits, this._blockSize - 8); + this._block.writeUInt32BE(lowBits, this._blockSize - 4); + } - this.once('end', onend); - } + this._update(this._block); + var hash = this._hash(); - // the no-half-open enforcer - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; + return enc ? hash.toString(enc) : hash + }; - // no more data can be written. - // But allow more writes to happen in this tick. - nextTick(this.end.bind(this)); - } + Hash$7.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + }; - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } + var hash$3 = Hash$7; - // 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. + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ - // A bit simpler than readable streams. - // Implement an async ._write(chunk, cb), and it'll handle all - // the drain event emission and buffering. + var inherits$f = inherits_browser.exports; + var Hash$6 = hash$3; + var Buffer$c = safeBuffer.exports.Buffer; - var _stream_writable = Writable; + var K$4 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - /**/ - var Buffer$h = buffer.Buffer; - /**/ + var W$5 = new Array(80); - Writable.WritableState = WritableState; + function Sha () { + this.init(); + this._w = W$5; + Hash$6.call(this, 64, 56); + } - /**/ - var util$2 = util$5; - util$2.inherits = inherits_browser.exports; - /**/ + inherits$f(Sha, Hash$6); - var Stream = require$$1; + Sha.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - util$2.inherits(Writable, Stream); + return this + }; - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; + function rotl5$1 (num) { + return (num << 5) | (num >>> 27) } - function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + function rotl30$1 (num) { + return (num << 30) | (num >>> 2) + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + function ft$1 (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + Sha.prototype._update = function (M) { + var W = this._w; - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + e = d; + d = c; + c = rotl30$1(b); + b = a; + a = t; + } - // a flag to see when we're in the middle of a write. - this.writing = false; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + }; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + Sha.prototype._hash = function () { + var H = Buffer$c.allocUnsafe(20); - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + return H + }; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var sha$4 = Sha; - // the amount that is being written when _write is called. - this.writelen = 0; + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ - this.buffer = []; + var inherits$e = inherits_browser.exports; + var Hash$5 = hash$3; + var Buffer$b = safeBuffer.exports.Buffer; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - } + var K$3 = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ]; - function Writable(options) { - var Duplex = _stream_duplex; + var W$4 = new Array(80); - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); + function Sha1 () { + this.init(); + this._w = W$4; - this._writableState = new WritableState(options, this); + Hash$5.call(this, 64, 56); + } - // legacy. - this.writable = true; + inherits$e(Sha1, Hash$5); - Stream.call(this); - } + Sha1.prototype.init = function () { + this._a = 0x67452301; + this._b = 0xefcdab89; + this._c = 0x98badcfe; + this._d = 0x10325476; + this._e = 0xc3d2e1f0; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); + return this }; + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - nextTick(function() { - cb(er); - }); + function rotl5 (num) { + return (num << 5) | (num >>> 27) } - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer$h.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; + function rotl30 (num) { + return (num << 30) | (num >>> 2) } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + Sha1.prototype._update = function (M) { + var W = this._w; - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; - if (typeof cb !== 'function') - cb = function() {}; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20); + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; - return ret; + e = d; + d = c; + c = rotl30(b); + b = a; + a = t; + } + + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer$h(chunk, encoding); - } - return chunk; - } + Sha1.prototype._hash = function () { + var H = Buffer$b.allocUnsafe(20); - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer$h.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; + H.writeInt32BE(this._a | 0, 0); + H.writeInt32BE(this._b | 0, 4); + H.writeInt32BE(this._c | 0, 8); + H.writeInt32BE(this._d | 0, 12); + H.writeInt32BE(this._e | 0, 16); - state.length += len; + return H + }; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + var sha1$1 = Sha1; - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - return ret; - } + var inherits$d = inherits_browser.exports; + var Hash$4 = hash$3; + var Buffer$a = safeBuffer.exports.Buffer; - function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + var K$2 = [ + 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 onwriteError(stream, state, sync, er, cb) { - if (sync) - nextTick(function() { - cb(er); - }); - else - cb(er); + var W$3 = new Array(64); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } + function Sha256$1 () { + this.init(); - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; + this._w = W$3; // new Array(64) + + Hash$4.call(this, 64, 56); } - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + inherits$d(Sha256$1, Hash$4); - onwriteStateUpdate(state); + Sha256$1.prototype.init = function () { + this._a = 0x6a09e667; + this._b = 0xbb67ae85; + this._c = 0x3c6ef372; + this._d = 0xa54ff53a; + this._e = 0x510e527f; + this._f = 0x9b05688c; + this._g = 0x1f83d9ab; + this._h = 0x5be0cd19; - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); + return this + }; - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - if (sync) { - nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } + function maj$1 (x, y, z) { + return (x & y) | (z & (x | y)) } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); + function sigma0$1 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } + function sigma1$1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + Sha256$1.prototype._update = function (M) { + var W = this._w; - doWrite(stream, state, len, chunk, encoding, cb); + var a = this._a | 0; + var b = this._b | 0; + var c = this._c | 0; + var d = this._d | 0; + var e = this._e | 0; + var f = this._f | 0; + var g = this._g | 0; + var h = this._h | 0; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; + var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - }; + h = g; + g = f; + f = e; + e = (d + T1) | 0; + d = c; + c = b; + b = a; + a = (T1 + T2) | 0; + } - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; + this._a = (a + this._a) | 0; + this._b = (b + this._b) | 0; + this._c = (c + this._c) | 0; + this._d = (d + this._d) | 0; + this._e = (e + this._e) | 0; + this._f = (f + this._f) | 0; + this._g = (g + this._g) | 0; + this._h = (h + this._h) | 0; + }; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + Sha256$1.prototype._hash = function () { + var H = Buffer$a.allocUnsafe(32); - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); + H.writeInt32BE(this._h, 28); - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); + return H }; + var sha256$2 = Sha256$1; - function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); - } + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ - function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; - } + var inherits$c = inherits_browser.exports; + var Sha256 = sha256$2; + var Hash$3 = hash$3; + var Buffer$9 = safeBuffer.exports.Buffer; - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; - } + var W$2 = new Array(64); - // 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. + function Sha224 () { + this.init(); + this._w = W$2; // new Array(64) - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. + Hash$3.call(this, 64, 56); + } - var _stream_transform = Transform$3; + inherits$c(Sha224, Sha256); - var Duplex = _stream_duplex; + Sha224.prototype.init = function () { + this._a = 0xc1059ed8; + this._b = 0x367cd507; + this._c = 0x3070dd17; + this._d = 0xf70e5939; + this._e = 0xffc00b31; + this._f = 0x68581511; + this._g = 0x64f98fa7; + this._h = 0xbefa4fa4; - /**/ - var util$1 = util$5; - util$1.inherits = inherits_browser.exports; - /**/ + return this + }; - util$1.inherits(Transform$3, Duplex); + Sha224.prototype._hash = function () { + var H = Buffer$9.allocUnsafe(28); + H.writeInt32BE(this._a, 0); + H.writeInt32BE(this._b, 4); + H.writeInt32BE(this._c, 8); + H.writeInt32BE(this._d, 12); + H.writeInt32BE(this._e, 16); + H.writeInt32BE(this._f, 20); + H.writeInt32BE(this._g, 24); - function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; + return H + }; - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - } + var sha224 = Sha224; - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + var inherits$b = inherits_browser.exports; + var Hash$2 = hash$3; + var Buffer$8 = safeBuffer.exports.Buffer; - var cb = ts.writecb; + var K$1 = [ + 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 + ]; - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + var W$1 = new Array(160); - ts.writechunk = null; - ts.writecb = null; + function Sha512 () { + this.init(); + this._w = W$1; + + Hash$2.call(this, 128, 112); + } - if (data !== null && data !== undefined) - stream.push(data); + inherits$b(Sha512, Hash$2); - if (cb) - cb(er); + Sha512.prototype.init = function () { + this._ah = 0x6a09e667; + this._bh = 0xbb67ae85; + this._ch = 0x3c6ef372; + this._dh = 0xa54ff53a; + this._eh = 0x510e527f; + this._fh = 0x9b05688c; + this._gh = 0x1f83d9ab; + this._hh = 0x5be0cd19; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } + this._al = 0xf3bcc908; + this._bl = 0x84caa73b; + this._cl = 0xfe94f82b; + this._dl = 0x5f1d36f1; + this._el = 0xade682d1; + this._fl = 0x2b3e6c1f; + this._gl = 0xfb41bd6b; + this._hl = 0x137e2179; + return this + }; - function Transform$3(options) { - if (!(this instanceof Transform$3)) - return new Transform$3(options); + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } - Duplex.call(this, options); + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } - this._transformState = new TransformState(options, this); + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } - // when the writable side finishes, then flush out anything remaining. - var stream = this; + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) } - Transform$3.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform$3.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); - }; + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } - Transform$3.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } - }; + Sha512.prototype._update = function (M) { + var W = this._w; - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform$3.prototype._read = function(n) { - var ts = this._transformState; + var ah = this._ah | 0; + var bh = this._bh | 0; + var ch = this._ch | 0; + var dh = this._dh | 0; + var eh = this._eh | 0; + var fh = this._fh | 0; + var gh = this._gh | 0; + var hh = this._hh | 0; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + var al = this._al | 0; + var bl = this._bl | 0; + var cl = this._cl | 0; + var dl = this._dl | 0; + var el = this._el | 0; + var fl = this._fl | 0; + var gl = this._gl | 0; + var hl = this._hl | 0; + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4); + W[i + 1] = M.readInt32BE(i * 4 + 4); } - }; + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2]; + var xl = W[i - 15 * 2 + 1]; + var gamma0 = Gamma0(xh, xl); + var gamma0l = Gamma0l(xl, xh); + xh = W[i - 2 * 2]; + xl = W[i - 2 * 2 + 1]; + var gamma1 = Gamma1(xh, xl); + var gamma1l = Gamma1l(xl, xh); - function done(stream, er) { - if (er) - return stream.emit('error', er); + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2]; + var Wi7l = W[i - 7 * 2 + 1]; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - stream._readableState; - var ts = stream._transformState; + var Wi16h = W[i - 16 * 2]; + var Wi16l = W[i - 16 * 2 + 1]; - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); + var Wil = (gamma0l + Wi7l) | 0; + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; + Wil = (Wil + gamma1l) | 0; + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; + Wil = (Wil + Wi16l) | 0; + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + W[i] = Wih; + W[i + 1] = Wil; + } - return stream.push(null); - } + for (var j = 0; j < 160; j += 2) { + Wih = W[j]; + Wil = W[j + 1]; - // 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 majh = maj(ah, bh, ch); + var majl = maj(al, bl, cl); - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. + var sigma0h = sigma0(ah, al); + var sigma0l = sigma0(al, ah); + var sigma1h = sigma1(eh, el); + var sigma1l = sigma1(el, eh); - var _stream_passthrough = PassThrough; + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K$1[j]; + var Kil = K$1[j + 1]; - var Transform$2 = _stream_transform; + var chh = Ch(eh, fh, gh); + var chl = Ch(el, fl, gl); - /**/ - var util = util$5; - util.inherits = inherits_browser.exports; - /**/ + var t1l = (hl + sigma1l) | 0; + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; + t1l = (t1l + chl) | 0; + t1h = (t1h + chh + getCarry(t1l, chl)) | 0; + t1l = (t1l + Kil) | 0; + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; + t1l = (t1l + Wil) | 0; + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; - util.inherits(PassThrough, Transform$2); + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0; + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = (dl + t1l) | 0; + eh = (dh + t1h + getCarry(el, dl)) | 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = (t1l + t2l) | 0; + ah = (t1h + t2h + getCarry(al, t1l)) | 0; + } - Transform$2.call(this, options); - } + this._al = (this._al + al) | 0; + this._bl = (this._bl + bl) | 0; + this._cl = (this._cl + cl) | 0; + this._dl = (this._dl + dl) | 0; + this._el = (this._el + el) | 0; + this._fl = (this._fl + fl) | 0; + this._gl = (this._gl + gl) | 0; + this._hl = (this._hl + hl) | 0; - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; }; - (function (module, exports) { - var Stream = require$$1; // hack to fix a circular dependency issue when used with browserify - exports = module.exports = _stream_readable; - exports.Stream = Stream; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; - }(readable, readable.exports)); - - var Buffer$g = safeBuffer.exports.Buffer; - var Transform$1 = readable.exports.Transform; - var inherits$g = inherits_browser.exports; + Sha512.prototype._hash = function () { + var H = Buffer$8.allocUnsafe(64); - function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer$g.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); } - } - function HashBase$2 (blockSize) { - Transform$1.call(this); - - this._block = Buffer$g.allocUnsafe(blockSize); - this._blockSize = blockSize; - this._blockOffset = 0; - this._length = [0, 0, 0, 0]; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); + writeInt64BE(this._gh, this._gl, 48); + writeInt64BE(this._hh, this._hl, 56); - this._finalized = false; - } + return H + }; - inherits$g(HashBase$2, Transform$1); + var sha512 = Sha512; - HashBase$2.prototype._transform = function (chunk, encoding, callback) { - var error = null; - try { - this.update(chunk, encoding); - } catch (err) { - error = err; - } + var inherits$a = inherits_browser.exports; + var SHA512$2 = sha512; + var Hash$1 = hash$3; + var Buffer$7 = safeBuffer.exports.Buffer; - callback(error); - }; + var W = new Array(160); - HashBase$2.prototype._flush = function (callback) { - var error = null; - try { - this.push(this.digest()); - } catch (err) { - error = err; - } + function Sha384 () { + this.init(); + this._w = W; - callback(error); - }; + Hash$1.call(this, 128, 112); + } - HashBase$2.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data'); - if (this._finalized) throw new Error('Digest already called') - if (!Buffer$g.isBuffer(data)) data = Buffer$g.from(data, encoding); + inherits$a(Sha384, SHA512$2); - // consume data - var block = this._block; - var offset = 0; - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]; - this._update(); - this._blockOffset = 0; - } - while (offset < data.length) block[this._blockOffset++] = data[offset++]; + Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d; + this._bh = 0x629a292a; + this._ch = 0x9159015a; + this._dh = 0x152fecd8; + this._eh = 0x67332667; + this._fh = 0x8eb44a87; + this._gh = 0xdb0c2e0d; + this._hh = 0x47b5481d; - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry; - carry = (this._length[j] / 0x0100000000) | 0; - if (carry > 0) this._length[j] -= 0x0100000000 * carry; - } + this._al = 0xc1059ed8; + this._bl = 0x367cd507; + this._cl = 0x3070dd17; + this._dl = 0xf70e5939; + this._el = 0xffc00b31; + this._fl = 0x68581511; + this._gl = 0x64f98fa7; + this._hl = 0xbefa4fa4; return this }; - HashBase$2.prototype._update = function () { - throw new Error('_update is not implemented') - }; - - HashBase$2.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true; - - var digest = this._digest(); - if (encoding !== undefined) digest = digest.toString(encoding); + Sha384.prototype._hash = function () { + var H = Buffer$7.allocUnsafe(48); - // reset state - this._block.fill(0); - this._blockOffset = 0; - for (var i = 0; i < 4; ++i) this._length[i] = 0; + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset); + H.writeInt32BE(l, offset + 4); + } - return digest - }; + writeInt64BE(this._ah, this._al, 0); + writeInt64BE(this._bh, this._bl, 8); + writeInt64BE(this._ch, this._cl, 16); + writeInt64BE(this._dh, this._dl, 24); + writeInt64BE(this._eh, this._el, 32); + writeInt64BE(this._fh, this._fl, 40); - HashBase$2.prototype._digest = function () { - throw new Error('_digest is not implemented') + return H }; - var hashBase = HashBase$2; + var sha384 = Sha384; - var inherits$f = inherits_browser.exports; - var HashBase$1 = hashBase; - var Buffer$f = safeBuffer.exports.Buffer; + var exports$1 = sha_js.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase(); - var ARRAY16$1 = new Array(16); + var Algorithm = exports$1[algorithm]; + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - function MD5$2 () { - HashBase$1.call(this, 64); + return new Algorithm() + }; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - } + exports$1.sha = sha$4; + exports$1.sha1 = sha1$1; + exports$1.sha224 = sha224; + exports$1.sha256 = sha256$2; + exports$1.sha384 = sha384; + exports$1.sha512 = sha512; - inherits$f(MD5$2, HashBase$1); + var sha$3 = sha_js.exports; - MD5$2.prototype._update = function () { - var M = ARRAY16$1; - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4); + var inherits$8; + if (typeof Object.create === 'function'){ + inherits$8 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$8 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$9 = inherits$8; - var a = this._a; - var b = this._b; - var c = this._c; - var d = this._d; + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7); - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12); - c = fnF(c, d, a, b, M[2], 0x242070db, 17); - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22); - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7); - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12); - c = fnF(c, d, a, b, M[6], 0xa8304613, 17); - b = fnF(b, c, d, a, M[7], 0xfd469501, 22); - a = fnF(a, b, c, d, M[8], 0x698098d8, 7); - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12); - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17); - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22); - a = fnF(a, b, c, d, M[12], 0x6b901122, 7); - d = fnF(d, a, b, c, M[13], 0xfd987193, 12); - c = fnF(c, d, a, b, M[14], 0xa679438e, 17); - b = fnF(b, c, d, a, M[15], 0x49b40821, 22); + 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. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, 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 + _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); + } + + // 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 !== 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 length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + 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()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(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); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return buffer.Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = buffer.Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + Readable.ReadableState = ReadableState; + + var debug$4 = debuglog('stream'); + inherits$9(Readable, EventEmitter$1); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5); - d = fnG(d, a, b, c, M[6], 0xc040b340, 9); - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14); - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20); - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5); - d = fnG(d, a, b, c, M[10], 0x02441453, 9); - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14); - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20); - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5); - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9); - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14); - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20); - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5); - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9); - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14); - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20); + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4); - d = fnH(d, a, b, c, M[8], 0x8771f681, 11); - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16); - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23); - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4); - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11); - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16); - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23); - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4); - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11); - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16); - b = fnH(b, c, d, a, M[6], 0x04881d05, 23); - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4); - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11); - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16); - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - a = fnI(a, b, c, d, M[0], 0xf4292244, 6); - d = fnI(d, a, b, c, M[7], 0x432aff97, 10); - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15); - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21); - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6); - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10); - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15); - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21); - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6); - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10); - c = fnI(c, d, a, b, M[6], 0xa3014314, 15); - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21); - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6); - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10); - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15); - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21); + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder_1(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { - this._a = (this._a + a) | 0; - this._b = (this._b + b) | 0; - this._c = (this._c + c) | 0; - this._d = (this._d + d) | 0; + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter$1.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$l.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); }; - MD5$2.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; } - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + return needMoreData(state); + } - // produce result - var buffer = Buffer$f.allocUnsafe(16); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - return buffer + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder_1(enc); + this._readableState.encoding = enc; + return this; }; - function rotl$1 (x, n) { - return (x << n) | (x >>> (32 - n)) + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; } - function fnF (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; } - function fnG (a, b, c, d, m, k, s) { - return (rotl$1((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug$4('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$4('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$4('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$4('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$4('reading or ended', doRead); + } else if (doRead) { + debug$4('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } - function fnH (a, b, c, d, m, k, s) { - return (rotl$1((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); } - function fnI (a, b, c, d, m, k, s) { - return (rotl$1((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$4('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } } - var md5_js = MD5$2; + function emitReadable_(stream) { + debug$4('emit readable'); + stream.emit('readable'); + flow(stream); + } - var Buffer$e = buffer.Buffer; - var inherits$e = inherits_browser.exports; - var HashBase = hashBase; + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } - var ARRAY16 = new Array(16); + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$4('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } - var zl = [ - 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 - ]; + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; - var zr = [ - 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 - ]; + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var sl = [ - 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 - ]; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$4('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$4('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug$4('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug$4('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$4('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$4('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$4('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$4('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug$4('unpipe'); + src.unpipe(dest); + } - var sr = [ - 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 - ]; + // tell the dest that it's being piped to + dest.emit('pipe', src); - var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]; - var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$4('pipe resume'); + src.resume(); + } - function RIPEMD160$3 () { - HashBase.call(this, 64); + return dest; + }; - // state - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug$4('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; } - inherits$e(RIPEMD160$3, HashBase); + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - RIPEMD160$3.prototype._update = function () { - var words = ARRAY16; - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - var al = this._a | 0; - var bl = this._b | 0; - var cl = this._c | 0; - var dl = this._d | 0; - var el = this._e | 0; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - var ar = this._a | 0; - var br = this._b | 0; - var cr = this._c | 0; - var dr = this._d | 0; - var er = this._e | 0; + if (!dest) dest = state.pipes; - // computation - for (var i = 0; i < 80; i += 1) { - var tl; - var tr; - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]); - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]); - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]); - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]); - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]); - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]); - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]); - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]); - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]); - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]); - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } - al = el; - el = dl; - dl = rotl(cl, 10); - cl = bl; - bl = tl; + // slow case. multiple pipe destinations. - ar = er; - er = dr; - dr = rotl(cr, 10); - cr = br; - br = tr; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; } - // update state - var t = (this._b + cl + dr) | 0; - this._b = (this._c + dl + er) | 0; - this._c = (this._d + el + ar) | 0; - this._d = (this._e + al + br) | 0; - this._e = (this._a + bl + cr) | 0; - this._a = t; + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; }; - RIPEMD160$3.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80; - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64); - this._update(); - this._blockOffset = 0; - } + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); - this._block.fill(0, this._blockOffset, 56); - this._block.writeUInt32LE(this._length[0], 56); - this._block.writeUInt32LE(this._length[1], 60); - this._update(); + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } - // produce result - var buffer = Buffer$e.alloc ? Buffer$e.alloc(20) : new Buffer$e(20); - buffer.writeInt32LE(this._a, 0); - buffer.writeInt32LE(this._b, 4); - buffer.writeInt32LE(this._c, 8); - buffer.writeInt32LE(this._d, 12); - buffer.writeInt32LE(this._e, 16); - return buffer + return res; }; + Readable.prototype.addListener = Readable.prototype.on; - function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) + function nReadingNextTick(self) { + debug$4('readable nexttick read 0'); + self.read(0); } - function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 - } + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$4('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; - function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } } - function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 - } + function resume_(stream, state) { + if (!state.reading) { + debug$4('resume read 0'); + stream.read(0); + } - function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } - function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 - } + Readable.prototype.pause = function () { + debug$4('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$4('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; - var ripemd160$2 = RIPEMD160$3; + function flow(stream) { + var state = stream._readableState; + debug$4('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } - var sha_js = {exports: {}}; + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - var Buffer$d = safeBuffer.exports.Buffer; + var self = this; + stream.on('end', function () { + debug$4('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - // prototype class for hash functions - function Hash$7 (blockSize, finalSize) { - this._block = Buffer$d.alloc(blockSize); - this._finalSize = finalSize; - this._blockSize = blockSize; - this._len = 0; - } + self.push(null); + }); - Hash$7.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8'; - data = Buffer$d.from(data, enc); - } + stream.on('data', function (chunk) { + debug$4('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - var block = this._block; - var blockSize = this._blockSize; - var length = data.length; - var accum = this._len; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize; - var remainder = Math.min(length - offset, blockSize - assigned); + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i]; + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); } + } - accum += remainder; - offset += remainder; + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); - if ((accum % blockSize) === 0) { - this._update(block); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$4('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); } - } + }; - this._len += length; - return this + return self; }; - Hash$7.prototype.digest = function (enc) { - var rem = this._len % this._blockSize; - - this._block[rem] = 0x80; + // exposed for testing purposes only. + Readable._fromList = fromList; - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1); + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - if (rem >= this._finalSize) { - this._update(this._block); - this._block.fill(0); + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); } - var bits = this._len * 8; - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4); + return ret; + } - // uint64 + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); } else { - var lowBits = (bits & 0xffffffff) >>> 0; - var highBits = (bits - lowBits) / 0x100000000; + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } - this._block.writeUInt32BE(highBits, this._blockSize - 8); - this._block.writeUInt32BE(lowBits, this._blockSize - 4); + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; } + list.length -= c; + return ret; + } - this._update(this._block); - var hash = this._hash(); + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$l.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } - return enc ? hash.toString(enc) : hash - }; + function endReadable(stream) { + var state = stream._readableState; - Hash$7.prototype._update = function () { - throw new Error('_update must be implemented by subclass') - }; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - var hash$3 = Hash$7; + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } - var inherits$d = inherits_browser.exports; - var Hash$6 = hash$3; - var Buffer$c = safeBuffer.exports.Buffer; + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - var K$4 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } - var W$5 = new Array(80); + // A bit simpler than readable streams. + Writable.WritableState = WritableState; + inherits$9(Writable, events.exports.EventEmitter); - function Sha () { - this.init(); - this._w = W$5; + function nop() {} - Hash$6.call(this, 64, 56); + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } - inherits$d(Sha, Hash$6); + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - Sha.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; + // a flag to see when we're in the middle of a write. + this.writing = false; - return this - }; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - function rotl5$1 (num) { - return (num << 5) | (num >>> 27) - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - function rotl30$1 (num) { - return (num << 30) | (num >>> 2) - } + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - function ft$1 (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - Sha.prototype._update = function (M) { - var W = this._w; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + // the amount that is being written when _write is called. + this.writelen = 0; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; + this.bufferedRequest = null; + this.lastBufferedRequest = null; - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5$1(a) + ft$1(s, b, c, d) + e + W[j] + K$4[s]) | 0; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - e = d; - d = c; - c = rotl30$1(b); - b = a; - a = t; - } + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - }; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - Sha.prototype._hash = function () { - var H = Buffer$c.allocUnsafe(20); + // count buffered requests + this.bufferedRequestCount = 0; - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } - return H + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; }; + function Writable(options) { - var sha$4 = Sha; - - /* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - var inherits$c = inherits_browser.exports; - var Hash$5 = hash$3; - var Buffer$b = safeBuffer.exports.Buffer; + this._writableState = new WritableState(options, this); - var K$3 = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 - ]; + // legacy. + this.writable = true; - var W$4 = new Array(80); + if (options) { + if (typeof options.write === 'function') this._write = options.write; - function Sha1 () { - this.init(); - this._w = W$4; + if (typeof options.writev === 'function') this._writev = options.writev; + } - Hash$5.call(this, 64, 56); + events.exports.EventEmitter.call(this); } - inherits$c(Sha1, Hash$5); - - Sha1.prototype.init = function () { - this._a = 0x67452301; - this._b = 0xefcdab89; - this._c = 0x98badcfe; - this._d = 0x10325476; - this._e = 0xc3d2e1f0; - - return this + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); }; - function rotl1 (num) { - return (num << 1) | (num >>> 31) + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); } - function rotl5 (num) { - return (num << 5) | (num >>> 27) + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!buffer.Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; } - function rotl30 (num) { - return (num << 30) | (num >>> 2) - } + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - Sha1.prototype._update = function (M) { - var W = this._w; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; + if (typeof cb !== 'function') cb = nop; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20); - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K$3[s]) | 0; + return ret; + }; - e = d; - d = c; - c = rotl30(b); - b = a; - a = t; - } + Writable.prototype.cork = function () { + var state = this._writableState; - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; + state.corked++; }; - Sha1.prototype._hash = function () { - var H = Buffer$b.allocUnsafe(20); + Writable.prototype.uncork = function () { + var state = this._writableState; - H.writeInt32BE(this._a | 0, 0); - H.writeInt32BE(this._b | 0, 4); - H.writeInt32BE(this._c | 0, 8); - H.writeInt32BE(this._d | 0, 12); - H.writeInt32BE(this._e | 0, 16); + if (state.corked) { + state.corked--; - return H + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } }; - var sha1$1 = Sha1; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = buffer.Buffer.from(chunk, encoding); + } + return chunk; + } - var inherits$b = inherits_browser.exports; - var Hash$4 = hash$3; - var Buffer$a = safeBuffer.exports.Buffer; + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); - var K$2 = [ - 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 - ]; + if (buffer.Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; - var W$3 = new Array(64); + state.length += len; - function Sha256$1 () { - this.init(); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - this._w = W$3; // new Array(64) + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - Hash$4.call(this, 64, 56); + return ret; } - inherits$b(Sha256$1, Hash$4); - - Sha256$1.prototype.init = function () { - this._a = 0x6a09e667; - this._b = 0xbb67ae85; - this._c = 0x3c6ef372; - this._d = 0xa54ff53a; - this._e = 0x510e527f; - this._f = 0x9b05688c; - this._g = 0x1f83d9ab; - this._h = 0x5be0cd19; + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - return this - }; + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); - function ch (x, y, z) { - return z ^ (x & (y ^ z)) + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - function maj$1 (x, y, z) { - return (x & y) | (z & (x | y)) + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - function sigma0$1 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) - } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - function sigma1$1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } } - function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); } - function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } } - Sha256$1.prototype._update = function (M) { - var W = this._w; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - var a = this._a | 0; - var b = this._b | 0; - var c = this._c | 0; - var d = this._d | 0; - var e = this._e | 0; - var f = this._f | 0; - var g = this._g | 0; - var h = this._h | 0; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4); - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0; + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1$1(e) + ch(e, f, g) + K$2[j] + W[j]) | 0; - var T2 = (sigma0$1(a) + maj$1(a, b, c)) | 0; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - h = g; - g = f; - f = e; - e = (d + T1) | 0; - d = c; - c = b; - b = a; - a = (T1 + T2) | 0; + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; } - this._a = (a + this._a) | 0; - this._b = (b + this._b) | 0; - this._c = (c + this._c) | 0; - this._d = (d + this._d) | 0; - this._e = (e + this._e) | 0; - this._f = (f + this._f) | 0; - this._g = (g + this._g) | 0; - this._h = (h + this._h) | 0; + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); }; - Sha256$1.prototype._hash = function () { - var H = Buffer$a.allocUnsafe(32); + Writable.prototype._writev = null; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); - H.writeInt32BE(this._h, 28); + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - return H + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); }; - var sha256$2 = Sha256$1; + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } - /** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } - var inherits$a = inherits_browser.exports; - var Sha256 = sha256$2; - var Hash$3 = hash$3; - var Buffer$9 = safeBuffer.exports.Buffer; + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } - var W$2 = new Array(64); + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } - function Sha224 () { - this.init(); + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; - this._w = W$2; // new Array(64) + this.next = null; + this.entry = null; - Hash$3.call(this, 64, 56); + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; } - inherits$a(Sha224, Sha256); + inherits$9(Duplex, Readable); - Sha224.prototype.init = function () { - this._a = 0xc1059ed8; - this._b = 0x367cd507; - this._c = 0x3070dd17; - this._d = 0xf70e5939; - this._e = 0xffc00b31; - this._f = 0x68581511; - this._g = 0x64f98fa7; - this._h = 0xbefa4fa4; + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - return this - }; + Readable.call(this, options); + Writable.call(this, options); - Sha224.prototype._hash = function () { - var H = Buffer$9.allocUnsafe(28); + if (options && options.readable === false) this.readable = false; - H.writeInt32BE(this._a, 0); - H.writeInt32BE(this._b, 4); - H.writeInt32BE(this._c, 8); - H.writeInt32BE(this._d, 12); - H.writeInt32BE(this._e, 16); - H.writeInt32BE(this._f, 20); - H.writeInt32BE(this._g, 24); + if (options && options.writable === false) this.writable = false; - return H - }; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - var sha224 = Sha224; + this.once('end', onend); + } - var inherits$9 = inherits_browser.exports; - var Hash$2 = hash$3; - var Buffer$8 = safeBuffer.exports.Buffer; + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - var K$1 = [ - 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 - ]; + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } - var W$1 = new Array(160); + function onEndNT(self) { + self.end(); + } - function Sha512 () { - this.init(); - this._w = W$1; + // a transform stream is a readable/writable stream where you do + inherits$9(Transform$1, Duplex); - Hash$2.call(this, 128, 112); + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; } - inherits$9(Sha512, Hash$2); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - Sha512.prototype.init = function () { - this._ah = 0x6a09e667; - this._bh = 0xbb67ae85; - this._ch = 0x3c6ef372; - this._dh = 0xa54ff53a; - this._eh = 0x510e527f; - this._fh = 0x9b05688c; - this._gh = 0x1f83d9ab; - this._hh = 0x5be0cd19; + var cb = ts.writecb; - this._al = 0xf3bcc908; - this._bl = 0x84caa73b; - this._cl = 0xfe94f82b; - this._dl = 0x5f1d36f1; - this._el = 0xade682d1; - this._fl = 0x2b3e6c1f; - this._gl = 0xfb41bd6b; - this._hl = 0x137e2179; + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - return this - }; + ts.writechunk = null; + ts.writecb = null; - function Ch (x, y, z) { - return z ^ (x & (y ^ z)) - } + if (data !== null && data !== undefined) stream.push(data); - function maj (x, y, z) { - return (x & y) | (z & (x | y)) - } + cb(er); - function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } + function Transform$1(options) { + if (!(this instanceof Transform$1)) return new Transform$1(options); - function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) - } + Duplex.call(this, options); - function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) - } + this._transformState = new TransformState(this); - function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); } - Sha512.prototype._update = function (M) { - var W = this._w; + Transform$1.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - var ah = this._ah | 0; - var bh = this._bh | 0; - var ch = this._ch | 0; - var dh = this._dh | 0; - var eh = this._eh | 0; - var fh = this._fh | 0; - var gh = this._gh | 0; - var hh = this._hh | 0; + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform$1.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; - var al = this._al | 0; - var bl = this._bl | 0; - var cl = this._cl | 0; - var dl = this._dl | 0; - var el = this._el | 0; - var fl = this._fl | 0; - var gl = this._gl | 0; - var hl = this._hl | 0; + Transform$1.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4); - W[i + 1] = M.readInt32BE(i * 4 + 4); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform$1.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2]; - var xl = W[i - 15 * 2 + 1]; - var gamma0 = Gamma0(xh, xl); - var gamma0l = Gamma0l(xl, xh); + }; - xh = W[i - 2 * 2]; - xl = W[i - 2 * 2 + 1]; - var gamma1 = Gamma1(xh, xl); - var gamma1l = Gamma1l(xl, xh); + function done(stream, er) { + if (er) return stream.emit('error', er); - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2]; - var Wi7l = W[i - 7 * 2 + 1]; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - var Wi16h = W[i - 16 * 2]; - var Wi16l = W[i - 16 * 2 + 1]; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - var Wil = (gamma0l + Wi7l) | 0; - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0; - Wil = (Wil + gamma1l) | 0; - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0; - Wil = (Wil + Wi16l) | 0; - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0; + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - W[i] = Wih; - W[i + 1] = Wil; - } + return stream.push(null); + } - for (var j = 0; j < 160; j += 2) { - Wih = W[j]; - Wil = W[j + 1]; + inherits$9(PassThrough, Transform$1); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - var majh = maj(ah, bh, ch); - var majl = maj(al, bl, cl); + Transform$1.call(this, options); + } - var sigma0h = sigma0(ah, al); - var sigma0l = sigma0(al, ah); - var sigma1h = sigma1(eh, el); - var sigma1l = sigma1(el, eh); + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K$1[j]; - var Kil = K$1[j + 1]; + inherits$9(Stream, EventEmitter$1); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform$1; + Stream.PassThrough = PassThrough; - var chh = Ch(eh, fh, gh); - var chl = Ch(el, fl, gl); + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; - var t1l = (hl + sigma1l) | 0; - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0; - t1l = (t1l + chl) | 0; - t1h = (t1h + chh + getCarry(t1l, chl)) | 0; - t1l = (t1l + Kil) | 0; - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0; - t1l = (t1l + Wil) | 0; - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0; + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0; - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0; + function Stream() { + EventEmitter$1.call(this); + } - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + getCarry(el, dl)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + getCarry(al, t1l)) | 0; + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } } - this._al = (this._al + al) | 0; - this._bl = (this._bl + bl) | 0; - this._cl = (this._cl + cl) | 0; - this._dl = (this._dl + dl) | 0; - this._el = (this._el + el) | 0; - this._fl = (this._fl + fl) | 0; - this._gl = (this._gl + gl) | 0; - this._hl = (this._hl + hl) | 0; + source.on('data', ondata); - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0; - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0; - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0; - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0; - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0; - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0; - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0; - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0; - }; + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } - Sha512.prototype._hash = function () { - var H = Buffer$8.allocUnsafe(64); + dest.on('drain', ondrain); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - writeInt64BE(this._gh, this._gl, 48); - writeInt64BE(this._hh, this._hl, 56); - - return H - }; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - var sha512 = Sha512; + dest.end(); + } - var inherits$8 = inherits_browser.exports; - var SHA512$2 = sha512; - var Hash$1 = hash$3; - var Buffer$7 = safeBuffer.exports.Buffer; - var W = new Array(160); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - function Sha384 () { - this.init(); - this._w = W; + if (typeof dest.destroy === 'function') dest.destroy(); + } - Hash$1.call(this, 128, 112); - } + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - inherits$8(Sha384, SHA512$2); + source.on('error', onerror); + dest.on('error', onerror); - Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d; - this._bh = 0x629a292a; - this._ch = 0x9159015a; - this._dh = 0x152fecd8; - this._eh = 0x67332667; - this._fh = 0x8eb44a87; - this._gh = 0xdb0c2e0d; - this._hh = 0x47b5481d; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - this._al = 0xc1059ed8; - this._bl = 0x367cd507; - this._cl = 0x3070dd17; - this._dl = 0xf70e5939; - this._el = 0xffc00b31; - this._fl = 0x68581511; - this._gl = 0x64f98fa7; - this._hl = 0xbefa4fa4; + source.removeListener('end', onend); + source.removeListener('close', onclose); - return this - }; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - Sha384.prototype._hash = function () { - var H = Buffer$7.allocUnsafe(48); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset); - H.writeInt32BE(l, offset + 4); + dest.removeListener('close', cleanup); } - writeInt64BE(this._ah, this._al, 0); - writeInt64BE(this._bh, this._bl, 8); - writeInt64BE(this._ch, this._cl, 16); - writeInt64BE(this._dh, this._dl, 24); - writeInt64BE(this._eh, this._el, 32); - writeInt64BE(this._fh, this._fl, 40); - - return H - }; - - var sha384 = Sha384; + source.on('end', cleanup); + source.on('close', cleanup); - var exports$1 = sha_js.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase(); + dest.on('close', cleanup); - var Algorithm = exports$1[algorithm]; - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + dest.emit('pipe', source); - return new Algorithm() + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; - exports$1.sha = sha$4; - exports$1.sha1 = sha1$1; - exports$1.sha224 = sha224; - exports$1.sha256 = sha256$2; - exports$1.sha384 = sha384; - exports$1.sha512 = sha512; + var stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform$1, + PassThrough: PassThrough, + Stream: Stream + }); - var sha$3 = sha_js.exports; + var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); var Buffer$6 = safeBuffer.exports.Buffer; var Transform = require$$1.Transform; @@ -11528,7 +12734,7 @@ var bs58check$5 = bs58checkBase(sha256x2); function pathElementsToBuffer(paths) { - var buffer = Buffer$k.alloc(1 + paths.length * 4); + var buffer = Buffer$l.alloc(1 + paths.length * 4); buffer[0] = paths.length; paths.forEach(function (element, index) { buffer.writeUInt32BE(element, 1 + 4 * index); @@ -23241,16 +24447,16 @@ const createHmac = browser$2; - const ONE1 = Buffer$k.alloc(1, 1); - const ZERO1 = Buffer$k.alloc(1, 0); + const ONE1 = Buffer$l.alloc(1, 1); + const ZERO1 = Buffer$l.alloc(1, 0); // https://tools.ietf.org/html/rfc6979#section-3.2 function deterministicGenerateK$1 (hash, x, checkSig, isPrivate, extraEntropy) { // Step A, ignored as hash already provided // Step B // Step C - let k = Buffer$k.alloc(32, 0); - let v = Buffer$k.alloc(32, 1); + let k = Buffer$l.alloc(32, 0); + let v = Buffer$l.alloc(32, 1); // Step D k = createHmac('sha256', k) @@ -23307,9 +24513,9 @@ const secp256k1 = new EC('secp256k1'); const deterministicGenerateK = rfc6979; - const ZERO32 = Buffer$k.alloc(32, 0); - const EC_GROUP_ORDER = Buffer$k.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); - const EC_P = Buffer$k.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); + const ZERO32 = Buffer$l.alloc(32, 0); + const EC_GROUP_ORDER = Buffer$l.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); + const EC_P = Buffer$l.from('fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', 'hex'); const n = secp256k1.curve.n; const nDiv2 = n.shrn(1); @@ -23381,9 +24587,9 @@ } function fromBuffer$1 (d) { return new BN(d) } - function toBuffer$1 (d) { return d.toArrayLike(Buffer$k, 'be', 32) } + function toBuffer$1 (d) { return d.toArrayLike(Buffer$l, 'be', 32) } function decodeFrom (P) { return secp256k1.curve.decodePoint(P) } - function getEncoded (P, compressed) { return Buffer$k.from(P._encode(compressed)) } + function getEncoded (P, compressed) { return Buffer$l.from(P._encode(compressed)) } function pointAdd (pA, pB, __compressed) { if (!isPoint(pA)) throw new TypeError(THROW_BAD_POINT) @@ -23515,7 +24721,7 @@ s = n.sub(s); } - const buffer = Buffer$k.allocUnsafe(64); + const buffer = Buffer$l.allocUnsafe(64); toBuffer$1(r).copy(buffer, 0); toBuffer$1(s).copy(buffer, 32); return buffer @@ -24100,7 +25306,7 @@ } function encodeRaw (version, privateKey, compressed) { - var result = new Buffer$k(compressed ? 34 : 33); + var result = new Buffer$l(compressed ? 34 : 33); result.writeUInt8(version, 0); privateKey.copy(result, 1); @@ -24219,7 +25425,7 @@ const version = !this.isNeutered() ? network.bip32.private : network.bip32.public; - const buffer = Buffer$k.allocUnsafe(78); + const buffer = Buffer$l.allocUnsafe(78); // 4 bytes: version bytes buffer.writeUInt32BE(version, 0); // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... @@ -24253,7 +25459,7 @@ derive(index) { typeforce$a(typeforce$a.UInt32, index); const isHardened = index >= HIGHEST_BIT; - const data = Buffer$k.allocUnsafe(37); + const data = Buffer$l.allocUnsafe(37); // Hardened child if (isHardened) { if (this.isNeutered()) @@ -24333,7 +25539,7 @@ } else { let sig = ecc$6.sign(hash, this.privateKey); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$l.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -24425,7 +25631,7 @@ if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits'); network = network || BITCOIN; - const I = crypto$3.hmacSHA512(Buffer$k.from('Bitcoin seed', 'utf8'), seed); + const I = crypto$3.hmacSHA512(Buffer$l.from('Bitcoin seed', 'utf8'), seed); const IL = I.slice(0, 32); const IR = I.slice(32); return fromPrivateKey$1(IL, IR, network); @@ -24532,7 +25738,7 @@ function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); - const buffer = Buffer$k.allocUnsafe(size); + const buffer = Buffer$l.allocUnsafe(size); const negative = _number < 0; for (let i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i); @@ -24727,18 +25933,18 @@ const types$9 = types$a; const bip66 = bip66$1; const typeforce$8 = typeforce_1; - const ZERO$1 = Buffer$k.alloc(1, 0); + const ZERO$1 = Buffer$l.alloc(1, 0); function toDER(x) { let i = 0; while (x[i] === 0) ++i; if (i === x.length) return ZERO$1; x = x.slice(i); - if (x[0] & 0x80) return Buffer$k.concat([ZERO$1, x], 1 + x.length); + if (x[0] & 0x80) return Buffer$l.concat([ZERO$1, x], 1 + x.length); return x; } function fromDER(x) { if (x[0] === 0x00) x = x.slice(1); - const buffer = Buffer$k.alloc(32, 0); + const buffer = Buffer$l.alloc(32, 0); const bstart = Math.max(0, 32 - x.length); x.copy(buffer, bstart); return buffer; @@ -24752,7 +25958,7 @@ const decoded = bip66.decode(buffer.slice(0, -1)); const r = fromDER(decoded.r); const s = fromDER(decoded.s); - const signature = Buffer$k.concat([r, s], 64); + const signature = Buffer$l.concat([r, s], 64); return { signature, hashType }; } script_signature.decode = decode$d; @@ -24767,11 +25973,11 @@ const hashTypeMod = hashType & ~0x80; if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType); - const hashTypeBuffer = Buffer$k.allocUnsafe(1); + const hashTypeBuffer = Buffer$l.allocUnsafe(1); hashTypeBuffer.writeUInt8(hashType, 0); const r = toDER(signature.slice(0, 32)); const s = toDER(signature.slice(32, 64)); - return Buffer$k.concat([bip66.encode(r, s), hashTypeBuffer]); + return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); } script_signature.encode = encode$e; @@ -25160,7 +26366,7 @@ // opcode return accum + 1; }, 0.0); - const buffer = Buffer$k.allocUnsafe(bufferSize); + const buffer = Buffer$l.allocUnsafe(bufferSize); let offset = 0; chunks.forEach(chunk => { // data chunk @@ -25245,7 +26451,7 @@ if (exports.OPS[chunkStr] !== undefined) return exports.OPS[chunkStr]; typeforce(types.Hex, chunkStr); // data! - return Buffer$k.from(chunkStr, 'hex'); + return Buffer$l.from(chunkStr, 'hex'); }), ); } @@ -25255,7 +26461,7 @@ typeforce(isPushOnly, chunks); return chunks.map(op => { if (singleChunkIsBuffer(op)) return op; - if (op === exports.OPS.OP_0) return Buffer$k.allocUnsafe(0); + if (op === exports.OPS.OP_0) return Buffer$l.allocUnsafe(0); return scriptNumber.encode(op - OP_INT_BASE); }); } @@ -25663,7 +26869,7 @@ const o = { name: 'p2pkh', network }; lazy$3.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(network.pubKeyHash, 0); o.hash.copy(payload, 1); return bs58check$2.encode(payload); @@ -25702,7 +26908,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch'); @@ -25821,7 +27027,7 @@ // output dependents lazy$2.prop(o, 'address', () => { if (!o.hash) return; - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(o.network.scriptHash, 0); o.hash.copy(payload, 1); return bs58check$1.encode(payload); @@ -25857,7 +27063,7 @@ return nameParts.join('-'); }); if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch'); @@ -26133,7 +27339,7 @@ const OPS$2 = bscript$j.OPS; const ecc$2 = js; const bech32$2 = bech32$3; - const EMPTY_BUFFER$1 = Buffer$k.alloc(0); + const EMPTY_BUFFER$1 = Buffer$l.alloc(0); // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} @@ -26161,7 +27367,7 @@ return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; }); const network = a.network || networks_1$2.bitcoin; @@ -26201,7 +27407,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26265,7 +27471,7 @@ const OPS$1 = bscript$i.OPS; const ecc$1 = js; const bech32$1 = bech32$3; - const EMPTY_BUFFER = Buffer$k.alloc(0); + const EMPTY_BUFFER = Buffer$l.alloc(0); function stacksEqual(a, b) { if (a.length !== b.length) return false; return a.every((x, i) => { @@ -26315,7 +27521,7 @@ return { version, prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; }); const _rchunks = lazy.value(() => { @@ -26380,7 +27586,7 @@ }); // extended validation if (opts.validate) { - let hash = Buffer$k.from([]); + let hash = Buffer$l.from([]); if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch'); @@ -26503,13 +27709,13 @@ return { version: result.words[0], prefix: result.prefix, - data: Buffer$k.from(data), + data: Buffer$l.from(data), }; } address$1.fromBech32 = fromBech32; function toBase58Check(hash, version) { typeforce$7(types$8.tuple(types$8.Hash160bit, types$8.UInt8), arguments); - const payload = Buffer$k.allocUnsafe(21); + const payload = Buffer$l.allocUnsafe(21); payload.writeUInt8(version, 0); hash.copy(payload, 1); return bs58check.encode(payload); @@ -26665,7 +27871,7 @@ return ecc.sign(hash, this.__D); } else { let sig = ecc.sign(hash, this.__D); - const extraData = Buffer$k.alloc(32, 0); + const extraData = Buffer$l.alloc(32, 0); let counter = 0; // if first try is lowR, skip the loop // for second try and on, add extra entropy counting up @@ -26867,7 +28073,7 @@ } bufferutils.reverseBuffer = reverseBuffer$1; function cloneBuffer(buffer) { - const clone = Buffer$k.allocUnsafe(buffer.length); + const clone = Buffer$l.allocUnsafe(buffer.length); buffer.copy(clone); return clone; } @@ -26990,17 +28196,17 @@ }, 0) ); } - const EMPTY_SCRIPT = Buffer$k.allocUnsafe(0); + const EMPTY_SCRIPT = Buffer$l.allocUnsafe(0); const EMPTY_WITNESS = []; - const ZERO = Buffer$k.from( + const ZERO = Buffer$l.from( '0000000000000000000000000000000000000000000000000000000000000000', 'hex', ); - const ONE = Buffer$k.from( + const ONE = Buffer$l.from( '0000000000000000000000000000000000000000000000000000000000000001', 'hex', ); - const VALUE_UINT64_MAX = Buffer$k.from('ffffffffffffffff', 'hex'); + const VALUE_UINT64_MAX = Buffer$l.from('ffffffffffffffff', 'hex'); const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX, @@ -27062,7 +28268,7 @@ return tx; } static fromHex(hex) { - return Transaction.fromBuffer(Buffer$k.from(hex, 'hex'), false); + return Transaction.fromBuffer(Buffer$l.from(hex, 'hex'), false); } static isCoinbaseHash(buffer) { typeforce$4(types$5.Hash256bit, buffer); @@ -27222,7 +28428,7 @@ txTmp.ins[inIndex].script = ourScript; } // serialize and hash - const buffer = Buffer$k.allocUnsafe(txTmp.byteLength(false) + 4); + const buffer = Buffer$l.allocUnsafe(txTmp.byteLength(false) + 4); buffer.writeInt32LE(hashType, buffer.length - 4); txTmp.__toBuffer(buffer, 0, false); return bcrypto$2.hash256(buffer); @@ -27232,13 +28438,13 @@ types$5.tuple(types$5.UInt32, types$5.Buffer, types$5.Satoshi, types$5.UInt32), arguments, ); - let tbuffer = Buffer$k.from([]); + let tbuffer = Buffer$l.from([]); let bufferWriter; let hashOutputs = ZERO; let hashPrevouts = ZERO; let hashSequence = ZERO; if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer$k.allocUnsafe(36 * this.ins.length); + tbuffer = Buffer$l.allocUnsafe(36 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeSlice(txIn.hash); @@ -27251,7 +28457,7 @@ (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE ) { - tbuffer = Buffer$k.allocUnsafe(4 * this.ins.length); + tbuffer = Buffer$l.allocUnsafe(4 * this.ins.length); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.ins.forEach(txIn => { bufferWriter.writeUInt32(txIn.sequence); @@ -27265,7 +28471,7 @@ const txOutsSize = this.outs.reduce((sum, output) => { return sum + 8 + varSliceSize(output.script); }, 0); - tbuffer = Buffer$k.allocUnsafe(txOutsSize); + tbuffer = Buffer$l.allocUnsafe(txOutsSize); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); this.outs.forEach(out => { bufferWriter.writeUInt64(out.value); @@ -27277,13 +28483,13 @@ inIndex < this.outs.length ) { const output = this.outs[inIndex]; - tbuffer = Buffer$k.allocUnsafe(8 + varSliceSize(output.script)); + tbuffer = Buffer$l.allocUnsafe(8 + varSliceSize(output.script)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); bufferWriter.writeUInt64(output.value); bufferWriter.writeVarSlice(output.script); hashOutputs = bcrypto$2.hash256(tbuffer); } - tbuffer = Buffer$k.allocUnsafe(156 + varSliceSize(prevOutScript)); + tbuffer = Buffer$l.allocUnsafe(156 + varSliceSize(prevOutScript)); bufferWriter = new bufferutils_1$3.BufferWriter(tbuffer, 0); const input = this.ins[inIndex]; bufferWriter.writeUInt32(this.version); @@ -27301,7 +28507,7 @@ } getHash(forWitness) { // wtxid for coinbase is always 32 bytes of 0x00 - if (forWitness && this.isCoinbase()) return Buffer$k.alloc(32, 0); + if (forWitness && this.isCoinbase()) return Buffer$l.alloc(32, 0); return bcrypto$2.hash256(this.__toBuffer(undefined, undefined, forWitness)); } getId() { @@ -27323,7 +28529,7 @@ this.ins[index].witness = witness; } __toBuffer(buffer, initialOffset, _ALLOW_WITNESS = false) { - if (!buffer) buffer = Buffer$k.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); + if (!buffer) buffer = Buffer$l.allocUnsafe(this.byteLength(_ALLOW_WITNESS)); const bufferWriter = new bufferutils_1$3.BufferWriter( buffer, initialOffset || 0, @@ -27385,7 +28591,7 @@ for (var i = 0; i < length; i += 2, ++j) { var left = results[i]; var right = i + 1 === length ? left : results[i + 1]; - var data = Buffer$k.concat([left, right]); + var data = Buffer$l.concat([left, right]); results[j] = digestFn(data); } @@ -27452,12 +28658,12 @@ return block; } static fromHex(hex) { - return Block.fromBuffer(Buffer$k.from(hex, 'hex')); + return Block.fromBuffer(Buffer$l.from(hex, 'hex')); } static calculateTarget(bits) { const exponent = ((bits & 0xff000000) >> 24) - 3; const mantissa = bits & 0x007fffff; - const target = Buffer$k.alloc(32, 0); + const target = Buffer$l.alloc(32, 0); target.writeUIntBE(mantissa, 29 - exponent, 3); return target; } @@ -27472,7 +28678,7 @@ const rootHash = fastMerkleRoot(hashes, bcrypto$1.hash256); return forWitness ? bcrypto$1.hash256( - Buffer$k.concat([rootHash, transactions[0].ins[0].witness[0]]), + Buffer$l.concat([rootHash, transactions[0].ins[0].witness[0]]), ) : rootHash; } @@ -27484,18 +28690,18 @@ // If multiple commits are found, the output with highest index is assumed. const witnessCommits = this.transactions[0].outs .filter(out => - out.script.slice(0, 6).equals(Buffer$k.from('6a24aa21a9ed', 'hex')), + out.script.slice(0, 6).equals(Buffer$l.from('6a24aa21a9ed', 'hex')), ) .map(out => out.script.slice(6, 38)); if (witnessCommits.length === 0) return null; // Use the commit with the highest output (should only be one though) const result = witnessCommits[witnessCommits.length - 1]; - if (!(result instanceof Buffer$k && result.length === 32)) return null; + if (!(result instanceof Buffer$l && result.length === 32)) return null; return result; } hasWitnessCommit() { if ( - this.witnessCommit instanceof Buffer$k && + this.witnessCommit instanceof Buffer$l && this.witnessCommit.length === 32 ) return true; @@ -27531,7 +28737,7 @@ } // TODO: buffer, offset compatibility toBuffer(headersOnly) { - const buffer = Buffer$k.allocUnsafe(this.byteLength(headersOnly)); + const buffer = Buffer$l.allocUnsafe(this.byteLength(headersOnly)); const bufferWriter = new bufferutils_1$2.BufferWriter(buffer); bufferWriter.writeInt32(this.version); bufferWriter.writeSlice(this.prevHash); @@ -27708,10 +28914,10 @@ } globalXpub$1.decode = decode$9; function encode$a(data) { - const head = Buffer$k.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); - const key = Buffer$k.concat([head, data.extendedPubkey]); + const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); + const key = Buffer$l.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -27760,7 +28966,7 @@ const typeFields_1$a = typeFields; function encode$9(data) { return { - key: Buffer$k.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), + key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } @@ -27781,7 +28987,7 @@ } finalScriptSig$1.decode = decode$8; function encode$8(data) { - const key = Buffer$k.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); + const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, @@ -27813,7 +29019,7 @@ } finalScriptWitness$1.decode = decode$7; function encode$7(data) { - const key = Buffer$k.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); + const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, @@ -27848,7 +29054,7 @@ nonWitnessUtxo$1.decode = decode$6; function encode$6(data) { return { - key: Buffer$k.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), + key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } @@ -27891,9 +29097,9 @@ } partialSig$1.decode = decode$5; function encode$5(pSig) { - const head = Buffer$k.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); + const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { - key: Buffer$k.concat([head, pSig.pubkey]), + key: Buffer$l.concat([head, pSig.pubkey]), value: pSig.signature, }; } @@ -27945,10 +29151,10 @@ } porCommitment$1.decode = decode$4; function encode$4(data) { - const key = Buffer$k.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); + const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, - value: Buffer$k.from(data, 'utf8'), + value: Buffer$l.from(data, 'utf8'), }; } porCommitment$1.encode = encode$4; @@ -27977,8 +29183,8 @@ } sighashType$1.decode = decode$3; function encode$3(data) { - const key = Buffer$k.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); - const value = Buffer$k.allocUnsafe(4); + const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); + const value = Buffer$l.allocUnsafe(4); value.writeUInt32LE(data, 0); return { key, @@ -28011,7 +29217,7 @@ } function encode$2(_number, buffer, offset) { checkUInt53(_number); - if (!buffer) buffer = Buffer$k.allocUnsafe(encodingLength(_number)); + if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; @@ -28097,8 +29303,8 @@ tools.reverseBuffer = reverseBuffer; function keyValsToBuffer(keyVals) { const buffers = keyVals.map(keyValToBuffer); - buffers.push(Buffer$k.from([0])); - return Buffer$k.concat(buffers); + buffers.push(Buffer$l.from([0])); + return Buffer$l.concat(buffers); } tools.keyValsToBuffer = keyValsToBuffer; function keyValToBuffer(keyVal) { @@ -28106,7 +29312,7 @@ const valLen = keyVal.value.length; const keyVarIntLen = varuint$3.encodingLength(keyLen); const valVarIntLen = varuint$3.encodingLength(valLen); - const buffer = Buffer$k.allocUnsafe( + const buffer = Buffer$l.allocUnsafe( keyVarIntLen + keyLen + valVarIntLen + valLen, ); varuint$3.encode(keyLen, buffer, 0); @@ -28170,12 +29376,12 @@ function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); - const result = Buffer$k.allocUnsafe(8 + varintLen + script.length); + const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); tools_1$2.writeUInt64LE(result, value, 0); varuint$2.encode(script.length, result, 8); script.copy(result, 8 + varintLen); return { - key: Buffer$k.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), + key: Buffer$l.from([typeFields_1$3.InputTypes.WITNESS_UTXO]), value: result, }; } @@ -28231,10 +29437,10 @@ return data; } function encode(data) { - const head = Buffer$k.from([TYPE_BYTE]); - const key = Buffer$k.concat([head, data.pubkey]); + const head = Buffer$l.from([TYPE_BYTE]); + const key = Buffer$l.concat([head, data.pubkey]); const splitPath = data.path.split('/'); - const value = Buffer$k.allocUnsafe(splitPath.length * 4); + const value = Buffer$l.allocUnsafe(splitPath.length * 4); data.masterFingerprint.copy(value, 0); let offset = 4; splitPath.slice(1).forEach(level => { @@ -28314,7 +29520,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$l.from([TYPE_BYTE]); return { key, value: data, @@ -28351,7 +29557,7 @@ return keyVal.value; } function encode(data) { - const key = Buffer$k.from([TYPE_BYTE]); + const key = Buffer$l.from([TYPE_BYTE]); return { key, value: data, @@ -28560,7 +29766,7 @@ } fromBuffer.psbtFromBuffer = psbtFromBuffer; function checkKeyBuffer(type, keyBuf, keyNum) { - if (!keyBuf.equals(Buffer$k.from([keyNum]))) { + if (!keyBuf.equals(Buffer$l.from([keyNum]))) { throw new Error( `Format Error: Invalid ${type} key: ${keyBuf.toString('hex')}`, ); @@ -28779,13 +29985,13 @@ const globalBuffer = tools_1.keyValsToBuffer(globalKeyVals); const keyValsOrEmptyToBuffer = keyVals => keyVals.length === 0 - ? [Buffer$k.from([0])] + ? [Buffer$l.from([0])] : keyVals.map(tools_1.keyValsToBuffer); const inputBuffers = keyValsOrEmptyToBuffer(inputKeyVals); const outputBuffers = keyValsOrEmptyToBuffer(outputKeyVals); - const header = Buffer$k.allocUnsafe(5); + const header = Buffer$l.allocUnsafe(5); header.writeUIntBE(0x70736274ff, 0, 5); - return Buffer$k.concat( + return Buffer$l.concat( [header, globalBuffer].concat(inputBuffers, outputBuffers), ); } @@ -29079,11 +30285,11 @@ }; } static fromBase64(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$l.from(data, 'base64'); return this.fromBuffer(buffer, txFromBuffer); } static fromHex(data, txFromBuffer) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$l.from(data, 'hex'); return this.fromBuffer(buffer, txFromBuffer); } static fromBuffer(buffer, txFromBuffer) { @@ -29303,11 +30509,11 @@ dpew(this, 'opts', false, true); } static fromBase64(data, opts = {}) { - const buffer = Buffer$k.from(data, 'base64'); + const buffer = Buffer$l.from(data, 'base64'); return this.fromBuffer(buffer, opts); } static fromHex(data, opts = {}) { - const buffer = Buffer$k.from(data, 'hex'); + const buffer = Buffer$l.from(data, 'hex'); return this.fromBuffer(buffer, opts); } static fromBuffer(buffer, opts = {}) { @@ -29831,7 +31037,7 @@ * It contains a bitcoinjs-lib Transaction object. */ class PsbtTransaction { - constructor(buffer = Buffer$k.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { + constructor(buffer = Buffer$l.from([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) { this.tx = transaction_1$2.Transaction.fromBuffer(buffer); checkTxEmpty(this.tx); Object.defineProperty(this, 'tx', { @@ -29856,7 +31062,7 @@ } const hash = typeof input.hash === 'string' - ? bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash, 'hex')) + ? bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash, 'hex')) : input.hash; this.tx.addInput(hash, input.index, input.sequence); } @@ -30031,7 +31237,7 @@ } function checkTxInputCache(cache, input) { const key = - bufferutils_1$1.reverseBuffer(Buffer$k.from(input.hash)).toString('hex') + + bufferutils_1$1.reverseBuffer(Buffer$l.from(input.hash)).toString('hex') + ':' + input.index; if (cache.__TX_IN_CACHE[key]) throw new Error('Duplicate input detected.'); @@ -30395,14 +31601,14 @@ return text; } function witnessStackToScriptWitness(witness) { - let buffer = Buffer$k.allocUnsafe(0); + let buffer = Buffer$l.allocUnsafe(0); function writeSlice(slice) { - buffer = Buffer$k.concat([buffer, Buffer$k.from(slice)]); + buffer = Buffer$l.concat([buffer, Buffer$l.from(slice)]); } function writeVarInt(i) { const currentLen = buffer.length; const varintLen = varuint.encodingLength(i); - buffer = Buffer$k.concat([buffer, Buffer$k.allocUnsafe(varintLen)]); + buffer = Buffer$l.concat([buffer, Buffer$l.allocUnsafe(varintLen)]); varuint.encode(i, buffer, currentLen); } function writeVarSlice(slice) { @@ -30911,7 +32117,7 @@ const script_1$3 = script$1; const types$2 = types$a; const typeforce$2 = typeforce_1; - const HEADER = Buffer$k.from('aa21a9ed', 'hex'); + const HEADER = Buffer$l.from('aa21a9ed', 'hex'); function check$2(script) { const buffer = bscript$3.compile(script); return ( @@ -30927,7 +32133,7 @@ }; function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); - const buffer = Buffer$k.allocUnsafe(36); + const buffer = Buffer$l.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); @@ -31203,7 +32409,7 @@ // is it a hex string? if (txIsString(txHash)) { // transaction hashs's are displayed in reverse order, un-reverse it - txHash = bufferutils_1.reverseBuffer(Buffer$k.from(txHash, 'hex')); + txHash = bufferutils_1.reverseBuffer(Buffer$l.from(txHash, 'hex')); // is it a Transaction object? } else if (txIsTransaction(txHash)) { const txOut = txHash.outs[vout]; @@ -34943,7 +36149,7 @@ if (n > Number.MAX_SAFE_INTEGER) { throw new Error("Can't convert numbers > MAX_SAFE_INT"); } - var byteArray = Buffer$k.alloc(8, 0); + var byteArray = Buffer$l.alloc(8, 0); for (var index = 0; index < byteArray.length; index++) { var byte = n & 0xff; byteArray[index] = byte; @@ -34972,7 +36178,7 @@ this.bufs = []; } BufferWriter.prototype.write = function (alloc, fn) { - var b = Buffer$k.alloc(alloc); + var b = Buffer$l.alloc(alloc); fn(b); this.bufs.push(b); }; @@ -34993,14 +36199,14 @@ this.bufs.push(varuintBitcoin.encode(i)); }; BufferWriter.prototype.writeSlice = function (slice) { - this.bufs.push(Buffer$k.from(slice)); + this.bufs.push(Buffer$l.from(slice)); }; BufferWriter.prototype.writeVarSlice = function (slice) { this.writeVarInt(slice.length); this.writeSlice(slice); }; BufferWriter.prototype.buffer = function () { - return Buffer$k.concat(this.bufs); + return Buffer$l.concat(this.bufs); }; return BufferWriter; }()); @@ -35142,9 +36348,9 @@ p2pkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE])); buf.writeSlice(pubkeyHash); - buf.writeSlice(Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG])); + buf.writeSlice(Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG])); return { scriptPubKey: buf.buffer() }; }; p2pkh.prototype.setSingleKeyInput = function (i, inputTx, _spentOutput, pubkey, path) { @@ -35171,7 +36377,7 @@ var xonlyPubkey = pubkey.slice(1); // x-only pubkey var buf = new BufferWriter(); var outputKey = this.getTaprootOutputKey(xonlyPubkey); - buf.writeSlice(Buffer$k.from([0x51, 32])); // push1, pubkeylen + buf.writeSlice(Buffer$l.from([0x51, 32])); // push1, pubkeylen buf.writeSlice(outputKey); return { scriptPubKey: buf.buffer() }; }; @@ -35194,8 +36400,8 @@ p2tr.prototype.hashTapTweak = function (x) { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification - var h = crypto_1.sha256(Buffer$k.from("TapTweak", "utf-8")); - return crypto_1.sha256(Buffer$k.concat([h, h, x])); + var h = crypto_1.sha256(Buffer$l.from("TapTweak", "utf-8")); + return crypto_1.sha256(Buffer$l.concat([h, h, x])); }; /** * Calculates a taproot output key from an internal key. This output key will be @@ -35214,13 +36420,13 @@ // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion - var evenEcdsaPubkey = Buffer$k.concat([ - Buffer$k.from([0x02]), + var evenEcdsaPubkey = Buffer$l.concat([ + Buffer$l.from([0x02]), internalPubkey, ]); var tweak = this.hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G - var outputEcdsaKey = Buffer$k.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); + var outputEcdsaKey = Buffer$l.from(js.pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. var outputSchnorrKey = outputEcdsaKey.slice(1); // Create address @@ -35237,7 +36443,7 @@ var buf = new BufferWriter(); var redeemScript = this.createRedeemScript(pubkey); var scriptHash = hashPublicKey(redeemScript); - buf.writeSlice(Buffer$k.from([OP_HASH160, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([OP_HASH160, HASH_SIZE])); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); return { scriptPubKey: buf.buffer(), redeemScript: redeemScript }; @@ -35267,7 +36473,7 @@ }; p2wpkhWrapped.prototype.createRedeemScript = function (pubkey) { var pubkeyHash = hashPublicKey(pubkey); - return Buffer$k.concat([Buffer$k.from("0014", "hex"), pubkeyHash]); + return Buffer$l.concat([Buffer$l.from("0014", "hex"), pubkeyHash]); }; return p2wpkhWrapped; }(SingleKeyAccount)); @@ -35279,7 +36485,7 @@ p2wpkh.prototype.singleKeyCondition = function (pubkey) { var buf = new BufferWriter(); var pubkeyHash = hashPublicKey(pubkey); - buf.writeSlice(Buffer$k.from([0, HASH_SIZE])); + buf.writeSlice(Buffer$l.from([0, HASH_SIZE])); buf.writeSlice(pubkeyHash); return { scriptPubKey: buf.buffer() }; }; @@ -35360,7 +36566,7 @@ var n = leaves.length; if (n == 0) { return { - root: new Node(undefined, undefined, Buffer$k.alloc(32, 0)), + root: new Node(undefined, undefined, Buffer$l.alloc(32, 0)), leaves: [] }; } @@ -35380,16 +36586,16 @@ return { root: node, leaves: leftBranch.leaves.concat(rightBranch.leaves) }; }; Merkle.prototype.hashNode = function (left, right) { - return this.h(Buffer$k.concat([Buffer$k.from([1]), left, right])); + return this.h(Buffer$l.concat([Buffer$l.from([1]), left, right])); }; return Merkle; }()); function hashLeaf(buf, hashFunction) { if (hashFunction === void 0) { hashFunction = crypto_1.sha256; } - return hashConcat(Buffer$k.from([0]), buf, hashFunction); + return hashConcat(Buffer$l.from([0]), buf, hashFunction); } function hashConcat(bufA, bufB, hashFunction) { - return hashFunction(Buffer$k.concat([bufA, bufB])); + return hashFunction(Buffer$l.concat([bufA, bufB])); } var Node = /** @class */ (function () { function Node(left, right, hash) { @@ -35454,13 +36660,13 @@ }; WalletPolicy.prototype.serialize = function () { var keyBuffers = this.keys.map(function (k) { - return Buffer$k.from(k, "ascii"); + return Buffer$l.from(k, "ascii"); }); var m = new Merkle(keyBuffers.map(function (k) { return hashLeaf(k); })); var buf = new BufferWriter(); buf.writeUInt8(0x01); // wallet type (policy map) buf.writeUInt8(0); // length of wallet name (empty string for default wallets) - buf.writeVarSlice(Buffer$k.from(this.descriptorTemplate, "ascii")); + buf.writeVarSlice(Buffer$l.from(this.descriptorTemplate, "ascii")); buf.writeVarInt(this.keys.length), buf.writeSlice(m.getRoot()); return buf.buffer(); }; @@ -35483,7 +36689,7 @@ tx.writeUInt32(psbt.getGlobalTxVersion()); var isSegwit = !!psbt.getInputWitnessUtxo(0); if (isSegwit) { - tx.writeSlice(Buffer$k.from([0, 1])); + tx.writeSlice(Buffer$l.from([0, 1])); } var inputCount = psbt.getGlobalInputCount(); tx.writeVarInt(inputCount); @@ -35491,7 +36697,7 @@ for (var i = 0; i < inputCount; i++) { tx.writeSlice(psbt.getInputPreviousTxid(i)); tx.writeUInt32(psbt.getInputOutputIndex(i)); - tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$k.from([])); + tx.writeVarSlice((_a = psbt.getInputFinalScriptsig(i)) !== null && _a !== void 0 ? _a : Buffer$l.from([])); tx.writeUInt32(psbt.getInputSequence(i)); if (isSegwit) { witnessWriter.writeSlice(psbt.getInputFinalScriptwitness(i)); @@ -35567,7 +36773,7 @@ psbtOut[psbtOut["SCRIPT"] = 4] = "SCRIPT"; psbtOut[psbtOut["TAP_BIP32_DERIVATION"] = 7] = "TAP_BIP32_DERIVATION"; })(psbtOut || (psbtOut = {})); - var PSBT_MAGIC_BYTES = Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff]); + var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { __extends$3(NoSuchEntry, _super); function NoSuchEntry() { @@ -35794,11 +37000,11 @@ }); }; PsbtV2.prototype.copyMap = function (from, to) { - from.forEach(function (v, k) { return to.set(k, Buffer$k.from(v)); }); + from.forEach(function (v, k) { return to.set(k, Buffer$l.from(v)); }); }; PsbtV2.prototype.serialize = function () { var buf = new BufferWriter(); - buf.writeSlice(Buffer$k.from([0x70, 0x73, 0x62, 0x74, 0xff])); + buf.writeSlice(Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff])); serializeMap(buf, this.globalMap); this.inputMaps.forEach(function (map) { serializeMap(buf, map); @@ -35842,17 +37048,17 @@ var result = []; map.forEach(function (_v, k) { if (_this.isKeyType(k, [keyType])) { - result.push(Buffer$k.from(k.substring(2), "hex")); + result.push(Buffer$l.from(k.substring(2), "hex")); } }); return result; }; PsbtV2.prototype.isKeyType = function (hexKey, keyTypes) { - var keyType = Buffer$k.from(hexKey.substring(0, 2), "hex").readUInt8(0); + var keyType = Buffer$l.from(hexKey.substring(0, 2), "hex").readUInt8(0); return keyTypes.some(function (k) { return k == keyType; }); }; PsbtV2.prototype.setGlobal = function (keyType, value) { - var key = new Key(keyType, Buffer$k.from([])); + var key = new Key(keyType, Buffer$l.from([])); this.globalMap.set(key.toString(), value); }; PsbtV2.prototype.getGlobal = function (keyType) { @@ -35938,7 +37144,7 @@ throw new NoSuchEntry(key.toString()); } // Make sure to return a copy, to protect the underlying data. - return Buffer$k.from(value); + return Buffer$l.from(value); } var Key = /** @class */ (function () { function Key(keyType, keyData) { @@ -35977,20 +37183,20 @@ function serializeMap(buf, map) { for (var k in map.keys) { var value = map.get(k); - var keyPair = new KeyPair(createKey(Buffer$k.from(k, "hex")), value); + var keyPair = new KeyPair(createKey(Buffer$l.from(k, "hex")), value); keyPair.serialize(buf); } buf.writeUInt8(0); } function b() { - return Buffer$k.from([]); + return Buffer$l.from([]); } function set(map, keyType, keyData, value) { var key = new Key(keyType, keyData); map.set(key.toString(), value); } function uint32LE(n) { - var b = Buffer$k.alloc(4); + var b = Buffer$l.alloc(4); b.writeUInt32LE(n, 0); return b; } @@ -36128,7 +37334,7 @@ } else if (data.length <= 256 * 256) { buf.writeUInt8(77); - var b = Buffer$k.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16LE(data.length, 0); buf.writeSlice(b); } @@ -36155,18 +37361,18 @@ } function createVarint(value) { if (value < 0xfd) { - var buffer_1 = Buffer$k.alloc(1); + var buffer_1 = Buffer$l.alloc(1); buffer_1[0] = value; return buffer_1; } if (value <= 0xffff) { - var buffer_2 = Buffer$k.alloc(3); + var buffer_2 = Buffer$l.alloc(3); buffer_2[0] = 0xfd; buffer_2[1] = value & 0xff; buffer_2[2] = (value >> 8) & 0xff; return buffer_2; } - var buffer = Buffer$k.alloc(5); + var buffer = Buffer$l.alloc(5); buffer[0] = 0xfe; buffer[1] = value & 0xff; buffer[2] = (value >> 8) & 0xff; @@ -36182,11 +37388,11 @@ */ function serializeTransactionOutputs(_a) { var outputs = _a.outputs; - var outputBuffer = Buffer$k.alloc(0); + var outputBuffer = Buffer$l.alloc(0); if (typeof outputs !== "undefined") { - outputBuffer = Buffer$k.concat([outputBuffer, createVarint(outputs.length)]); + outputBuffer = Buffer$l.concat([outputBuffer, createVarint(outputs.length)]); outputs.forEach(function (output) { - outputBuffer = Buffer$k.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, output.amount, createVarint(output.script.length), @@ -36200,18 +37406,18 @@ if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var isBech32 = additionals.includes("bech32"); - var inputBuffer = Buffer$k.alloc(0); + var inputBuffer = Buffer$l.alloc(0); var useWitness = typeof transaction["witness"] != "undefined" && !skipWitness; transaction.inputs.forEach(function (input) { inputBuffer = isDecred || isBech32 - ? Buffer$k.concat([ + ? Buffer$l.concat([ inputBuffer, input.prevout, - Buffer$k.from([0x00]), + Buffer$l.from([0x00]), input.sequence, ]) - : Buffer$k.concat([ + : Buffer$l.concat([ inputBuffer, input.prevout, createVarint(input.script.length), @@ -36222,19 +37428,19 @@ var outputBuffer = serializeTransactionOutputs(transaction); if (typeof transaction.outputs !== "undefined" && typeof transaction.locktime !== "undefined") { - outputBuffer = Buffer$k.concat([ + outputBuffer = Buffer$l.concat([ outputBuffer, - (useWitness && transaction.witness) || Buffer$k.alloc(0), + (useWitness && transaction.witness) || Buffer$l.alloc(0), transaction.locktime, - transaction.nExpiryHeight || Buffer$k.alloc(0), - transaction.extraData || Buffer$k.alloc(0), + transaction.nExpiryHeight || Buffer$l.alloc(0), + transaction.extraData || Buffer$l.alloc(0), ]); } - return Buffer$k.concat([ + return Buffer$l.concat([ transaction.version, - timestamp ? timestamp : Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), - useWitness ? Buffer$k.from("0001", "hex") : Buffer$k.alloc(0), + timestamp ? timestamp : Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), + useWitness ? Buffer$l.from("0001", "hex") : Buffer$l.alloc(0), createVarint(transaction.inputs.length), inputBuffer, outputBuffer, @@ -36372,7 +37578,7 @@ case 2: address = _c.sent(); components = getXpubComponents(xpub); - uncompressedPubkey = Buffer$k.from(js.pointCompress(components.pubkey, false)); + uncompressedPubkey = Buffer$l.from(js.pointCompress(components.pubkey, false)); return [2 /*return*/, { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, @@ -36415,7 +37621,7 @@ masterFingerprint = _a.sent(); policy = new WalletPolicy(descrTempl, createKey$1(masterFingerprint, accountPath, accountXpub)); changeAndIndex = pathElements.slice(-2, pathElements.length); - return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$k.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; + return [2 /*return*/, this.client.getWalletAddress(policy, Buffer$l.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display)]; } }); }); @@ -36484,7 +37690,7 @@ i++; return [3 /*break*/, 2]; case 7: - outputsConcat = Buffer$k.from(arg.outputScriptHex, "hex"); + outputsConcat = Buffer$l.from(arg.outputScriptHex, "hex"); outputsBufferReader = new BufferReader(outputsConcat); outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); @@ -36580,7 +37786,7 @@ case 0: inputTx = input[0]; spentOutputIndex = input[1]; - redeemScript = input[2] ? Buffer$k.from(input[2], "hex") : undefined; + redeemScript = input[2] ? Buffer$l.from(input[2], "hex") : undefined; sequence = input[3]; if (sequence != undefined) { psbt.setInputSequence(i, sequence); @@ -36624,7 +37830,7 @@ var sigs; return __generator$e(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$k.alloc(32, 0), progressCallback)]; + case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; case 1: sigs = _a.sent(); sigs.forEach(function (v, k) { @@ -36913,9 +38119,9 @@ firstRound = false; if (typeof indexLookup === "number") { firstRound = true; - prefix = Buffer$k.alloc(4); + prefix = Buffer$l.alloc(4); prefix.writeUInt32BE(indexLookup, 0); - data = Buffer$k.concat([prefix, transactionData], transactionData.length + 4); + data = Buffer$l.concat([prefix, transactionData], transactionData.length + 4); } else { data = transactionData; @@ -36950,7 +38156,7 @@ return __generator$c(this, function (_b) { switch (_b.label) { case 0: - seq = sequence || Buffer$k.alloc(0); + seq = sequence || Buffer$l.alloc(0); scriptBlocks = []; offset = 0; while (offset !== script.length) { @@ -36961,7 +38167,7 @@ scriptBlocks.push(script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$k.concat([script.slice(offset, offset + blockSize), seq])); + scriptBlocks.push(Buffer$l.concat([script.slice(offset, offset + blockSize), seq])); } offset += blockSize; } @@ -37003,10 +38209,10 @@ processWholeScriptBlock = function (block) { return getTrustedInputRaw(transport, block); }; - return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$k.concat([ + return [4 /*yield*/, getTrustedInputRaw(transport, Buffer$l.concat([ transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), createVarint(inputs.length), ]), indexLookup)]; case 1: @@ -37020,14 +38226,14 @@ if (!!inputs_1_1.done) return [3 /*break*/, 7]; input = inputs_1_1.value; isXSTV2 = isXST && - Buffer$k.compare(version, Buffer$k.from([0x02, 0x00, 0x00, 0x00])) === 0; + Buffer$l.compare(version, Buffer$l.from([0x02, 0x00, 0x00, 0x00])) === 0; treeField = isDecred - ? input.tree || Buffer$k.from([0x00]) - : Buffer$k.alloc(0); - data = Buffer$k.concat([ + ? input.tree || Buffer$l.from([0x00]) + : Buffer$l.alloc(0); + data = Buffer$l.concat([ input.prevout, treeField, - isXSTV2 ? Buffer$k.from([0x00]) : createVarint(input.script.length), + isXSTV2 ? Buffer$l.from([0x00]) : createVarint(input.script.length), ]); return [4 /*yield*/, getTrustedInputRaw(transport, data)]; case 4: @@ -37037,7 +38243,7 @@ // deferred.notify("input"); // Reference: https://github.com/StealthSend/Stealth/commit/5be35d6c2c500b32ed82e5d6913d66d18a4b0a7f#diff-e8db9b851adc2422aadfffca88f14c91R566 return [4 /*yield*/, (isDecred - ? processWholeScriptBlock(Buffer$k.concat([input.script, input.sequence])) + ? processWholeScriptBlock(Buffer$l.concat([input.script, input.sequence])) : isXSTV2 ? processWholeScriptBlock(input.sequence) : processScriptBlocks(input.script, input.sequence))]; @@ -37073,9 +38279,9 @@ case 13: if (!!outputs_1_1.done) return [3 /*break*/, 16]; output = outputs_1_1.value; - data = Buffer$k.concat([ + data = Buffer$l.concat([ output.amount, - isDecred ? Buffer$k.from([0x00, 0x00]) : Buffer$k.alloc(0), + isDecred ? Buffer$l.from([0x00, 0x00]) : Buffer$l.alloc(0), createVarint(output.script.length), output.script, ]); @@ -37106,12 +38312,12 @@ endData.push(extraData); } if (endData.length) { - data = Buffer$k.concat(endData); + data = Buffer$l.concat(endData); extraPart = isDecred ? data - : Buffer$k.concat([createVarint(data.length), data]); + : Buffer$l.concat([createVarint(data.length), data]); } - return [4 /*yield*/, processScriptBlocks(Buffer$k.concat([locktime, extraPart || Buffer$k.alloc(0)]))]; + return [4 /*yield*/, processScriptBlocks(Buffer$l.concat([locktime, extraPart || Buffer$l.alloc(0)]))]; case 20: res = _c.sent(); browser(res, "missing result in processScriptBlocks"); @@ -37194,10 +38400,10 @@ return __generator$b(this, function (_e) { switch (_e.label) { case 0: - data = Buffer$k.concat([ + data = Buffer$l.concat([ transaction.version, - transaction.timestamp || Buffer$k.alloc(0), - transaction.nVersionGroupId || Buffer$k.alloc(0), + transaction.timestamp || Buffer$l.alloc(0), + transaction.nVersionGroupId || Buffer$l.alloc(0), createVarint(transaction.inputs.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, true, data, bip143, overwinter, additionals)]; @@ -37217,24 +38423,24 @@ inputValue = inputs[i].value; if (bip143) { if (useTrustedInputForSegwit && inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputValue.length]); + prefix = Buffer$l.from([0x01, inputValue.length]); } else { - prefix = Buffer$k.from([0x02]); + prefix = Buffer$l.from([0x02]); } } else { if (inputs[i].trustedInput) { - prefix = Buffer$k.from([0x01, inputs[i].value.length]); + prefix = Buffer$l.from([0x01, inputs[i].value.length]); } else { - prefix = Buffer$k.from([0x00]); + prefix = Buffer$l.from([0x00]); } } - data = Buffer$k.concat([ + data = Buffer$l.concat([ prefix, inputValue, - isDecred ? Buffer$k.from([0x00]) : Buffer$k.alloc(0), + isDecred ? Buffer$l.from([0x00]) : Buffer$l.alloc(0), createVarint(input.script.length), ]); return [4 /*yield*/, startUntrustedHashTransactionInputRaw(transport, newTransaction, false, data, bip143, overwinter, additionals)]; @@ -37254,7 +38460,7 @@ scriptBlocks.push(input.script.slice(offset, offset + blockSize)); } else { - scriptBlocks.push(Buffer$k.concat([ + scriptBlocks.push(Buffer$l.concat([ input.script.slice(offset, offset + blockSize), input.sequence, ])); @@ -37323,7 +38529,7 @@ var hash = sha$3("sha256") .update(sha$3("sha256").update(serializeTransaction(transaction, true)).digest()) .digest(); - var data = Buffer$k.alloc(4); + var data = Buffer$l.alloc(4); data.writeUInt32LE(indexLookup, 0); var outputs = transaction.outputs, locktime = transaction.locktime; if (!outputs || !locktime) { @@ -37332,38 +38538,38 @@ if (!outputs[indexLookup]) { throw new Error("getTrustedInputBIP143: wrong index"); } - hash = Buffer$k.concat([hash, data, outputs[indexLookup].amount]); + hash = Buffer$l.concat([hash, data, outputs[indexLookup].amount]); return hash.toString("hex"); } function compressPublicKey(publicKey) { var prefix = (publicKey[64] & 1) !== 0 ? 0x03 : 0x02; - var prefixBuffer = Buffer$k.alloc(1); + var prefixBuffer = Buffer$l.alloc(1); prefixBuffer[0] = prefix; - return Buffer$k.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); + return Buffer$l.concat([prefixBuffer, publicKey.slice(1, 1 + 32)]); } function signTransaction(transport, path, lockTime, sigHashType, expiryHeight, additionals) { if (additionals === void 0) { additionals = []; } var isDecred = additionals.includes("decred"); var pathsBuffer = bip32asBuffer(path); - var lockTimeBuffer = Buffer$k.alloc(4); + var lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32BE(lockTime, 0); var buffer = isDecred - ? Buffer$k.concat([ + ? Buffer$l.concat([ pathsBuffer, lockTimeBuffer, - expiryHeight || Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([sigHashType]), + expiryHeight || Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([sigHashType]), ]) - : Buffer$k.concat([ + : Buffer$l.concat([ pathsBuffer, - Buffer$k.from([0x00]), + Buffer$l.from([0x00]), lockTimeBuffer, - Buffer$k.from([sigHashType]), + Buffer$l.from([sigHashType]), ]); if (expiryHeight && !isDecred) { - buffer = Buffer$k.concat([buffer, expiryHeight]); + buffer = Buffer$l.concat([buffer, expiryHeight]); } return transport.send(0xe0, 0x48, 0x00, 0x00, buffer).then(function (result) { if (result.length > 0) { @@ -37638,9 +38844,9 @@ additionals.includes("gold") || additionals.includes("bip143"))) || (!!expiryHeight && !isDecred); - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); !!expiryHeight && !isDecred ? defaultVersion.writeUInt32LE(sapling ? 0x80000004 : 0x80000003, 0) : isXST @@ -37655,12 +38861,12 @@ targetTransaction = { inputs: [], version: defaultVersion, - timestamp: Buffer$k.alloc(0) + timestamp: Buffer$l.alloc(0) }; getTrustedInputCall = useBip143 && !useTrustedInputForSegwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); notify(0, 0); _b.label = 5; case 5: @@ -37675,13 +38881,13 @@ case 7: trustedInput = _b.sent(); log("hw", "got trustedInput=" + trustedInput); - sequence = Buffer$k.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: true, - value: Buffer$k.from(trustedInput, "hex"), + value: Buffer$l.from(trustedInput, "hex"), sequence: sequence }); _b.label = 8; @@ -37692,11 +38898,11 @@ regularOutputs.push(outputs[index]); } if (expiryHeight && !isDecred) { - targetTransaction.nVersionGroupId = Buffer$k.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); + targetTransaction.nVersionGroupId = Buffer$l.from(sapling ? [0x85, 0x20, 0x2f, 0x89] : [0x70, 0x82, 0xc4, 0x03]); targetTransaction.nExpiryHeight = expiryHeight; // For sapling : valueBalance (8), nShieldedSpend (1), nShieldedOutput (1), nJoinSplit (1) // Overwinter : use nJoinSplit (1) - targetTransaction.extraData = Buffer$k.from(sapling + targetTransaction.extraData = Buffer$l.from(sapling ? [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] : [0x00]); } @@ -37720,7 +38926,7 @@ return [7 /*endfinally*/]; case 13: targetTransaction.inputs = inputs.map(function (input) { - var sequence = Buffer$k.alloc(4); + var sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); @@ -37749,12 +38955,12 @@ return [3 /*break*/, 14]; case 17: for (i = 0; i < result_1.length; i++) { - publicKeys.push(compressPublicKey(Buffer$k.from(result_1[i].publicKey, "hex"))); + publicKeys.push(compressPublicKey(Buffer$l.from(result_1[i].publicKey, "hex"))); } _b.label = 18; case 18: if (initialTimestamp !== undefined) { - targetTransaction.timestamp = Buffer$k.alloc(4); + targetTransaction.timestamp = Buffer$l.alloc(4); targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); } onDeviceSignatureRequested(); @@ -37786,13 +38992,13 @@ if (!(i < inputs.length)) return [3 /*break*/, 34]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : !segwit ? regularOutputs[i].script - : Buffer$k.concat([ - Buffer$k.from([OP_DUP, OP_HASH160, HASH_SIZE]), + : Buffer$l.concat([ + Buffer$l.from([OP_DUP, OP_HASH160, HASH_SIZE]), hashPublicKey(publicKeys[i]), - Buffer$k.from([OP_EQUALVERIFY, OP_CHECKSIG]), + Buffer$l.from([OP_EQUALVERIFY, OP_CHECKSIG]), ]); pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = useBip143 ? [trustedInputs[i]] : trustedInputs; @@ -37837,20 +39043,20 @@ // Populate the final input scripts for (i = 0; i < inputs.length; i++) { if (segwit) { - targetTransaction.witness = Buffer$k.alloc(0); + targetTransaction.witness = Buffer$l.alloc(0); if (!bech32) { - targetTransaction.inputs[i].script = Buffer$k.concat([ - Buffer$k.from("160014", "hex"), + targetTransaction.inputs[i].script = Buffer$l.concat([ + Buffer$l.from("160014", "hex"), hashPublicKey(publicKeys[i]), ]); } } else { - signatureSize = Buffer$k.alloc(1); - keySize = Buffer$k.alloc(1); + signatureSize = Buffer$l.alloc(1); + keySize = Buffer$l.alloc(1); signatureSize[0] = signatures[i].length; keySize[0] = publicKeys[i].length; - targetTransaction.inputs[i].script = Buffer$k.concat([ + targetTransaction.inputs[i].script = Buffer$l.concat([ signatureSize, signatures[i], keySize, @@ -37860,51 +39066,51 @@ offset = useBip143 && !useTrustedInputForSegwit ? 0 : 4; targetTransaction.inputs[i].prevout = trustedInputs[i].value.slice(offset, offset + 0x24); } - lockTimeBuffer = Buffer$k.alloc(4); + lockTimeBuffer = Buffer$l.alloc(4); lockTimeBuffer.writeUInt32LE(lockTime, 0); - result = Buffer$k.concat([ + result = Buffer$l.concat([ serializeTransaction(targetTransaction, false, targetTransaction.timestamp, additionals), outputScript, ]); if (segwit && !isDecred) { - witness = Buffer$k.alloc(0); + witness = Buffer$l.alloc(0); for (i = 0; i < inputs.length; i++) { - tmpScriptData = Buffer$k.concat([ - Buffer$k.from("02", "hex"), - Buffer$k.from([signatures[i].length]), + tmpScriptData = Buffer$l.concat([ + Buffer$l.from("02", "hex"), + Buffer$l.from([signatures[i].length]), signatures[i], - Buffer$k.from([publicKeys[i].length]), + Buffer$l.from([publicKeys[i].length]), publicKeys[i], ]); - witness = Buffer$k.concat([witness, tmpScriptData]); + witness = Buffer$l.concat([witness, tmpScriptData]); } - result = Buffer$k.concat([result, witness]); + result = Buffer$l.concat([result, witness]); } // FIXME: In ZEC or KMD sapling lockTime is serialized before expiryHeight. // expiryHeight is used only in overwinter/sapling so I moved lockTimeBuffer here // and it should not break other coins because expiryHeight is false for them. // Don't know about Decred though. - result = Buffer$k.concat([result, lockTimeBuffer]); + result = Buffer$l.concat([result, lockTimeBuffer]); if (expiryHeight) { - result = Buffer$k.concat([ + result = Buffer$l.concat([ result, - targetTransaction.nExpiryHeight || Buffer$k.alloc(0), - targetTransaction.extraData || Buffer$k.alloc(0), + targetTransaction.nExpiryHeight || Buffer$l.alloc(0), + targetTransaction.extraData || Buffer$l.alloc(0), ]); } if (isDecred) { - decredWitness_1 = Buffer$k.from([targetTransaction.inputs.length]); + decredWitness_1 = Buffer$l.from([targetTransaction.inputs.length]); inputs.forEach(function (input, inputIndex) { - decredWitness_1 = Buffer$k.concat([ + decredWitness_1 = Buffer$l.concat([ decredWitness_1, - Buffer$k.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0x00, 0x00, 0x00, 0x00]), - Buffer$k.from([0xff, 0xff, 0xff, 0xff]), - Buffer$k.from([targetTransaction.inputs[inputIndex].script.length]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0x00, 0x00, 0x00, 0x00]), + Buffer$l.from([0xff, 0xff, 0xff, 0xff]), + Buffer$l.from([targetTransaction.inputs[inputIndex].script.length]), targetTransaction.inputs[inputIndex].script, ]); }); - result = Buffer$k.concat([result, decredWitness_1]); + result = Buffer$l.concat([result, decredWitness_1]); } return [2 /*return*/, result.toString("hex")]; } @@ -37956,7 +39162,7 @@ switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); - message = Buffer$k.from(messageHex, "hex"); + message = Buffer$l.from(messageHex, "hex"); offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; @@ -37969,7 +39175,7 @@ chunkSize = offset + maxChunkSize > message.length ? message.length - offset : maxChunkSize; - buffer = Buffer$k.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); + buffer = Buffer$l.alloc(offset === 0 ? 1 + paths.length * 4 + 2 + chunkSize : chunkSize); if (offset === 0) { buffer[0] = paths.length; paths.forEach(function (element, index) { @@ -37996,7 +39202,7 @@ case 2: _b.sent(); return [3 /*break*/, 1]; - case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$k.from([0x00]))]; + case 3: return [4 /*yield*/, transport.send(0xe0, 0x4e, 0x80, 0x00, Buffer$l.from([0x00]))]; case 4: res = _b.sent(); v = res[0] - 0x30; @@ -38093,9 +39299,9 @@ switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$k.alloc(0); - nullPrevout = Buffer$k.alloc(0); - defaultVersion = Buffer$k.alloc(4); + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); defaultVersion.writeUInt32LE(transactionVersion, 0); trustedInputs = []; regularOutputs = []; @@ -38105,11 +39311,11 @@ startTime = Date.now(); targetTransaction = { inputs: [], - timestamp: Buffer$k.alloc(0), + timestamp: Buffer$l.alloc(0), version: defaultVersion }; getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$k.from(outputScriptHex, "hex"); + outputScript = Buffer$l.from(outputScriptHex, "hex"); _c.label = 1; case 1: _c.trys.push([1, 7, 8, 9]); @@ -38122,15 +39328,15 @@ return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; case 3: trustedInput = _c.sent(); - sequence = Buffer$k.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" ? input[3] : DEFAULT_SEQUENCE, 0); trustedInputs.push({ trustedInput: false, value: segwit - ? Buffer$k.from(trustedInput, "hex") - : Buffer$k.from(trustedInput, "hex").slice(4, 4 + 0x24), + ? Buffer$l.from(trustedInput, "hex") + : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), sequence: sequence }); _c.label = 4; @@ -38158,7 +39364,7 @@ case 9: // Pre-build the target transaction for (i = 0; i < inputs.length; i++) { - sequence = Buffer$k.alloc(4); + sequence = Buffer$l.alloc(4); sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" ? inputs[i][3] : DEFAULT_SEQUENCE, 0); @@ -38183,12 +39389,12 @@ if (!(i < inputs.length)) return [3 /*break*/, 19]; input = inputs[i]; script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$k.from(input[2], "hex") + ? Buffer$l.from(input[2], "hex") : regularOutputs[i].script; pseudoTX = Object.assign({}, targetTransaction); pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$k.alloc(4); + pseudoTX.timestamp = Buffer$l.alloc(4); pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); } if (segwit) { @@ -38318,8 +39524,8 @@ return [4 /*yield*/, this.derivatePath(path)]; case 2: accountDerivation = _b.sent(); - fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$k.from(parentDerivation.publicKey, "hex"))); - xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$k.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$k.from(accountDerivation.publicKey, "hex"))); + fingerprint = makeFingerprint(compressPublicKeySECP256(Buffer$l.from(parentDerivation.publicKey, "hex"))); + xpub = makeXpub(xpubVersion, pathElements.length, fingerprint, pathElements[pathElements.length - 1], Buffer$l.from(accountDerivation.chainCode, "hex"), compressPublicKeySECP256(Buffer$l.from(accountDerivation.publicKey, "hex"))); return [2 /*return*/, xpub]; } }); @@ -38437,29 +39643,29 @@ return hash160(compressedPubKey).slice(0, 4); } function asBufferUInt32BE(n) { - var buf = Buffer$k.allocUnsafe(4); + var buf = Buffer$l.allocUnsafe(4); buf.writeUInt32BE(n, 0); return buf; } var compressPublicKeySECP256 = function (publicKey) { - return Buffer$k.concat([ - Buffer$k.from([0x02 + (publicKey[64] & 0x01)]), + return Buffer$l.concat([ + Buffer$l.from([0x02 + (publicKey[64] & 0x01)]), publicKey.slice(1, 33), ]); }; function makeXpub(version, depth, parentFingerprint, index, chainCode, pubKey) { var indexBuffer = asBufferUInt32BE(index); indexBuffer[0] |= 0x80; - var extendedKeyBytes = Buffer$k.concat([ + var extendedKeyBytes = Buffer$l.concat([ asBufferUInt32BE(version), - Buffer$k.from([depth]), + Buffer$l.from([depth]), parentFingerprint, indexBuffer, chainCode, pubKey, ]); var checksum = hash256(extendedKeyBytes).slice(0, 4); - return bs58.encode(Buffer$k.concat([extendedKeyBytes, checksum])); + return bs58.encode(Buffer$l.concat([extendedKeyBytes, checksum])); } function sha256(buffer) { return sha$3("sha256").update(buffer).digest(); @@ -38506,7 +39712,7 @@ } MerkleMap.prototype.commitment = function () { // returns a buffer between 65 and 73 (included) bytes long - return Buffer$k.concat([ + return Buffer$l.concat([ createVarint(this.keys.length), this.keysTree.getRoot(), this.valuesTree.getRoot(), @@ -38604,7 +39810,7 @@ } return v; }); - var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$k.from(k, "hex"); }); + var sortedKeys = sortedKeysStrings.map(function (k) { return Buffer$l.from(k, "hex"); }); var merkleMap = new MerkleMap(sortedKeys, values); return merkleMap; }; @@ -38685,9 +39891,9 @@ return _this; } YieldCommand.prototype.execute = function (request) { - this.results.push(Buffer$k.from(request.subarray(1))); + this.results.push(Buffer$l.from(request.subarray(1))); this.progressCallback(); - return Buffer$k.from(""); + return Buffer$l.from(""); }; return YieldCommand; }(ClientCommand)); @@ -38701,7 +39907,7 @@ return _this; } GetPreimageCommand.prototype.execute = function (request) { - var req = Buffer$k.from(request.subarray(1)); + var req = Buffer$l.from(request.subarray(1)); // we expect no more data to read if (req.length != 1 + 32) { throw new Error("Invalid request, unexpected trailing data"); @@ -38710,7 +39916,7 @@ throw new Error("Unsupported request, the first byte should be 0"); } // read the hash - var hash = Buffer$k.alloc(32); + var hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { hash[i] = req[1 + i]; } @@ -38724,13 +39930,13 @@ var payload_size = Math.min(max_payload_size, known_preimage.length); if (payload_size < known_preimage.length) { for (var i = payload_size; i < known_preimage.length; i++) { - this.queue.push(Buffer$k.from([known_preimage[i]])); + this.queue.push(Buffer$l.from([known_preimage[i]])); } } - return Buffer$k.concat([ + return Buffer$l.concat([ preimage_len_varint, - Buffer$k.from([payload_size]), - Buffer$k.from(known_preimage.subarray(0, payload_size)), + Buffer$l.from([payload_size]), + Buffer$l.from(known_preimage.subarray(0, payload_size)), ]); } throw Error("Requested unknown preimage for: " + req_hash_hex); @@ -38748,7 +39954,7 @@ } GetMerkleLeafProofCommand.prototype.execute = function (request) { var _a; - var req = Buffer$k.from(request.subarray(1)); + var req = Buffer$l.from(request.subarray(1)); if (req.length < 32 + 1 + 1) { throw new Error("Invalid request, expected at least 34 bytes"); } @@ -38781,10 +39987,10 @@ if (n_leftover_elements > 0) { (_a = this.queue).push.apply(_a, __spreadArray$1([], __read$1(proof.slice(-n_leftover_elements)), false)); } - return Buffer$k.concat(__spreadArray$1([ + return Buffer$l.concat(__spreadArray$1([ mt.getLeafHash(leaf_index), - Buffer$k.from([proof.length]), - Buffer$k.from([n_response_elements]) + Buffer$l.from([proof.length]), + Buffer$l.from([n_response_elements]) ], __read$1(proof.slice(0, n_response_elements)), false)); }; return GetMerkleLeafProofCommand; @@ -38798,18 +40004,18 @@ return _this; } GetMerkleLeafIndexCommand.prototype.execute = function (request) { - var req = Buffer$k.from(request.subarray(1)); + var req = Buffer$l.from(request.subarray(1)); if (req.length != 32 + 32) { throw new Error("Invalid request, unexpected trailing data"); } // read the root hash - var root_hash = Buffer$k.alloc(32); + var root_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { root_hash[i] = req.readUInt8(i); } var root_hash_hex = root_hash.toString("hex"); // read the leaf hash - var leef_hash = Buffer$k.alloc(32); + var leef_hash = Buffer$l.alloc(32); for (var i = 0; i < 32; i++) { leef_hash[i] = req.readUInt8(32 + i); } @@ -38827,7 +40033,7 @@ break; } } - return Buffer$k.concat([Buffer$k.from([found]), createVarint(leaf_index)]); + return Buffer$l.concat([Buffer$l.from([found]), createVarint(leaf_index)]); }; return GetMerkleLeafIndexCommand; }(ClientCommand)); @@ -38854,9 +40060,9 @@ var max_elements = Math.floor(253 / element_len); var n_returned_elements = Math.min(max_elements, this.queue.length); var returned_elements = this.queue.splice(0, n_returned_elements); - return Buffer$k.concat(__spreadArray$1([ - Buffer$k.from([n_returned_elements]), - Buffer$k.from([element_len]) + return Buffer$l.concat(__spreadArray$1([ + Buffer$l.from([n_returned_elements]), + Buffer$l.from([element_len]) ], __read$1(returned_elements), false)); }; return GetMoreElementsCommand; @@ -38919,7 +40125,7 @@ try { for (var elements_1 = __values$3(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) { var el = elements_1_1.value; - var preimage = Buffer$k.concat([Buffer$k.from([0]), el]); + var preimage = Buffer$l.concat([Buffer$l.from([0]), el]); this.addKnownPreimage(preimage); } } @@ -39058,8 +40264,8 @@ if (pathElements.length > 6) { throw new Error("Path too long. At most 6 levels allowed."); } - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_PUBKEY, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), pathElementsToBuffer(pathElements), ]))]; case 1: @@ -39083,15 +40289,15 @@ throw new Error("Invalid HMAC length"); } clientInterpreter = new ClientCommandInterpreter(function () { }); - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); - addressIndexBuffer = Buffer$k.alloc(4); + addressIndexBuffer = Buffer$l.alloc(4); addressIndexBuffer.writeUInt32BE(addressIndex, 0); - return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$k.concat([ - Buffer$k.from(display ? [1] : [0]), + return [4 /*yield*/, this.makeRequest(BitcoinIns.GET_WALLET_ADDRESS, Buffer$l.concat([ + Buffer$l.from(display ? [1] : [0]), walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), - Buffer$k.from([change]), + walletHMAC || Buffer$l.alloc(32, 0), + Buffer$l.from([change]), addressIndexBuffer, ]), clientInterpreter)]; case 1: @@ -39114,7 +40320,7 @@ } clientInterpreter = new ClientCommandInterpreter(progressCallback); // prepare ClientCommandInterpreter - clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$k.from(k, "ascii"); })); + clientInterpreter.addKnownList(walletPolicy.keys.map(function (k) { return Buffer$l.from(k, "ascii"); })); clientInterpreter.addKnownPreimage(walletPolicy.serialize()); clientInterpreter.addKnownMapping(merkelizedPsbt.globalMerkleMap); try { @@ -39147,14 +40353,14 @@ inputMapsRoot = new Merkle(merkelizedPsbt.inputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); clientInterpreter.addKnownList(merkelizedPsbt.outputMapCommitments); outputMapsRoot = new Merkle(merkelizedPsbt.outputMapCommitments.map(function (m) { return hashLeaf(m); })).getRoot(); - return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$k.concat([ + return [4 /*yield*/, this.makeRequest(BitcoinIns.SIGN_PSBT, Buffer$l.concat([ merkelizedPsbt.getGlobalKeysValuesRoot(), createVarint(merkelizedPsbt.getGlobalInputCount()), inputMapsRoot, createVarint(merkelizedPsbt.getGlobalOutputCount()), outputMapsRoot, walletPolicy.getWalletId(), - walletHMAC || Buffer$k.alloc(32, 0), + walletHMAC || Buffer$l.alloc(32, 0), ]), clientInterpreter)]; case 1: _h.sent(); @@ -39181,7 +40387,7 @@ AppClient.prototype.getMasterFingerprint = function () { return __awaiter$4(this, void 0, void 0, function () { return __generator$4(this, function (_a) { - return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$k.from([]))]; + return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; }); }); }; @@ -39234,15 +40440,15 @@ var outputs = []; var witness = false; var offset = 0; - var timestamp = Buffer$k.alloc(0); - var nExpiryHeight = Buffer$k.alloc(0); - var nVersionGroupId = Buffer$k.alloc(0); - var extraData = Buffer$k.alloc(0); + var timestamp = Buffer$l.alloc(0); + var nExpiryHeight = Buffer$l.alloc(0); + var nVersionGroupId = Buffer$l.alloc(0); + var extraData = Buffer$l.alloc(0); var isDecred = additionals.includes("decred"); - var transaction = Buffer$k.from(transactionHex, "hex"); + var transaction = Buffer$l.from(transactionHex, "hex"); var version = transaction.slice(offset, offset + 4); - var overwinter = version.equals(Buffer$k.from([0x03, 0x00, 0x00, 0x80])) || - version.equals(Buffer$k.from([0x04, 0x00, 0x00, 0x80])); + var overwinter = version.equals(Buffer$l.from([0x03, 0x00, 0x00, 0x80])) || + version.equals(Buffer$l.from([0x04, 0x00, 0x00, 0x80])); offset += 4; if (!hasTimestamp && isSegwitSupported && @@ -39265,8 +40471,8 @@ for (var i = 0; i < numberInputs; i++) { var prevout = transaction.slice(offset, offset + 36); offset += 36; - var script = Buffer$k.alloc(0); - var tree = Buffer$k.alloc(0); + var script = Buffer$l.alloc(0); + var tree = Buffer$l.alloc(0); //No script for decred, it has a witness if (!isDecred) { varint = getVarint(transaction, offset); @@ -40196,7 +41402,7 @@ * @return a Promise of response buffer */ this.send = function (cla, ins, p1, p2, data, statusList) { - if (data === void 0) { data = Buffer$k.alloc(0); } + if (data === void 0) { data = Buffer$l.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes.OK]; } return __awaiter$2(_this, void 0, void 0, function () { var response, sw; @@ -40206,9 +41412,9 @@ if (data.length >= 256) { throw new TransportError("data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig"); } - return [4 /*yield*/, this.exchange(Buffer$k.concat([ - Buffer$k.from([cla, ins, p1, p2]), - Buffer$k.from([data.length]), + return [4 /*yield*/, this.exchange(Buffer$l.concat([ + Buffer$l.from([cla, ins, p1, p2]), + Buffer$l.from([data.length]), data, ]))]; case 1: @@ -40429,12 +41635,12 @@ var errors_1 = require$$0; var Tag = 0x05; function asUInt16BE(value) { - var b = Buffer$k.alloc(2); + var b = Buffer$l.alloc(2); b.writeUInt16BE(value, 0); return b; } var initialAcc = { - data: Buffer$k.alloc(0), + data: Buffer$l.alloc(0), dataLength: 0, sequence: 0 }; @@ -40444,21 +41650,21 @@ var createHIDframing = function (channel, packetSize) { return { makeBlocks: function (apdu) { - var data = Buffer$k.concat([asUInt16BE(apdu.length), apdu]); + var data = Buffer$l.concat([asUInt16BE(apdu.length), apdu]); var blockSize = packetSize - 5; var nbBlocks = Math.ceil(data.length / blockSize); - data = Buffer$k.concat([ + data = Buffer$l.concat([ data, - Buffer$k.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + Buffer$l.alloc(nbBlocks * blockSize - data.length + 1).fill(0), ]); var blocks = []; for (var i = 0; i < nbBlocks; i++) { - var head = Buffer$k.alloc(5); + var head = Buffer$l.alloc(5); head.writeUInt16BE(channel, 0); head.writeUInt8(Tag, 2); head.writeUInt16BE(i, 3); var chunk = data.slice(i * blockSize, (i + 1) * blockSize); - blocks.push(Buffer$k.concat([head, chunk])); + blocks.push(Buffer$l.concat([head, chunk])); } return blocks; }, @@ -40478,7 +41684,7 @@ } sequence++; var chunkData = chunk.slice(acc ? 5 : 7); - data = Buffer$k.concat([data, chunkData]); + data = Buffer$l.concat([data, chunkData]); if (data.length > dataLength) { data = data.slice(0, dataLength); } @@ -40935,7 +42141,7 @@ return [4 /*yield*/, this.device.transferIn(endpointNumber, packetSize)]; case 5: r = _b.sent(); - buffer = Buffer$k.from(r.data.buffer); + buffer = Buffer$l.from(r.data.buffer); acc = framing.reduceResponse(acc, buffer); return [3 /*break*/, 4]; case 6: @@ -41040,6 +42246,5 @@ window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; -//window.TransportSpeculos = NewLedger.SpeculosTransport.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From cd83483ea95973cde6a331bc41b52988ca526d62 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 11:09:19 +1100 Subject: [PATCH 64/78] wtf --- js/ledger.js | 4037 +++++++++++++++++++++++++------------------------- 1 file changed, 2020 insertions(+), 2017 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 94409683..13e4770a 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -5023,6 +5023,8 @@ var readableBrowser = {exports: {}}; + var _registry = {}; + // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js @@ -5732,7 +5734,7 @@ 'default': _nodeResolve_empty }); - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + var require$$4 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); 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; } @@ -5749,7 +5751,7 @@ var _require$2 = buffer, Buffer$k = _require$2.Buffer; - var _require2 = require$$3, + var _require2 = require$$4, inspect$1 = _require2.inspect; var custom = inspect$1 && inspect$1.custom || 'inspect'; @@ -6201,2542 +6203,2536 @@ getHighWaterMark: getHighWaterMark$2 }; - /** - * Module exports. - */ + var string_decoder = {}; - var browser$5 = deprecate$1; + /**/ - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ + var Buffer$j = safeBuffer.exports.Buffer; + /**/ - function deprecate$1 (fn, msg) { - if (config('noDeprecation')) { - return fn; + var isEncoding = Buffer$j.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; } + }; - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; + 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; } - return fn.apply(this, arguments); } - - return deprecated; } - - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!commonjsGlobal.localStorage) return false; - } catch (_) { - return false; - } - var val = commonjsGlobal.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === '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$j.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; } - var _stream_writable = Writable$2; - // there will be only 2 of these for each stream - - - function CorkedRequest$1(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; + function StringDecoder$2(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$j.allocUnsafe(nb); } - /* */ - - /**/ - - - var Duplex$4; - /**/ - Writable$2.WritableState = WritableState$1; - /**/ - - var internalUtil = { - deprecate: browser$5 + StringDecoder$2.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 || ''; }; - /**/ - - /**/ - - var Stream$2 = streamBrowser; - /**/ + StringDecoder$2.prototype.end = utf8End; - var Buffer$j = buffer.Buffer; + // Returns only complete characters in a Buffer + StringDecoder$2.prototype.text = utf8Text; - var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder$2.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; + }; - function _uint8ArrayToBuffer$1(chunk) { - return Buffer$j.from(chunk); + // 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; } - function _isUint8Array$1(obj) { - return Buffer$j.isBuffer(obj) || obj instanceof OurUint8Array$1; + // 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; } - var destroyImpl$1 = destroy_1; + // 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'; + } + } + } + } - var _require$1 = state, - getHighWaterMark$1 = _require$1.getHighWaterMark; + // 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); + 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; + } - var _require$codes$3 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK$1 = _require$codes$3.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes$3.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED$1 = _require$codes$3.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes$3.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes$3.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes$3.ERR_UNKNOWN_ENCODING; + // 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); + } - var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + // 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; + } - inherits_browser.exports(Writable$2, Stream$2); + // 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); + } - function nop$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 WritableState$1(options, stream, isDuplex) { - Duplex$4 = Duplex$4 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + 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); + } - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$4; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + 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; + } - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } - this.highWaterMark = getHighWaterMark$1(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } - this.finalCalled = false; // drain event flag. + var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - this.needDrain = false; // at the start of calling end() + function once$1(callback) { + var called = false; + return function () { + if (called) return; + called = true; - this.ending = false; // when end() has been called, and returned + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - this.ended = false; // when 'finish' is emitted + callback.apply(this, args); + }; + } - this.finished = false; // has it been destroyed + function noop$1() {} - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. + function isRequest$1(stream) { + return stream.setHeader && typeof stream.abort === 'function'; + } - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + function eos$1(stream, opts, callback) { + if (typeof opts === 'function') return eos$1(stream, null, opts); + if (!opts) opts = {}; + callback = once$1(callback || noop$1); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - this.length = 0; // a flag to see when we're in the middle of a write. + var writableEnded = stream._writableState && stream._writableState.finished; - this.writing = false; // when true all writes will be buffered until .uncork() call + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. + var readableEnded = stream._readableState && stream._readableState.endEmitted; - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + var onerror = function onerror(err) { + callback.call(stream, err); + }; - this.onwrite = function (er) { - onwrite$1(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } - this.writecb = null; // the amount that is being written when _write is called. + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams + if (isRequest$1(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - this.prefinished = false; // True if the error was already emitted and should not be thrown again + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + } - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + var endOfStream = eos$1; - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + var _Object$setPrototypeO; - this.autoDestroy = !!options.autoDestroy; // count buffered requests + function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + var finished = endOfStream; - this.corkedRequestsFree = new CorkedRequest$1(this); + var kLastResolve = Symbol('lastResolve'); + var kLastReject = Symbol('lastReject'); + var kError = Symbol('error'); + var kEnded = Symbol('ended'); + var kLastPromise = Symbol('lastPromise'); + var kHandlePromise = Symbol('handlePromise'); + var kStream = Symbol('stream'); + + function createIterResult(value, done) { + return { + value: value, + done: done + }; } - WritableState$1.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; - while (current) { - out.push(current); - current = current.next; - } + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' - return out; - }; - - (function () { - try { - Object.defineProperty(WritableState$1.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} - })(); // Test _writableState for inheritance to account for Duplex streams, - // whose prototype chain only points to Readable. + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + nextTick(readAndResolve, iter); + } - var realHasInstance; + function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } - if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable$2, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable$2) return false; - return object && object._writableState instanceof WritableState$1; - } - }); - } else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; + iter[kHandlePromise](resolve, reject); + }, reject); }; } - function Writable$2(options) { - Duplex$4 = Duplex$4 || _stream_duplex; // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 + var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, - var isDuplex = this instanceof Duplex$4; - if (!isDuplex && !realHasInstance.call(Writable$2, this)) return new Writable$2(options); - this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + next: function next() { + var _this = this; - this.writable = true; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } + if (error !== null) { + return Promise.reject(error); + } - Stream$2.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time - Writable$2.prototype.pipe = function () { - errorOrDestroy$1(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd$1(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + var lastPromise = this[kLastPromise]; + var promise; - errorOrDestroy$1(stream, er); - nextTick(cb, er); - } // Checks that a user-supplied chunk is valid, especially for the particular - // mode the stream is in. Currently this means that `null` is never accepted - // and undefined/non-string values are only allowed in object mode. + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } - function validChunk$1(stream, state, chunk, cb) { - var er; + promise = new Promise(this[kHandlePromise]); + } - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer'], chunk); + this[kLastPromise] = promise; + return promise; } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; - if (er) { - errorOrDestroy$1(stream, er); - nextTick(cb, er); - return false; - } + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } - return true; - } + resolve(createIterResult(undefined, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); - Writable$2.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { + var _Object$create; - var isBuf = !state.objectMode && _isUint8Array$1(chunk); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); - if (isBuf && !Buffer$j.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer$1(chunk); - } + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop$1; - if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); - } - return ret; - }; + iterator[kError] = err; + return; + } - Writable$2.prototype.cork = function () { - this._writableState.corked++; + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; - Writable$2.prototype.uncork = function () { - var state = this._writableState; + var async_iterator = createReadableStreamAsyncIterator$1; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); - } + var fromBrowser = function () { + throw new Error('Readable.from is not available in the browser') }; - Writable$2.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; + const Registry$4 = _registry; + Registry$4.Readable = Readable$1; + + Readable$1.ReadableState = ReadableState$1; + /**/ + + events.exports.EventEmitter; + + var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; }; + /**/ - Object.defineProperty(Writable$2.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); + /**/ - function decodeChunk$1(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$j.from(chunk, encoding); - } - return chunk; + var Stream$2 = streamBrowser; + /**/ + + + var Buffer$i = buffer.Buffer; + + var OurUint8Array$1 = commonjsGlobal.Uint8Array || function () {}; + + function _uint8ArrayToBuffer$1(chunk) { + return Buffer$i.from(chunk); } - Object.defineProperty(Writable$2.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - - function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk$1(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } + function _isUint8Array$1(obj) { + return Buffer$i.isBuffer(obj) || obj instanceof OurUint8Array$1; + } + /**/ - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + var debugUtil = require$$4; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + var debug$5; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } + if (debugUtil && debugUtil.debuglog) { + debug$5 = debugUtil.debuglog('stream'); + } else { + debug$5 = function debug() {}; + } + /**/ - state.bufferedRequestCount += 1; - } else { - doWrite$1(stream, state, false, len, chunk, encoding, cb); - } - return ret; - } + var BufferList$1 = buffer_list; - function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } + var destroyImpl$1 = destroy_1; - function onwriteError$1(stream, state, sync, er, cb) { - --state.pendingcb; + var _require$1 = state, + getHighWaterMark$1 = _require$1.getHighWaterMark; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - nextTick(cb, er); // this can emit finish, and it will always happen - // after error + var _require$codes$3 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE$1 = _require$codes$3.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes$3.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED$2 = _require$codes$3.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$3.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - nextTick(finishMaybe$1, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy$1(stream, er); // this can emit finish, but finish must - // always follow error - finishMaybe$1(stream, state); - } - } + var StringDecoder$1; + var createReadableStreamAsyncIterator; + var from; - function onwriteStateUpdate$1(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + inherits_browser.exports(Readable$1, Stream$2); - function onwrite$1(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); - onwriteStateUpdate$1(state); - if (er) onwriteError$1(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish$1(state) || stream.destroyed; + var errorOrDestroy$1 = destroyImpl$1.errorOrDestroy; + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer$1(stream, state); - } + function prependListener$1(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. - if (sync) { - nextTick(afterWrite$1, stream, state, finished, cb); - } else { - afterWrite$1(stream, state, finished, cb); - } - } + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } - function afterWrite$1(stream, state, finished, cb) { - if (!finished) onwriteDrain$1(stream, state); - state.pendingcb--; - cb(); - finishMaybe$1(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. + function ReadableState$1(options, stream, isDuplex) { + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Registry$4.Duplex; // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away - function onwriteDrain$1(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark$1(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() - function clearBuffer$1(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + this.buffer = new BufferList$1(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - buffer.allBuffers = allBuffers; - doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - state.pendingcb++; - state.lastBufferedRequest = null; + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest$1(state); - } + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite$1(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - if (state.writing) { - break; - } - } + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - if (entry === null) state.lastBufferedRequest = null; - } + this.readingMore = false; + this.decoder = null; + this.encoding = null; - state.bufferedRequest = entry; - state.bufferProcessing = false; + if (options.encoding) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + this.decoder = new StringDecoder$1(options.encoding); + this.encoding = options.encoding; + } } - Writable$2.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED$2('_write()')); - }; + function Readable$1(options) { + if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 - Writable$2.prototype._writev = null; + var isDuplex = this instanceof Registry$4.Duplex; + this._readableState = new ReadableState$1(options, this, isDuplex); // legacy - Writable$2.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + this.readable = true; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. + Stream$2.call(this); + } - - if (!state.ending) endWritable$1(this, state, cb); - return this; - }; - - Object.defineProperty(Writable$2.prototype, 'writableLength', { + Object.defineProperty(Readable$1.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { - return this._writableState.length; + if (this._readableState === undefined) { + return false; + } + + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; } }); + Readable$1.prototype.destroy = destroyImpl$1.destroy; + Readable$1.prototype._undestroy = destroyImpl$1.undestroy; - function needFinish$1(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } + Readable$1.prototype._destroy = function (err, cb) { + cb(err); + }; // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. - function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - errorOrDestroy$1(stream, err); - } + Readable$1.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe$1(stream, state); - }); - } + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; - function prefinish$2(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); + if (encoding !== state.encoding) { + chunk = Buffer$i.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; } + } else { + skipChunkCheck = true; } - } - function finishMaybe$1(stream, state) { - var need = needFinish$1(state); + return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); + }; // Unshift should *always* be something directly out of read() - if (need) { - prefinish$2(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); + Readable$1.prototype.unshift = function (chunk) { + return readableAddChunk$1(this, chunk, null, true, false); + }; - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; + function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug$5('readableAddChunk', chunk); + var state = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); + if (chunk === null) { + state.reading = false; + onEofChunk$1(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); + + if (er) { + errorOrDestroy$1(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$i.prototype) { + chunk = _uint8ArrayToBuffer$1(chunk); + } + + if (addToFront) { + if (state.endEmitted) errorOrDestroy$1(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy$1(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); + } else { + addChunk(stream, state, chunk, false); } } + } else if (!addToFront) { + state.reading = false; + maybeReadMore$1(stream, state); } - } + } // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. - return need; - } - function endWritable$1(stream, state, cb) { - state.ending = true; - finishMaybe$1(stream, state); + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } - if (cb) { - if (state.finished) nextTick(cb);else stream.once('finish', cb); + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable$1(stream); } - state.ended = true; - stream.writable = false; + maybeReadMore$1(stream, state); } - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. + function chunkInvalid$1(state, chunk) { + var er; + if (!_isUint8Array$1(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE$1('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } - state.corkedRequestsFree.next = corkReq; + return er; } - Object.defineProperty(Writable$2.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } + Readable$1.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; // backwards compatibility. - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + Readable$1.prototype.setEncoding = function (enc) { + if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; + var decoder = new StringDecoder$1(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - this._writableState.destroyed = value; + var p = this._readableState.buffer.head; + var content = ''; + + while (p !== null) { + content += decoder.write(p.data); + p = p.next; } - }); - Writable$2.prototype.destroy = destroyImpl$1.destroy; - Writable$2.prototype._undestroy = destroyImpl$1.undestroy; - Writable$2.prototype._destroy = function (err, cb) { - cb(err); - }; + this._readableState.buffer.clear(); - /**/ + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; // Don't raise the hwm > 1GB - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - } + var MAX_HWM$1 = 0x40000000; - return keys; - }; - /**/ + function computeNewHighWaterMark$1(n) { + if (n >= MAX_HWM$1) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM$1; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } // This function is designed to be inlinable, so please take care when making + // changes to the function body. - var _stream_duplex = Duplex$3; - var Readable$2 = _stream_readable; + function howMuchToRead$1(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; - var Writable$1 = _stream_writable; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. - inherits_browser.exports(Duplex$3, Readable$2); - { - // Allow the keys array to be GC'ed. - var keys$1 = objectKeys(Writable$1.prototype); + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); + if (n <= state.length) return n; // Don't have enough - for (var v$1 = 0; v$1 < keys$1.length; v$1++) { - var method$1 = keys$1[v$1]; - if (!Duplex$3.prototype[method$1]) Duplex$3.prototype[method$1] = Writable$1.prototype[method$1]; + if (!state.ended) { + state.needReadable = true; + return 0; } - } - - function Duplex$3(options) { - if (!(this instanceof Duplex$3)) return new Duplex$3(options); - Readable$2.call(this, options); - Writable$1.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; + return state.length; + } // you can override either this method, or the async _read(n) below. - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend$1); - } - } - } - Object.defineProperty(Duplex$3.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex$3.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); // the no-half-open enforcer + Readable$1.prototype.read = function (n) { + debug$5('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. - function onend$1() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug$5('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); + return null; + } - nextTick(onEndNT$1, this); - } + n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. - function onEndNT$1(self) { - self.end(); - } + if (n === 0 && state.ended) { + if (state.length === 0) endReadable$1(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. - Object.defineProperty(Duplex$3.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + var doRead = state.needReadable; + debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$5('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - var string_decoder = {}; + if (state.ended || state.reading) { + doRead = false; + debug$5('reading or ended', doRead); + } else if (doRead) { + debug$5('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. - /**/ + if (state.length === 0) state.needReadable = true; // call internal read method - var Buffer$i = safeBuffer.exports.Buffer; - /**/ + this._read(state.highWaterMark); - var isEncoding = Buffer$i.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; - } - }; + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. - 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; - } + if (!state.reading) n = howMuchToRead$1(nOrig, state); } - } - // 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$i.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. - var StringDecoder_1 = string_decoder.StringDecoder = StringDecoder$2; - function StringDecoder$2(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$i.allocUnsafe(nb); - } + var ret; + if (n > 0) ret = fromList$1(n, state);else ret = null; - StringDecoder$2.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; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; - }; - - StringDecoder$2.prototype.end = utf8End; - - // Returns only complete characters in a Buffer - StringDecoder$2.prototype.text = utf8Text; - - // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - StringDecoder$2.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); + state.length -= n; + state.awaitDrain = 0; } - 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; - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - // 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'; - } - } + if (nOrig !== n && state.ended) endReadable$1(this); } - } - // 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); - 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; - } + if (ret !== null) this.emit('data', ret); + return ret; + }; - // 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); - } + function onEofChunk$1(stream, state) { + debug$5('onEofChunk'); + if (state.ended) return; - // 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; - } + if (state.decoder) { + var chunk = state.decoder.end(); - // 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); - } + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - 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; - } + state.ended = true; - 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]; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable$1(stream); } 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) : ''; - } - - var ERR_STREAM_PREMATURE_CLOSE = errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE; - - function once$1(callback) { - var called = false; - return function () { - if (called) return; - called = true; + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_$1(stream); } + } + } // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. - callback.apply(this, args); - }; - } - function noop$1() {} + function emitReadable$1(stream) { + var state = stream._readableState; + debug$5('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; - function isRequest$1(stream) { - return stream.setHeader && typeof stream.abort === 'function'; + if (!state.emittedReadable) { + debug$5('emitReadable', state.flowing); + state.emittedReadable = true; + nextTick(emitReadable_$1, stream); + } } - function eos$1(stream, opts, callback) { - if (typeof opts === 'function') return eos$1(stream, null, opts); - if (!opts) opts = {}; - callback = once$1(callback || noop$1); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + function emitReadable_$1(stream) { + var state = stream._readableState; + debug$5('emitReadable_', state.destroyed, state.length, state.ended); - var onerror = function onerror(err) { - callback.call(stream, err); - }; + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. - var onclose = function onclose() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow$1(stream); + } // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + function maybeReadMore$1(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_$1, stream, state); + } + } - if (isRequest$1(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); + function maybeReadMore_$1(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug$5('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) // didn't get any data, stop spinning. + break; } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; - } + state.readingMore = false; + } // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. - var endOfStream = eos$1; - var _Object$setPrototypeO; + Readable$1.prototype._read = function (n) { + errorOrDestroy$1(this, new ERR_METHOD_NOT_IMPLEMENTED$2('_read()')); + }; - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + Readable$1.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - var finished = endOfStream; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; - var kLastResolve = Symbol('lastResolve'); - var kLastReject = Symbol('lastReject'); - var kError = Symbol('error'); - var kEnded = Symbol('ended'); - var kLastPromise = Symbol('lastPromise'); - var kHandlePromise = Symbol('handlePromise'); - var kStream = Symbol('stream'); + case 1: + state.pipes = [state.pipes, dest]; + break; - function createIterResult(value, done) { - return { - value: value, - done: done - }; - } + default: + state.pipes.push(dest); + break; + } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; + state.pipesCount += 1; + debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' + function onunpipe(readable, unpipeInfo) { + debug$5('onunpipe'); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } - } - function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - nextTick(readAndResolve, iter); - } + function onend() { + debug$5('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. - function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - iter[kHandlePromise](resolve, reject); - }, reject); - }; - } + var ondrain = pipeOnDrain$1(src); + dest.on('drain', ondrain); + var cleanedUp = false; - var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, + function cleanup() { + debug$5('cleanup'); // cleanup event handlers once the pipe is broken - next: function next() { - var _this = this; + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (error !== null) { - return Promise.reject(error); - } + src.on('data', ondata); - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } + function ondata(chunk) { + debug$5('ondata'); + var ret = dest.write(chunk); + debug$5('dest.write', ret); - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { + debug$5('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - var lastPromise = this[kLastPromise]; - var promise; + function onerror(er) { + debug$5('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy$1(dest, er); + } // Make sure our error handler is attached before userland ones. - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } + prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - promise = new Promise(this[kHandlePromise]); - } + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } - this[kLastPromise] = promise; - return promise; + dest.once('close', onclose); + + function onfinish() { + debug$5('onfinish'); + dest.removeListener('close', onclose); + unpipe(); } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } + dest.once('finish', onfinish); - resolve(createIterResult(undefined, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); + function unpipe() { + debug$5('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to - var createReadableStreamAsyncIterator$1 = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); + dest.emit('pipe', src); // start the flow if it hasn't been started already. - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error + if (!state.flowing) { + debug$5('pipe resume'); + src.resume(); + } - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } + return dest; + }; - iterator[kError] = err; - return; + function pipeOnDrain$1(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug$5('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow$1(src); } + }; + } - var resolve = iterator[kLastResolve]; + Readable$1.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } + if (state.pipesCount === 0) return this; // just one destination. most common case. - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; - }; + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; // got a match. - var async_iterator = createReadableStreamAsyncIterator$1; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. - var fromBrowser = function () { - throw new Error('Readable.from is not available in the browser') - }; - var _stream_readable = Readable$1; - /**/ + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - var Duplex$2; - /**/ + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } - Readable$1.ReadableState = ReadableState$1; - /**/ + return this; + } // try to find the right one. - events.exports.EventEmitter; - var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + var index = indexOf$1(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; + }; // set up data events if they are asked for + // Ensure readable listeners eventually get something - /**/ + Readable$1.prototype.on = function (ev, fn) { + var res = Stream$2.prototype.on.call(this, ev, fn); + var state = this._readableState; - var Stream$1 = streamBrowser; - /**/ + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug$5('on readable', state.length, state.reading); - var Buffer$h = buffer.Buffer; + if (state.length) { + emitReadable$1(this); + } else if (!state.reading) { + nextTick(nReadingNextTick$1, this); + } + } + } - var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; + return res; + }; - function _uint8ArrayToBuffer(chunk) { - return Buffer$h.from(chunk); - } + Readable$1.prototype.addListener = Readable$1.prototype.on; - function _isUint8Array(obj) { - return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; - } - /**/ + Readable$1.prototype.removeListener = function (ev, fn) { + var res = Stream$2.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } - var debugUtil = require$$3; + return res; + }; - var debug$5; + Readable$1.prototype.removeAllListeners = function (ev) { + var res = Stream$2.prototype.removeAllListeners.apply(this, arguments); - if (debugUtil && debugUtil.debuglog) { - debug$5 = debugUtil.debuglog('stream'); - } else { - debug$5 = function debug() {}; + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + nextTick(updateReadableListening, this); + } + + return res; + }; + + function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } } - /**/ + + function nReadingNextTick$1(self) { + debug$5('readable nexttick read 0'); + self.read(0); + } // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. - var BufferList$1 = buffer_list; + Readable$1.prototype.resume = function () { + var state = this._readableState; - var destroyImpl = destroy_1; + if (!state.flowing) { + debug$5('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - var _require = state, - getHighWaterMark = _require.getHighWaterMark; + state.flowing = !state.readableListening; + resume$1(this, state); + } - var _require$codes$2 = errorsBrowser.codes, - ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes$2.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes$2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. + state.paused = false; + return this; + }; + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_$1, stream, state); + } + } - var StringDecoder$1; - var createReadableStreamAsyncIterator; - var from; + function resume_$1(stream, state) { + debug$5('resume', state.reading); - inherits_browser.exports(Readable$1, Stream$1); + if (!state.reading) { + stream.read(0); + } - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + state.resumeScheduled = false; + stream.emit('resume'); + flow$1(stream); + if (state.flowing && !state.reading) stream.read(0); + } - function prependListener$1(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. + Readable$1.prototype.pause = function () { + debug$5('call pause flowing=%j', this._readableState.flowing); - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } + if (this._readableState.flowing !== false) { + debug$5('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } - function ReadableState$1(options, stream, isDuplex) { - Duplex$2 = Duplex$2 || _stream_duplex; - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. + this._readableState.paused = true; + return this; + }; - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex$2; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away + function flow$1(stream) { + var state = stream._readableState; + debug$5('flow', state.flowing); - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" + while (state.flowing && stream.read() !== null) { + } + } // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList$1(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. + Readable$1.prototype.wrap = function (stream) { + var _this = this; - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug$5('wrapped end'); - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') + _this.push(null); + }); + stream.on('data', function (chunk) { + debug$5('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - this.autoDestroy = !!options.autoDestroy; // has it been destroyed + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. + var ret = _this.push(chunk); - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + if (!ret) { + paused = true; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - this.decoder = new StringDecoder$1(options.encoding); - this.encoding = options.encoding; - } - } + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. - function Readable$1(options) { - Duplex$2 = Duplex$2 || _stream_duplex; - if (!(this instanceof Readable$1)) return new Readable$1(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex$2; - this._readableState = new ReadableState$1(options, this, isDuplex); // legacy + this._read = function (n) { + debug$5('wrapped _read', n); - this.readable = true; + if (paused) { + paused = false; + stream.resume(); + } + }; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + return this; + }; - Stream$1.call(this); + if (typeof Symbol === 'function') { + Readable$1.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = async_iterator; + } + + return createReadableStreamAsyncIterator(this); + }; } - Object.defineProperty(Readable$1.prototype, 'destroyed', { + Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); // exposed for testing purposes only. + Readable$1._fromList = fromList$1; + Object.defineProperty(Readable$1.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. - this._readableState.destroyed = value; + function fromList$1(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); } - }); - Readable$1.prototype.destroy = destroyImpl.destroy; - Readable$1.prototype._undestroy = destroyImpl.undestroy; + return ret; + } - Readable$1.prototype._destroy = function (err, cb) { - cb(err); - }; // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. + function endReadable$1(stream) { + var state = stream._readableState; + debug$5('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT$1, state, stream); + } + } + function endReadableNT$1(state, stream) { + debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - Readable$1.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; - if (encoding !== state.encoding) { - chunk = Buffer$h.from(chunk, encoding); - encoding = ''; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); } - - skipChunkCheck = true; } - } else { - skipChunkCheck = true; } + } - return readableAddChunk$1(this, chunk, encoding, false, skipChunkCheck); - }; // Unshift should *always* be something directly out of read() + if (typeof Symbol === 'function') { + Readable$1.from = function (iterable, opts) { + if (from === undefined) { + from = fromBrowser; + } + return from(Readable$1, iterable, opts); + }; + } - Readable$1.prototype.unshift = function (chunk) { - return readableAddChunk$1(this, chunk, null, true, false); - }; + function indexOf$1(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } - function readableAddChunk$1(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug$5('readableAddChunk', chunk); - var state = stream._readableState; + return -1; + } - if (chunk === null) { - state.reading = false; - onEofChunk$1(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid$1(state, chunk); + /** + * Module exports. + */ - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer$h.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } + var browser$5 = deprecate$1; - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; + /** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore$1(stream, state); - } else { - addChunk(stream, state, chunk, false); - } + function deprecate$1 (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); } - } else if (!addToFront) { - state.reading = false; - maybeReadMore$1(stream, state); + warned = true; } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - + return fn.apply(this, arguments); + } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); + return deprecated; } - function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable$1(stream); - } + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - maybeReadMore$1(stream, state); + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!commonjsGlobal.localStorage) return false; + } catch (_) { + return false; + } + var val = commonjsGlobal.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } - function chunkInvalid$1(state, chunk) { - var er; + const Registry$3 = _registry; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } + Registry$3.Writable = Writable$1; + // there will be only 2 of these for each stream - return er; - } - Readable$1.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; // backwards compatibility. + function CorkedRequest$1(state) { + var _this = this; + this.next = null; + this.entry = null; - Readable$1.prototype.setEncoding = function (enc) { - if (!StringDecoder$1) StringDecoder$1 = string_decoder.StringDecoder; - var decoder = new StringDecoder$1(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: + /**/ - var p = this._readableState.buffer.head; - var content = ''; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } + /**/ - this._readableState.buffer.clear(); + Writable$1.WritableState = WritableState$1; + /**/ - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; // Don't raise the hwm > 1GB + var internalUtil = { + deprecate: browser$5 + }; + /**/ + /**/ - var MAX_HWM$1 = 0x40000000; + var Stream$1 = streamBrowser; + /**/ - function computeNewHighWaterMark$1(n) { - if (n >= MAX_HWM$1) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM$1; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. + var Buffer$h = buffer.Buffer; + var OurUint8Array = commonjsGlobal.Uint8Array || function () {}; - function howMuchToRead$1(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + function _uint8ArrayToBuffer(chunk) { + return Buffer$h.from(chunk); + } - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. + function _isUint8Array(obj) { + return Buffer$h.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = destroy_1; - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark$1(n); - if (n <= state.length) return n; // Don't have enough + var _require = state, + getHighWaterMark = _require.getHighWaterMark; - if (!state.ended) { - state.needReadable = true; - return 0; - } + var _require$codes$2 = errorsBrowser.codes, + ERR_INVALID_ARG_TYPE = _require$codes$2.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED$1 = _require$codes$2.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK$1 = _require$codes$2.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes$2.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED$1 = _require$codes$2.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes$2.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes$2.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes$2.ERR_UNKNOWN_ENCODING; - return state.length; - } // you can override either this method, or the async _read(n) below. + var errorOrDestroy = destroyImpl.errorOrDestroy; + inherits_browser.exports(Writable$1, Stream$1); - Readable$1.prototype.read = function (n) { - debug$5('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. + function nop$1() {} + + function WritableState$1(options, stream, isDuplex) { + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Registry$3.Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug$5('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable$1(this);else emitReadable$1(this); - return null; - } + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() - n = howMuchToRead$1(n, state); // if we've ended, and we're now clear, then finish it up. + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - if (n === 0 && state.ended) { - if (state.length === 0) endReadable$1(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. + this.finalCalled = false; // drain event flag. + this.needDrain = false; // at the start of calling end() - var doRead = state.needReadable; - debug$5('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + this.ending = false; // when end() has been called, and returned - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug$5('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. + this.ended = false; // when 'finish' is emitted + this.finished = false; // has it been destroyed - if (state.ended || state.reading) { - doRead = false; - debug$5('reading or ended', doRead); - } else if (doRead) { - debug$5('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. - if (state.length === 0) state.needReadable = true; // call internal read method + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. - this._read(state.highWaterMark); + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. + this.length = 0; // a flag to see when we're in the middle of a write. - if (!state.reading) n = howMuchToRead$1(nOrig, state); - } + this.writing = false; // when true all writes will be buffered until .uncork() call - var ret; - if (n > 0) ret = fromList$1(n, state);else ret = null; + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - if (nOrig !== n && state.ended) endReadable$1(this); - } + this.onwrite = function (er) { + onwrite$1(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) - if (ret !== null) this.emit('data', ret); - return ret; - }; - function onEofChunk$1(stream, state) { - debug$5('onEofChunk'); - if (state.ended) return; + this.writecb = null; // the amount that is being written when _write is called. - if (state.decoder) { - var chunk = state.decoder.end(); + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams - state.ended = true; + this.prefinished = false; // True if the error was already emitted and should not be thrown again - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable$1(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_$1(stream); - } - } - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; // count buffered requests - function emitReadable$1(stream) { - var state = stream._readableState; - debug$5('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two - if (!state.emittedReadable) { - debug$5('emitReadable', state.flowing); - state.emittedReadable = true; - nextTick(emitReadable_$1, stream); - } + this.corkedRequestsFree = new CorkedRequest$1(this); } - function emitReadable_$1(stream) { - var state = stream._readableState; - debug$5('emitReadable_', state.destroyed, state.length, state.ended); + WritableState$1.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. + while (current) { + out.push(current); + current = current.next; + } + return out; + }; - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow$1(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. + (function () { + try { + Object.defineProperty(WritableState$1.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. - function maybeReadMore$1(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick(maybeReadMore_$1, stream, state); - } + var realHasInstance; + + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable$1, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable$1) return false; + return object && object._writableState instanceof WritableState$1; + } + }); + } else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; } - function maybeReadMore_$1(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug$5('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; + function Writable$1(options) { + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Registry$3.Duplex; + if (!isDuplex && !realHasInstance.call(Writable$1, this)) return new Writable$1(options); + this._writableState = new WritableState$1(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; } - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. + Stream$1.call(this); + } // Otherwise people can pipe Writable streams, which is just wrong. - Readable$1.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED$1('_read()')); + Writable$1.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; - Readable$1.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; + function writeAfterEnd$1(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; + errorOrDestroy(stream, er); + nextTick(cb, er); + } // Checks that a user-supplied chunk is valid, especially for the particular + // mode the stream is in. Currently this means that `null` is never accepted + // and undefined/non-string values are only allowed in object mode. - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; + function validChunk$1(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } - state.pipesCount += 1; - debug$5('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); + if (er) { + errorOrDestroy(stream, er); + nextTick(cb, er); + return false; + } - function onunpipe(readable, unpipeInfo) { - debug$5('onunpipe'); + return true; + } - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } + Writable$1.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer$h.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - function onend() { - debug$5('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop$1; + if (state.ending) writeAfterEnd$1(this, cb);else if (isBuf || validChunk$1(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer$1(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; - var ondrain = pipeOnDrain$1(src); - dest.on('drain', ondrain); - var cleanedUp = false; + Writable$1.prototype.cork = function () { + this._writableState.corked++; + }; - function cleanup() { - debug$5('cleanup'); // cleanup event handlers once the pipe is broken + Writable$1.prototype.uncork = function () { + var state = this._writableState; - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer$1(this, state); + } + }; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + Writable$1.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + Object.defineProperty(Writable$1.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); } + }); - src.on('data', ondata); + function decodeChunk$1(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$h.from(chunk, encoding); + } - function ondata(chunk) { - debug$5('ondata'); - var ret = dest.write(chunk); - debug$5('dest.write', ret); + return chunk; + } - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug$5('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } + Object.defineProperty(Writable$1.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. - src.pause(); + function writeOrBuffer$1(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk$1(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - function onerror(er) { - debug$5('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; - prependListener$1(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); + state.bufferedRequestCount += 1; + } else { + doWrite$1(stream, state, false, len, chunk, encoding, cb); } - dest.once('close', onclose); - - function onfinish() { - debug$5('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } + return ret; + } - dest.once('finish', onfinish); + function doWrite$1(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED$1('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } - function unpipe() { - debug$5('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + function onwriteError$1(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + nextTick(cb, er); // this can emit finish, and it will always happen + // after error - dest.emit('pipe', src); // start the flow if it hasn't been started already. + nextTick(finishMaybe$1, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error - if (!state.flowing) { - debug$5('pipe resume'); - src.resume(); + finishMaybe$1(stream, state); } + } - return dest; - }; + function onwriteStateUpdate$1(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - function pipeOnDrain$1(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug$5('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + function onwrite$1(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK$1(); + onwriteStateUpdate$1(state); + if (er) onwriteError$1(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish$1(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer$1(stream, state); + } - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow$1(src); + if (sync) { + nextTick(afterWrite$1, stream, state, finished, cb); + } else { + afterWrite$1(stream, state, finished, cb); } - }; + } } - Readable$1.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + function afterWrite$1(stream, state, finished, cb) { + if (!finished) onwriteDrain$1(stream, state); + state.pendingcb--; + cb(); + finishMaybe$1(stream, state); + } // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. - if (state.pipesCount === 0) return this; // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. + function onwriteDrain$1(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } // if there's something in the buffer waiting, then process it - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. + function clearBuffer$1(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - return this; - } // try to find the right one. - - - var index = indexOf$1(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something - + buffer.allBuffers = allBuffers; + doWrite$1(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite - Readable$1.prototype.on = function (ev, fn) { - var res = Stream$1.prototype.on.call(this, ev, fn); - var state = this._readableState; + state.pendingcb++; + state.lastBufferedRequest = null; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest$1(state); + } - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug$5('on readable', state.length, state.reading); + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite$1(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. - if (state.length) { - emitReadable$1(this); - } else if (!state.reading) { - nextTick(nReadingNextTick$1, this); + if (state.writing) { + break; } } + + if (entry === null) state.lastBufferedRequest = null; } - return res; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable$1.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED$1('_write()')); }; - Readable$1.prototype.addListener = Readable$1.prototype.on; + Writable$1.prototype._writev = null; - Readable$1.prototype.removeListener = function (ev, fn) { - var res = Stream$1.prototype.removeListener.call(this, ev, fn); + Writable$1.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return res; - }; + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - Readable$1.prototype.removeAllListeners = function (ev) { - var res = Stream$1.prototype.removeAllListeners.apply(this, arguments); + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - nextTick(updateReadableListening, this); - } - return res; + if (!state.ending) endWritable$1(this, state, cb); + return this; }; - function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); + Object.defineProperty(Writable$1.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; } - } + }); - function nReadingNextTick$1(self) { - debug$5('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. + function needFinish$1(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; - Readable$1.prototype.resume = function () { - var state = this._readableState; + if (err) { + errorOrDestroy(stream, err); + } - if (!state.flowing) { - debug$5('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe$1(stream, state); + }); + } - state.flowing = !state.readableListening; - resume$1(this, state); + function prefinish$2(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } + } - state.paused = false; - return this; - }; + function finishMaybe$1(stream, state) { + var need = needFinish$1(state); - function resume$1(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick(resume_$1, stream, state); + if (need) { + prefinish$2(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } } + + return need; } - function resume_$1(stream, state) { - debug$5('resume', state.reading); + function endWritable$1(stream, state, cb) { + state.ending = true; + finishMaybe$1(stream, state); - if (!state.reading) { - stream.read(0); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); } - state.resumeScheduled = false; - stream.emit('resume'); - flow$1(stream); - if (state.flowing && !state.reading) stream.read(0); + state.ended = true; + stream.writable = false; } - Readable$1.prototype.pause = function () { - debug$5('call pause flowing=%j', this._readableState.flowing); + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; - if (this._readableState.flowing !== false) { - debug$5('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. - this._readableState.paused = true; - return this; - }; - function flow$1(stream) { - var state = stream._readableState; - debug$5('flow', state.flowing); + state.corkedRequestsFree.next = corkReq; + } - while (state.flowing && stream.read() !== null) { - } - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. + Object.defineProperty(Writable$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - Readable$1.prototype.wrap = function (stream) { - var _this = this; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug$5('wrapped end'); + this._writableState.destroyed = value; + } + }); + Writable$1.prototype.destroy = destroyImpl.destroy; + Writable$1.prototype._undestroy = destroyImpl.undestroy; - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } + Writable$1.prototype._destroy = function (err, cb) { + cb(err); + }; - _this.push(null); - }); - stream.on('data', function (chunk) { - debug$5('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode + /**/ - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var objectKeys = Object.keys || function (obj) { + var keys = []; - var ret = _this.push(chunk); + for (var key in obj) { + keys.push(key); + } - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. + return keys; + }; + /**/ - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. + const Registry$2 = _registry; + Registry$2.Duplex = Duplex$1; - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. + inherits_browser.exports(Duplex$1, Registry$2.Readable); + { + // Allow the keys array to be GC'ed. + var keys$1 = objectKeys(Registry$2.Writable.prototype); - this._read = function (n) { - debug$5('wrapped _read', n); + for (var v$1 = 0; v$1 < keys$1.length; v$1++) { + var method$1 = keys$1[v$1]; + if (!Duplex$1.prototype[method$1]) Duplex$1.prototype[method$1] = Registry$2.Writable.prototype[method$1]; + } + } - if (paused) { - paused = false; - stream.resume(); - } - }; + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) return new Duplex$1(options); + Registry$2.Readable.call(this, options); + Registry$2.Writable.call(this, options); + this.allowHalfOpen = true; - return this; - }; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; - if (typeof Symbol === 'function') { - Readable$1.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = async_iterator; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend$1); } - - return createReadableStreamAsyncIterator(this); - }; + } } - Object.defineProperty(Readable$1.prototype, 'readableHighWaterMark', { + Object.defineProperty(Duplex$1.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { - return this._readableState.highWaterMark; + return this._writableState.highWaterMark; } }); - Object.defineProperty(Readable$1.prototype, 'readableBuffer', { + Object.defineProperty(Duplex$1.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { - return this._readableState && this._readableState.buffer; + return this._writableState && this._writableState.getBuffer(); } }); - Object.defineProperty(Readable$1.prototype, 'readableFlowing', { + Object.defineProperty(Duplex$1.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } + return this._writableState.length; } - }); // exposed for testing purposes only. + }); // the no-half-open enforcer - Readable$1._fromList = fromList$1; - Object.defineProperty(Readable$1.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. + function onend$1() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. - function fromList$1(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; + nextTick(onEndNT$1, this); } - function endReadable$1(stream) { - var state = stream._readableState; - debug$5('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - nextTick(endReadableNT$1, state, stream); - } + function onEndNT$1(self) { + self.end(); } - function endReadableNT$1(state, stream) { - debug$5('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } + Object.defineProperty(Duplex$1.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - } - } - if (typeof Symbol === 'function') { - Readable$1.from = function (iterable, opts) { - if (from === undefined) { - from = fromBrowser; - } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed - return from(Readable$1, iterable, opts); - }; - } - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + this._readableState.destroyed = value; + this._writableState.destroyed = value; } + }); - return -1; - } + const Registry$1 = _registry; - var _stream_transform = Transform$4; + Registry$1.Transform = Transform$4; var _require$codes$1 = errorsBrowser.codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes$1.ERR_METHOD_NOT_IMPLEMENTED, @@ -8744,9 +8740,7 @@ ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex$1 = _stream_duplex; - - inherits_browser.exports(Transform$4, Duplex$1); + inherits_browser.exports(Transform$4, Registry$1.Duplex); function afterTransform$1(er, data) { var ts = this._transformState; @@ -8772,7 +8766,7 @@ function Transform$4(options) { if (!(this instanceof Transform$4)) return new Transform$4(options); - Duplex$1.call(this, options); + Registry$1.Duplex.call(this, options); this._transformState = { afterTransform: afterTransform$1.bind(this), needTransform: false, @@ -8811,7 +8805,7 @@ Transform$4.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; - return Duplex$1.prototype.push.call(this, chunk, encoding); + return Registry$1.Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. @@ -8858,7 +8852,7 @@ }; Transform$4.prototype._destroy = function (err, cb) { - Duplex$1.prototype._destroy.call(this, err, function (err2) { + Registry$1.Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; @@ -8875,15 +8869,14 @@ return stream.push(null); } - var _stream_passthrough = PassThrough$1; + const Registry = _registry; + Registry.PassThrough = PassThrough$1; - var Transform$3 = _stream_transform; - - inherits_browser.exports(PassThrough$1, Transform$3); + inherits_browser.exports(PassThrough$1, Registry.Transform); function PassThrough$1(options) { if (!(this instanceof PassThrough$1)) return new PassThrough$1(options); - Transform$3.call(this, options); + Transform.call(this, options); } PassThrough$1.prototype._transform = function (chunk, encoding, cb) { @@ -8985,19 +8978,29 @@ var pipeline_1 = pipeline; (function (module, exports) { - exports = module.exports = _stream_readable; - exports.Stream = exports; - exports.Readable = exports; - exports.Writable = _stream_writable; - exports.Duplex = _stream_duplex; - exports.Transform = _stream_transform; - exports.PassThrough = _stream_passthrough; + const Registry = _registry; + + + + + + + + + exports = module.exports = Registry.Readable; + + exports.Stream = Registry.Readable; + exports.Readable = Registry.Readable; + exports.Writable = Registry.Writable; + exports.Duplex = Registry.Duplex; + exports.Transform = Registry.Transform; + exports.PassThrough = Registry.PassThrough; exports.finished = endOfStream; exports.pipeline = pipeline_1; }(readableBrowser, readableBrowser.exports)); var Buffer$g = safeBuffer.exports.Buffer; - var Transform$2 = readableBrowser.exports.Transform; + var Transform$3 = readableBrowser.exports.Transform; var inherits$i = inherits_browser.exports; function throwIfNotStringOrBuffer (val, prefix) { @@ -9007,7 +9010,7 @@ } function HashBase$2 (blockSize) { - Transform$2.call(this); + Transform$3.call(this); this._block = Buffer$g.allocUnsafe(blockSize); this._blockSize = blockSize; @@ -9017,7 +9020,7 @@ this._finalized = false; } - inherits$i(HashBase$2, Transform$2); + inherits$i(HashBase$2, Transform$3); HashBase$2.prototype._transform = function (chunk, encoding, callback) { var error = null; @@ -12163,7 +12166,7 @@ } // a transform stream is a readable/writable stream where you do - inherits$9(Transform$1, Duplex); + inherits$9(Transform$2, Duplex); function TransformState(stream) { this.afterTransform = function (er, data) { @@ -12198,8 +12201,8 @@ stream._read(rs.highWaterMark); } } - function Transform$1(options) { - if (!(this instanceof Transform$1)) return new Transform$1(options); + function Transform$2(options) { + if (!(this instanceof Transform$2)) return new Transform$2(options); Duplex.call(this, options); @@ -12229,7 +12232,7 @@ }); } - Transform$1.prototype.push = function (chunk, encoding) { + Transform$2.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; @@ -12244,11 +12247,11 @@ // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. - Transform$1.prototype._transform = function (chunk, encoding, cb) { + Transform$2.prototype._transform = function (chunk, encoding, cb) { throw new Error('Not implemented'); }; - Transform$1.prototype._write = function (chunk, encoding, cb) { + Transform$2.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; @@ -12262,7 +12265,7 @@ // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. - Transform$1.prototype._read = function (n) { + Transform$2.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { @@ -12290,11 +12293,11 @@ return stream.push(null); } - inherits$9(PassThrough, Transform$1); + inherits$9(PassThrough, Transform$2); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform$1.call(this, options); + Transform$2.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { @@ -12305,7 +12308,7 @@ Stream.Readable = Readable; Stream.Writable = Writable; Stream.Duplex = Duplex; - Stream.Transform = Transform$1; + Stream.Transform = Transform$2; Stream.PassThrough = PassThrough; // Backwards-compat with node 0.4.x @@ -12407,7 +12410,7 @@ Readable: Readable, Writable: Writable, Duplex: Duplex, - Transform: Transform$1, + Transform: Transform$2, PassThrough: PassThrough, Stream: Stream }); @@ -12415,12 +12418,12 @@ var require$$1 = /*@__PURE__*/getAugmentedNamespace(stream); var Buffer$6 = safeBuffer.exports.Buffer; - var Transform = require$$1.Transform; + var Transform$1 = require$$1.Transform; var StringDecoder = string_decoder.StringDecoder; var inherits$7 = inherits_browser.exports; function CipherBase (hashMode) { - Transform.call(this); + Transform$1.call(this); this.hashMode = typeof hashMode === 'string'; if (this.hashMode) { this[hashMode] = this._finalOrDigest; @@ -12434,7 +12437,7 @@ this._decoder = null; this._encoding = null; } - inherits$7(CipherBase, Transform); + inherits$7(CipherBase, Transform$1); CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { From 28f4a8d069d9416ab687edfd11be11ed14eac44c Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 11:13:22 +1100 Subject: [PATCH 65/78] wtf --- js/ledger.js | 1326 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 1178 insertions(+), 148 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index 13e4770a..2d032a05 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -999,7 +999,7 @@ var toString = {}.toString; - var isArray$1 = Array.isArray || function (arr) { + var isArray$2 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$1(obj.data)) { + if (obj.type === 'Buffer' && isArray$2(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1332,7 +1332,7 @@ }; Buffer$l.concat = function concat (list, length) { - if (!isArray$1(list)) { + if (!isArray$2(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -5166,7 +5166,7 @@ var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config$1 = {}; + var config$2 = {}; function noop$2() {} @@ -5243,7 +5243,7 @@ hrtime: hrtime, platform: platform, release: release, - config: config$1, + config: config$2, uptime: uptime }; @@ -7911,16 +7911,16 @@ */ function deprecate$1 (fn, msg) { - if (config('noDeprecation')) { + if (config$1('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { - if (config('throwDeprecation')) { + if (config$1('throwDeprecation')) { throw new Error(msg); - } else if (config('traceDeprecation')) { + } else if (config$1('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); @@ -7941,7 +7941,7 @@ * @api private */ - function config (name) { + function config$1 (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!commonjsGlobal.localStorage) return false; @@ -10264,7 +10264,7 @@ } }); for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { + if (isNull(x) || !isObject$1(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); @@ -10415,7 +10415,7 @@ // Check that value is an object with an inspect function on it if (ctx.customInspect && value && - isFunction(value.inspect) && + isFunction$1(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== inspect && // Also filter out any prototype objects using the circular check. @@ -10450,7 +10450,7 @@ // Some type of object without properties can be shortcutted. if (keys.length === 0) { - if (isFunction(value)) { + if (isFunction$1(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } @@ -10468,13 +10468,13 @@ var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array - if (isArray(value)) { + if (isArray$1(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions - if (isFunction(value)) { + if (isFunction$1(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } @@ -10647,7 +10647,7 @@ // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { + function isArray$1(ar) { return Array.isArray(ar); } @@ -10672,23 +10672,23 @@ } function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + return isObject$1(re) && objectToString(re) === '[object RegExp]'; } - function isObject(arg) { + function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + return isObject$1(d) && objectToString(d) === '[object Date]'; } function isError(e) { - return isObject(e) && + return isObject$1(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } - function isFunction(arg) { + function isFunction$1(arg) { return typeof arg === 'function'; } @@ -10698,7 +10698,7 @@ function _extend(origin, add) { // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + if (!add || !isObject$1(add)) return origin; var keys = Object.keys(add); var i = keys.length; @@ -36285,7 +36285,7 @@ return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } - var __extends$4 = (undefined && undefined.__extends) || (function () { + var __extends$6 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36313,7 +36313,7 @@ * and calls an abstract method to do the actual work. */ var SingleKeyAccount = /** @class */ (function (_super) { - __extends$4(SingleKeyAccount, _super); + __extends$6(SingleKeyAccount, _super); function SingleKeyAccount() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36344,7 +36344,7 @@ return SingleKeyAccount; }(BaseAccount)); var p2pkh = /** @class */ (function (_super) { - __extends$4(p2pkh, _super); + __extends$6(p2pkh, _super); function p2pkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36372,7 +36372,7 @@ return p2pkh; }(SingleKeyAccount)); var p2tr = /** @class */ (function (_super) { - __extends$4(p2tr, _super); + __extends$6(p2tr, _super); function p2tr() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36438,7 +36438,7 @@ return p2tr; }(SingleKeyAccount)); var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$4(p2wpkhWrapped, _super); + __extends$6(p2wpkhWrapped, _super); function p2wpkhWrapped() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36481,7 +36481,7 @@ return p2wpkhWrapped; }(SingleKeyAccount)); var p2wpkh = /** @class */ (function (_super) { - __extends$4(p2wpkh, _super); + __extends$6(p2wpkh, _super); function p2wpkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36717,7 +36717,7 @@ return tx.buffer(); } - var __extends$3 = (undefined && undefined.__extends) || (function () { + var __extends$5 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36778,7 +36778,7 @@ })(psbtOut || (psbtOut = {})); var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { - __extends$3(NoSuchEntry, _super); + __extends$5(NoSuchEntry, _super); function NoSuchEntry() { return _super !== null && _super.apply(this, arguments) || this; } @@ -37450,7 +37450,7 @@ ]); } - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$f = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37459,7 +37459,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$f = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37540,9 +37540,9 @@ */ BtcNew.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var pathElements, xpub, xpubComponents; - return __generator$e(this, function (_b) { + return __generator$f(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -37567,9 +37567,9 @@ */ BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$e(this, function (_c) { + return __generator$f(this, function (_c) { switch (_c.label) { case 0: pathElements = pathStringToArray(path); @@ -37607,9 +37607,9 @@ * ourselves, but we don't at this time, and instead return an empty ("") address. */ BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$e(this, function (_a) { + return __generator$f(this, function (_a) { switch (_a.label) { case 0: accountPath = hardenedPathOf(pathElements); @@ -37638,9 +37638,9 @@ * transaction is returned. */ BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$e(this, function (_a) { + return __generator$f(this, function (_a) { switch (_a.label) { case 0: inputCount = arg.inputs.length; @@ -37751,9 +37751,9 @@ * properties depend on the accountType used. */ BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var pathElems, i, xpub, pubkey, cond; - return __generator$e(this, function (_a) { + return __generator$f(this, function (_a) { switch (_a.label) { case 0: if (!path) @@ -37782,9 +37782,9 @@ * public key and its derivation path. */ BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$e(this, function (_a) { + return __generator$f(this, function (_a) { switch (_a.label) { case 0: inputTx = input[0]; @@ -37829,9 +37829,9 @@ * to the appropriate input fields of the PSBT. */ BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$f(this, void 0, void 0, function () { var sigs; - return __generator$e(this, function (_a) { + return __generator$f(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; case 1: @@ -37948,7 +37948,7 @@ }; return __assign$4.apply(this, arguments); }; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37957,7 +37957,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37991,9 +37991,9 @@ cashaddr: 3 }; function getWalletPublicKey(transport, options) { - return __awaiter$d(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$d(this, function (_b) { + return __generator$e(this, function (_b) { switch (_b.label) { case 0: _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; @@ -38066,7 +38066,7 @@ var browser = invariant; - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38075,7 +38075,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38114,9 +38114,9 @@ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$c(this, void 0, void 0, function () { + return __awaiter$d(this, void 0, void 0, function () { var data, firstRound, prefix, trustedInput, res; - return __generator$c(this, function (_a) { + return __generator$d(this, function (_a) { switch (_a.label) { case 0: firstRound = false; @@ -38140,11 +38140,11 @@ } function getTrustedInput(transport, indexLookup, transaction, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$c(this, void 0, void 0, function () { + return __awaiter$d(this, void 0, void 0, function () { var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; var e_1, _a, e_2, _b; var _this = this; - return __generator$c(this, function (_c) { + return __generator$d(this, function (_c) { switch (_c.label) { case 0: version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; @@ -38153,10 +38153,10 @@ } isDecred = additionals.includes("decred"); isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { + processScriptBlocks = function (script, sequence) { return __awaiter$d(_this, void 0, void 0, function () { var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; var e_3, _a; - return __generator$c(this, function (_b) { + return __generator$d(this, function (_b) { switch (_b.label) { case 0: seq = sequence || Buffer$l.alloc(0); @@ -38330,7 +38330,7 @@ }); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38339,7 +38339,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38397,10 +38397,10 @@ if (overwinter === void 0) { overwinter = false; } if (additionals === void 0) { additionals = []; } if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; var e_2, _c, e_1, _d; - return __generator$b(this, function (_e) { + return __generator$c(this, function (_e) { switch (_e.label) { case 0: data = Buffer$l.concat([ @@ -38583,7 +38583,7 @@ }); } - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38592,7 +38592,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38625,9 +38625,9 @@ } function hashOutputFull(transport, outputScript, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$a(this, void 0, void 0, function () { + return __awaiter$b(this, void 0, void 0, function () { var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$a(this, function (_a) { + return __generator$b(this, function (_a) { switch (_a.label) { case 0: offset = 0; @@ -38657,7 +38657,7 @@ }); } - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38666,7 +38666,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38693,9 +38693,9 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { + var getAppAndVersion = function (transport) { return __awaiter$a(void 0, void 0, void 0, function () { var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$9(this, function (_a) { + return __generator$a(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; case 1: @@ -38738,7 +38738,7 @@ }; return __assign$3.apply(this, arguments); }; - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38747,7 +38747,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38795,10 +38795,10 @@ onDeviceSignatureRequested: function () { } }; function createTransaction(transport, arg) { - return __awaiter$8(this, void 0, void 0, function () { + return __awaiter$9(this, void 0, void 0, function () { var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; var e_2, _a; - return __generator$8(this, function (_b) { + return __generator$9(this, function (_b) { switch (_b.label) { case 0: signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); @@ -39121,7 +39121,7 @@ }); } - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39130,7 +39130,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39159,9 +39159,9 @@ }; function signMessage(transport, _a) { var path = _a.path, messageHex = _a.messageHex; - return __awaiter$7(this, void 0, void 0, function () { + return __awaiter$8(this, void 0, void 0, function () { var paths, message, offset, _loop_1, res, v, r, s; - return __generator$7(this, function (_b) { + return __generator$8(this, function (_b) { switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); @@ -39169,7 +39169,7 @@ offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; - return __generator$7(this, function (_c) { + return __generator$8(this, function (_c) { switch (_c.label) { case 0: maxChunkSize = offset === 0 @@ -39241,7 +39241,7 @@ }; return __assign$2.apply(this, arguments); }; - var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39250,7 +39250,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39295,10 +39295,10 @@ transactionVersion: DEFAULT_VERSION }; function signP2SHTransaction(transport, arg) { - return __awaiter$6(this, void 0, void 0, function () { + return __awaiter$7(this, void 0, void 0, function () { var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; - return __generator$6(this, function (_c) { + return __generator$7(this, function (_c) { switch (_c.label) { case 0: _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; @@ -39445,7 +39445,7 @@ }; return __assign$1.apply(this, arguments); }; - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39454,7 +39454,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39494,9 +39494,9 @@ this.derivationsCache = {}; } BtcOld.prototype.derivatePath = function (path) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$6(this, void 0, void 0, function () { var res; - return __generator$5(this, function (_a) { + return __generator$6(this, function (_a) { switch (_a.label) { case 0: if (this.derivationsCache[path]) @@ -39514,9 +39514,9 @@ }; BtcOld.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$6(this, void 0, void 0, function () { var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$5(this, function (_b) { + return __generator$6(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -39724,7 +39724,7 @@ return MerkleMap; }()); - var __extends$2 = (undefined && undefined.__extends) || (function () { + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39776,7 +39776,7 @@ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt */ var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$2(MerkelizedPsbt, _super); + __extends$4(MerkelizedPsbt, _super); function MerkelizedPsbt(psbt) { var _this = _super.call(this) || this; _this.inputMerkleMaps = []; @@ -39820,7 +39820,7 @@ return MerkelizedPsbt; }(PsbtV2)); - var __extends$1 = (undefined && undefined.__extends) || (function () { + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39885,7 +39885,7 @@ return ClientCommand; }()); var YieldCommand = /** @class */ (function (_super) { - __extends$1(YieldCommand, _super); + __extends$3(YieldCommand, _super); function YieldCommand(results, progressCallback) { var _this = _super.call(this) || this; _this.progressCallback = progressCallback; @@ -39901,7 +39901,7 @@ return YieldCommand; }(ClientCommand)); var GetPreimageCommand = /** @class */ (function (_super) { - __extends$1(GetPreimageCommand, _super); + __extends$3(GetPreimageCommand, _super); function GetPreimageCommand(known_preimages, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_PREIMAGE; @@ -39947,7 +39947,7 @@ return GetPreimageCommand; }(ClientCommand)); var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafProofCommand, _super); + __extends$3(GetMerkleLeafProofCommand, _super); function GetMerkleLeafProofCommand(known_trees, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; @@ -39999,7 +39999,7 @@ return GetMerkleLeafProofCommand; }(ClientCommand)); var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$1(GetMerkleLeafIndexCommand, _super); + __extends$3(GetMerkleLeafIndexCommand, _super); function GetMerkleLeafIndexCommand(known_trees) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; @@ -40041,7 +40041,7 @@ return GetMerkleLeafIndexCommand; }(ClientCommand)); var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$1(GetMoreElementsCommand, _super); + __extends$3(GetMoreElementsCommand, _super); function GetMoreElementsCommand(queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MORE_ELEMENTS; @@ -40160,7 +40160,7 @@ return ClientCommandInterpreter; }()); - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40169,7 +40169,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40231,9 +40231,9 @@ this.transport = transport; } AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var response, hwRequest, commandResponse; - return __generator$4(this, function (_a) { + return __generator$5(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ 0x9000, @@ -40259,9 +40259,9 @@ }); }; AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var response; - return __generator$4(this, function (_a) { + return __generator$5(this, function (_a) { switch (_a.label) { case 0: if (pathElements.length > 6) { @@ -40279,9 +40279,9 @@ }); }; AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var clientInterpreter, addressIndexBuffer, response; - return __generator$4(this, function (_a) { + return __generator$5(this, function (_a) { switch (_a.label) { case 0: if (change !== 0 && change !== 1) @@ -40311,10 +40311,10 @@ }); }; AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; var e_1, _e, e_2, _f, e_3, _g; - return __generator$4(this, function (_h) { + return __generator$5(this, function (_h) { switch (_h.label) { case 0: merkelizedPsbt = new MerkelizedPsbt(psbt); @@ -40388,8 +40388,8 @@ }); }; AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$4(this, void 0, void 0, function () { - return __generator$4(this, function (_a) { + return __awaiter$5(this, void 0, void 0, function () { + return __generator$5(this, function (_a) { return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; }); }); @@ -40569,7 +40569,7 @@ return t; } - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40578,7 +40578,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40814,9 +40814,9 @@ return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); }; Btc.prototype.getCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var _lazyImpl, impl; - return __generator$3(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: _lazyImpl = this._lazyImpl; @@ -40832,9 +40832,9 @@ }); }; Btc.prototype.inferCorrectImpl = function () { - return __awaiter$3(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var appAndVersion, canUseNewImplementation; - return __generator$3(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; case 1: @@ -41310,7 +41310,7 @@ TransportStatusError: TransportStatusError }); - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41319,7 +41319,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41407,9 +41407,9 @@ this.send = function (cla, ins, p1, p2, data, statusList) { if (data === void 0) { data = Buffer$l.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$2(_this, void 0, void 0, function () { + return __awaiter$3(_this, void 0, void 0, function () { var response, sw; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: if (data.length >= 256) { @@ -41431,10 +41431,10 @@ }); }); }; - this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { + this.exchangeAtomicImpl = function (f) { return __awaiter$3(_this, void 0, void 0, function () { var resolveBusy, busyPromise, unresponsiveReached, timeout, res; var _this = this; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: if (this.exchangeBusyPromise) { @@ -41599,9 +41599,9 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return __awaiter$2(_this, void 0, void 0, function () { + return __awaiter$3(_this, void 0, void 0, function () { var _appAPIlock; - return __generator$2(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: _appAPIlock = this._appAPIlock; @@ -41826,7 +41826,7 @@ } } - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41835,7 +41835,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41868,9 +41868,9 @@ }, ]; function requestLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var device; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.requestDevice({ filters: ledgerDevices @@ -41883,9 +41883,9 @@ }); } function getLedgerDevices() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var devices; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.getDevices()]; case 1: @@ -41896,9 +41896,9 @@ }); } function getFirstLedgerDevice() { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter$2(this, void 0, void 0, function () { var existingDevices; - return __generator$1(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -41916,7 +41916,7 @@ typeof navigator.usb.getDevices === "function"); }; - var __extends = (undefined && undefined.__extends) || (function () { + var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -41931,7 +41931,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41940,7 +41940,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41977,7 +41977,7 @@ * TransportWebUSB.create().then(transport => ...) */ var TransportWebUSB = /** @class */ (function (_super) { - __extends(TransportWebUSB, _super); + __extends$2(TransportWebUSB, _super); function TransportWebUSB(device, interfaceNumber) { var _this = _super.call(this) || this; _this.channel = Math.floor(Math.random() * 0xffff); @@ -41998,9 +41998,9 @@ * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ TransportWebUSB.request = function () { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var device; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, requestLedgerDevice()]; case 1: @@ -42014,9 +42014,9 @@ * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). */ TransportWebUSB.openConnected = function () { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var devices; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -42032,9 +42032,9 @@ * Create a Ledger transport with a USBDevice */ TransportWebUSB.open = function (device) { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var iface, interfaceNumber, e_1, transport, onDisconnect; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, device.open()]; case 1: @@ -42088,8 +42088,8 @@ * Release the transport device */ TransportWebUSB.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { + return __awaiter$1(this, void 0, void 0, function () { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.exchangeBusyPromise]; case 1: @@ -42114,14 +42114,14 @@ * @returns a promise of apdu response */ TransportWebUSB.prototype.exchange = function (apdu) { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var b; var _this = this; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter$1(_this, void 0, void 0, function () { var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return __generator(this, function (_b) { + return __generator$1(this, function (_b) { switch (_b.label) { case 0: _a = this, channel = _a.channel, packetSize = _a.packetSize; @@ -42213,9 +42213,9 @@ return TransportWebUSB; }(Transport)); function gracefullyResetDevice(device) { - return __awaiter(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var err_1; - return __generator(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); @@ -42238,8 +42238,1038 @@ 'default': TransportWebUSB }); + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends$1(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isFunction(x) { + return typeof x === 'function'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var _enable_super_gross_mode_that_will_cause_bad_things = false; + var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function hostReportError(err) { + setTimeout(function () { throw err; }, 0); + } + + /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ + var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + }, + complete: function () { } + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isObject(x) { + return x !== null && typeof x === 'object'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; + })(); + var UnsubscriptionError = UnsubscriptionErrorImpl; + + /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ + var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._ctorUnsubscribe = true; + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (isFunction(_unsubscribe)) { + if (_ctorUnsubscribe) { + this._unsubscribe = undefined; + } + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (isArray(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof UnsubscriptionError) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } + } + } + } + if (errors) { + throw new UnsubscriptionError(errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + } + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; + }()); + function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); + })(); + + /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + var Subscriber = /*@__PURE__*/ (function (_super) { + __extends$1(Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = empty; + break; + case 1: + if (!destinationOrNext) { + _this.destination = empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[rxSubscriber] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; + }(Subscription)); + var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __extends$1(SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (isFunction(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== empty) { + context = Object.create(observerOrNext); + if (isFunction(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + hostReportError(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + hostReportError(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!config.useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + hostReportError(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ + function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof Subscriber) { + observer = destination; + } + else { + observer = null; + } + } + return true; + } + + /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ + function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber]) { + return nextOrObserver[rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber(empty); + } + return new Subscriber(nextOrObserver, error, complete); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function identity(x) { + return x; + } + + /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ + function pipeFromArray(fns) { + if (fns.length === 0) { + return identity; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; + } + + /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = toSubscriber(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (config.useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (canReportError(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[observable] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipeFromArray(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; + }()); + function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = config.Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { + function ObjectUnsubscribedErrorImpl() { + Error.call(this); + this.message = 'object unsubscribed'; + this.name = 'ObjectUnsubscribedError'; + return this; + } + ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ObjectUnsubscribedErrorImpl; + })(); + var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; + + /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ + var SubjectSubscription = /*@__PURE__*/ (function (_super) { + __extends$1(SubjectSubscription, _super); + function SubjectSubscription(subject, subscriber) { + var _this = _super.call(this) || this; + _this.subject = subject; + _this.subscriber = subscriber; + _this.closed = false; + return _this; + } + SubjectSubscription.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.closed = true; + var subject = this.subject; + var observers = subject.observers; + this.subject = null; + if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { + return; + } + var subscriberIndex = observers.indexOf(this.subscriber); + if (subscriberIndex !== -1) { + observers.splice(subscriberIndex, 1); + } + }; + return SubjectSubscription; + }(Subscription)); + + /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ + var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + __extends$1(SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; + }(Subscriber)); + var Subject = /*@__PURE__*/ (function (_super) { + __extends$1(Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[rxSubscriber] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); + } + } + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return Subscription.EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return Subscription.EMPTY; + } + else { + this.observers.push(subscriber); + return new SubjectSubscription(this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new Observable(); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; + }(Observable)); + var AnonymousSubject = /*@__PURE__*/ (function (_super) { + __extends$1(AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return Subscription.EMPTY; + } + }; + return AnonymousSubject; + }(Subject)); + + var net = {}; + + var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Speculos TCP transport implementation + * + * @example + * import SpeculosTransport from "@ledgerhq/hw-transport-node-speculos"; + * const transport = await SpeculosTransport.open({ apduPort }); + * const res = await transport.send(0xE0, 0x01, 0, 0); + */ + var SpeculosTransport = /** @class */ (function (_super) { + __extends(SpeculosTransport, _super); + function SpeculosTransport(apduSocket, opts) { + var _this = _super.call(this) || this; + _this.rejectExchange = function (_e) { }; + _this.resolveExchange = function (_b) { }; + _this.automationEvents = new Subject(); + /** + * Send a speculos button command + * typically "Ll" would press and release the left button + * typically "Rr" would press and release the right button + * @param {*} command + */ + _this.button = function (command) { + return new Promise(function (resolve, reject) { + log("speculos-button", command); + var _a = _this.opts, buttonPort = _a.buttonPort, host = _a.host; + if (!buttonPort) + throw new Error("buttonPort is missing"); + var socket = new net.Socket(); + socket.on("error", function (e) { + socket.destroy(); + reject(e); + }); + socket.connect(buttonPort, host || "127.0.0.1", function () { + socket.write(Buffer$l.from(command, "ascii")); + socket.destroy(); + resolve(); + }); + }); + }; + _this.opts = opts; + _this.apduSocket = apduSocket; + apduSocket.on("error", function (e) { + _this.emit("disconnect", new DisconnectedDevice(e.message)); + _this.rejectExchange(e); + _this.apduSocket.destroy(); + }); + apduSocket.on("end", function () { + _this.emit("disconnect", new DisconnectedDevice()); + _this.rejectExchange(new DisconnectedDeviceDuringOperation()); + }); + apduSocket.on("data", function (data) { + try { + _this.resolveExchange(decodeAPDUPayload(data)); + } + catch (e) { + _this.rejectExchange(e); + } + }); + var automationPort = opts.automationPort; + if (automationPort) { + var socket_1 = new net.Socket(); + _this.automationSocket = socket_1; + socket_1.on("error", function (e) { + log("speculos-automation-error", String(e)); + socket_1.destroy(); + }); + socket_1.on("data", function (data) { + log("speculos-automation-data", data.toString("ascii")); + var split = data.toString("ascii").split("\n"); + split + .filter(function (ascii) { return !!ascii; }) + .forEach(function (ascii) { + var json = JSON.parse(ascii); + _this.automationEvents.next(json); + }); + }); + socket_1.connect(automationPort, opts.host || "127.0.0.1"); + } + return _this; + } + SpeculosTransport.prototype.exchange = function (apdu) { + return __awaiter(this, void 0, void 0, function () { + var hex, encoded, res; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + hex = apdu.toString("hex"); + log("apdu", "=> " + hex); + encoded = encodeAPDU(apdu); + return [4 /*yield*/, new Promise(function (resolve, reject) { + _this.rejectExchange = reject; + _this.resolveExchange = resolve; + _this.apduSocket.write(encoded); + })]; + case 1: + res = _a.sent(); + log("apdu", "<= " + res.toString("hex")); + return [2 /*return*/, res]; + } + }); + }); + }; + SpeculosTransport.prototype.setScrambleKey = function () { }; + SpeculosTransport.prototype.close = function () { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + if (this.automationSocket) + this.automationSocket.destroy(); + this.apduSocket.destroy(); + return [2 /*return*/, Promise.resolve()]; + }); + }); + }; + SpeculosTransport.isSupported = function () { return Promise.resolve(true); }; + // this transport is not discoverable + SpeculosTransport.list = function () { return Promise.resolve([]); }; + SpeculosTransport.listen = function (_observer) { return ({ + unsubscribe: function () { } + }); }; + /** + * + */ + SpeculosTransport.open = function (opts) { + return new Promise(function (resolve, reject) { + var socket = new net.Socket(); + socket.on("error", function (e) { + socket.destroy(); + reject(e); + }); + socket.on("end", function () { + reject(new DisconnectedDevice("tcp closed")); + }); + socket.connect(opts.apduPort, opts.host || "127.0.0.1", function () { + // we delay a bit the transport creation to make sure the tcp does not hang up + setTimeout(function () { + resolve(new SpeculosTransport(socket, opts)); + }, 100); + }); + }); + }; + return SpeculosTransport; + }(Transport)); + function encodeAPDU(apdu) { + var size = Buffer$l.allocUnsafe(4); + size.writeUIntBE(apdu.length, 0, 4); + return Buffer$l.concat([size, apdu]); + } + function decodeAPDUPayload(data) { + var dataLength = data.readUIntBE(0, 4); // 4 bytes tells the data length + var size = dataLength + 2; // size does not include the status code so we add 2 + var payload = data.slice(4); + if (payload.length !== size) { + throw new TransportError("Expected payload of length ".concat(size, " but got ").concat(payload.length), ""); + } + return payload; + } + + var SpeculosTransport$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': SpeculosTransport + }); + exports.Btc = Btc$1; exports.Log = index; + exports.SpeculosTransport = SpeculosTransport$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; From e0d3cf7de94c16c34f265296b78199add42df868 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 11:17:29 +1100 Subject: [PATCH 66/78] wtf --- js/ledger.js | 1 + 1 file changed, 1 insertion(+) diff --git a/js/ledger.js b/js/ledger.js index 2d032a05..7ed0883f 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -43279,5 +43279,6 @@ window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; +window.SpeculosTransport = NewLedger.SpeculosTransport.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From 3e6431f2d79f0231ccd056dc1de105e4cf57cc15 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Wed, 16 Feb 2022 11:36:55 +1100 Subject: [PATCH 67/78] different module for speculos --- js/cointoolkit.js | 3 +- js/ledger.js | 3248 +++++++++++++++++++++++++++++---------------- 2 files changed, 2094 insertions(+), 1157 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 3e1eb7f2..cacafb59 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -676,7 +676,8 @@ $(document).ready(function() { async function getLedgerAddress(format, callback) { try { - const transport = await window.TransportWebUSB.create(); + //const transport = await window.TransportWebUSB.create(); + const transport = await window.SpeculosTransport.open(); const appBtc = new window.Btc(transport); result = await appBtc.getWalletPublicKey( coinjs.ledgerPath, diff --git a/js/ledger.js b/js/ledger.js index 7ed0883f..3af7fba0 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -997,10 +997,10 @@ buffer[offset + i - d] |= s * 128; } - var toString = {}.toString; + var toString$1 = {}.toString; var isArray$2 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; + return toString$1.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; @@ -1284,7 +1284,7 @@ } return length | 0 } - Buffer$l.isBuffer = isBuffer; + Buffer$l.isBuffer = isBuffer$1; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } @@ -2750,7 +2750,7 @@ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually - function isBuffer(obj) { + function isBuffer$1(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) } @@ -5166,7 +5166,7 @@ var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; - var config$2 = {}; + var config$1 = {}; function noop$2() {} @@ -5243,7 +5243,7 @@ hrtime: hrtime, platform: platform, release: release, - config: config$2, + config: config$1, uptime: uptime }; @@ -7911,16 +7911,16 @@ */ function deprecate$1 (fn, msg) { - if (config$1('noDeprecation')) { + if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { - if (config$1('throwDeprecation')) { + if (config('throwDeprecation')) { throw new Error(msg); - } else if (config$1('traceDeprecation')) { + } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); @@ -7941,7 +7941,7 @@ * @api private */ - function config$1 (name) { + function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!commonjsGlobal.localStorage) return false; @@ -10236,7 +10236,7 @@ var formatRegExp = /%[sdj%]/g; function format(f) { - if (!isString(f)) { + if (!isString$1(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); @@ -10278,16 +10278,24 @@ // If --no-deprecation is set, then it is a no-op. function deprecate(fn, msg) { // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { + if (isUndefined$1(global$1.process)) { return function() { return deprecate(fn, msg).apply(this, arguments); }; } + if (process.noDeprecation === true) { + return fn; + } + 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; @@ -10301,8 +10309,8 @@ var debugs = {}; var debugEnviron; function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = ''; + if (isUndefined$1(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { @@ -10343,10 +10351,10 @@ _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 (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined$1(ctx.depth)) ctx.depth = 2; + if (isUndefined$1(ctx.colors)) ctx.colors = false; + if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } @@ -10421,7 +10429,7 @@ // 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)) { + if (!isString$1(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; @@ -10457,7 +10465,7 @@ if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } - if (isDate(value)) { + if (isDate$1(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { @@ -10485,7 +10493,7 @@ } // Make dates with properties first say the date - if (isDate(value)) { + if (isDate$1(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } @@ -10524,15 +10532,15 @@ function formatPrimitive(ctx, value) { - if (isUndefined(value)) + if (isUndefined$1(value)) return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { + if (isString$1(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } - if (isNumber(value)) + if (isNumber$1(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); @@ -10606,7 +10614,7 @@ str = ctx.stylize('[Circular]', 'special'); } } - if (isUndefined(name)) { + if (isUndefined$1(name)) { if (array && key.match(/^\d+$/)) { return str; } @@ -10659,15 +10667,15 @@ return arg === null; } - function isNumber(arg) { + function isNumber$1(arg) { return typeof arg === 'number'; } - function isString(arg) { + function isString$1(arg) { return typeof arg === 'string'; } - function isUndefined(arg) { + function isUndefined$1(arg) { return arg === void 0; } @@ -10679,7 +10687,7 @@ return typeof arg === 'object' && arg !== null; } - function isDate(d) { + function isDate$1(d) { return isObject$1(d) && objectToString(d) === '[object Date]'; } @@ -11109,7 +11117,7 @@ function chunkInvalid(state, chunk) { var er = null; - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; @@ -11499,7 +11507,7 @@ // proxy certain important events. var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { + forEach$1(events, function (ev) { stream.on(ev, self.emit.bind(self, ev)); }); @@ -11641,7 +11649,7 @@ } } - function forEach(xs, f) { + function forEach$1(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } @@ -16447,7 +16455,7 @@ dependencies: dependencies }; - var utils$n = {}; + var utils$B = {}; var bn = {exports: {}}; @@ -19909,7 +19917,7 @@ throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; - var utils$m = {}; + var utils$A = {}; (function (exports) { @@ -19969,14 +19977,14 @@ else return arr; }; - }(utils$m)); + }(utils$A)); (function (exports) { var utils = exports; var BN = bn.exports; var minAssert = minimalisticAssert; - var minUtils = utils$m; + var minUtils = utils$A; utils.assert = minAssert; utils.toArray = minUtils.toArray; @@ -20089,7 +20097,7 @@ return new BN(bytes, 'hex', 'le'); } utils.intFromLE = intFromLE; - }(utils$n)); + }(utils$B)); var brorand = {exports: {}}; @@ -20162,10 +20170,10 @@ var curve = {}; var BN$8 = bn.exports; - var utils$l = utils$n; - var getNAF = utils$l.getNAF; - var getJSF = utils$l.getJSF; - var assert$e = utils$l.assert; + var utils$z = utils$B; + var getNAF = utils$z.getNAF; + var getJSF = utils$z.getJSF; + var assert$e = utils$z.assert; function BaseCurve(type, conf) { this.type = type; @@ -20428,7 +20436,7 @@ }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$l.toArray(bytes, enc); + bytes = utils$z.toArray(bytes, enc); var len = this.p.byteLength(); @@ -20466,7 +20474,7 @@ }; BasePoint.prototype.encode = function encode(enc, compact) { - return utils$l.encode(this._encode(compact), enc); + return utils$z.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { @@ -20540,12 +20548,12 @@ return r; }; - var utils$k = utils$n; + var utils$y = utils$B; var BN$7 = bn.exports; var inherits$3 = inherits_browser.exports; var Base$2 = base; - var assert$d = utils$k.assert; + var assert$d = utils$y.assert; function ShortCurve(conf) { Base$2.call(this, 'short', conf); @@ -21481,7 +21489,7 @@ var inherits$2 = inherits_browser.exports; var Base$1 = base; - var utils$j = utils$n; + var utils$x = utils$B; function MontCurve(conf) { Base$1.call(this, 'mont', conf); @@ -21521,7 +21529,7 @@ inherits$2(Point$1, Base$1.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$j.toArray(bytes, enc), 1); + return this.point(utils$x.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point(x, z) { @@ -21654,12 +21662,12 @@ return this.x.fromRed(); }; - var utils$i = utils$n; + var utils$w = utils$B; var BN$5 = bn.exports; var inherits$1 = inherits_browser.exports; var Base = base; - var assert$c = utils$i.assert; + var assert$c = utils$w.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() @@ -22102,12 +22110,12 @@ var hash$2 = {}; - var utils$h = {}; + var utils$v = {}; var assert$b = minimalisticAssert; var inherits = inherits_browser.exports; - utils$h.inherits = inherits; + utils$v.inherits = inherits; function isSurrogatePair(msg, i) { if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { @@ -22164,7 +22172,7 @@ } return res; } - utils$h.toArray = toArray; + utils$v.toArray = toArray; function toHex(msg) { var res = ''; @@ -22172,7 +22180,7 @@ res += zero2(msg[i].toString(16)); return res; } - utils$h.toHex = toHex; + utils$v.toHex = toHex; function htonl(w) { var res = (w >>> 24) | @@ -22181,7 +22189,7 @@ ((w & 0xff) << 24); return res >>> 0; } - utils$h.htonl = htonl; + utils$v.htonl = htonl; function toHex32(msg, endian) { var res = ''; @@ -22193,7 +22201,7 @@ } return res; } - utils$h.toHex32 = toHex32; + utils$v.toHex32 = toHex32; function zero2(word) { if (word.length === 1) @@ -22201,7 +22209,7 @@ else return word; } - utils$h.zero2 = zero2; + utils$v.zero2 = zero2; function zero8(word) { if (word.length === 7) @@ -22221,7 +22229,7 @@ else return word; } - utils$h.zero8 = zero8; + utils$v.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; @@ -22237,7 +22245,7 @@ } return res; } - utils$h.join32 = join32; + utils$v.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); @@ -22257,37 +22265,37 @@ } return res; } - utils$h.split32 = split32; + utils$v.split32 = split32; function rotr32$1(w, b) { return (w >>> b) | (w << (32 - b)); } - utils$h.rotr32 = rotr32$1; + utils$v.rotr32 = rotr32$1; function rotl32$2(w, b) { return (w << b) | (w >>> (32 - b)); } - utils$h.rotl32 = rotl32$2; + utils$v.rotl32 = rotl32$2; function sum32$3(a, b) { return (a + b) >>> 0; } - utils$h.sum32 = sum32$3; + utils$v.sum32 = sum32$3; function sum32_3$1(a, b, c) { return (a + b + c) >>> 0; } - utils$h.sum32_3 = sum32_3$1; + utils$v.sum32_3 = sum32_3$1; function sum32_4$2(a, b, c, d) { return (a + b + c + d) >>> 0; } - utils$h.sum32_4 = sum32_4$2; + utils$v.sum32_4 = sum32_4$2; function sum32_5$2(a, b, c, d, e) { return (a + b + c + d + e) >>> 0; } - utils$h.sum32_5 = sum32_5$2; + utils$v.sum32_5 = sum32_5$2; function sum64$1(buf, pos, ah, al) { var bh = buf[pos]; @@ -22298,20 +22306,20 @@ buf[pos] = hi >>> 0; buf[pos + 1] = lo; } - utils$h.sum64 = sum64$1; + utils$v.sum64 = sum64$1; function sum64_hi$1(ah, al, bh, bl) { var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } - utils$h.sum64_hi = sum64_hi$1; + utils$v.sum64_hi = sum64_hi$1; function sum64_lo$1(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } - utils$h.sum64_lo = sum64_lo$1; + utils$v.sum64_lo = sum64_lo$1; function sum64_4_hi$1(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; @@ -22326,13 +22334,13 @@ var hi = ah + bh + ch + dh + carry; return hi >>> 0; } - utils$h.sum64_4_hi = sum64_4_hi$1; + utils$v.sum64_4_hi = sum64_4_hi$1; function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } - utils$h.sum64_4_lo = sum64_4_lo$1; + utils$v.sum64_4_lo = sum64_4_lo$1; function sum64_5_hi$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; @@ -22349,41 +22357,41 @@ var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } - utils$h.sum64_5_hi = sum64_5_hi$1; + utils$v.sum64_5_hi = sum64_5_hi$1; function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } - utils$h.sum64_5_lo = sum64_5_lo$1; + utils$v.sum64_5_lo = sum64_5_lo$1; function rotr64_hi$1(ah, al, num) { var r = (al << (32 - num)) | (ah >>> num); return r >>> 0; } - utils$h.rotr64_hi = rotr64_hi$1; + utils$v.rotr64_hi = rotr64_hi$1; function rotr64_lo$1(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } - utils$h.rotr64_lo = rotr64_lo$1; + utils$v.rotr64_lo = rotr64_lo$1; function shr64_hi$1(ah, al, num) { return ah >>> num; } - utils$h.shr64_hi = shr64_hi$1; + utils$v.shr64_hi = shr64_hi$1; function shr64_lo$1(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } - utils$h.shr64_lo = shr64_lo$1; + utils$v.shr64_lo = shr64_lo$1; var common$5 = {}; - var utils$g = utils$h; + var utils$u = utils$v; var assert$a = minimalisticAssert; function BlockHash$4() { @@ -22402,7 +22410,7 @@ BlockHash$4.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks - msg = utils$g.toArray(msg, enc); + msg = utils$u.toArray(msg, enc); if (!this.pending) this.pending = msg; else @@ -22419,7 +22427,7 @@ if (this.pending.length === 0) this.pending = null; - msg = utils$g.join32(msg, 0, msg.length - r, this.endian); + msg = utils$u.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); } @@ -22478,8 +22486,8 @@ var common$4 = {}; - var utils$f = utils$h; - var rotr32 = utils$f.rotr32; + var utils$t = utils$v; + var rotr32 = utils$t.rotr32; function ft_1$1(s, x, y, z) { if (s === 0) @@ -22526,13 +22534,13 @@ } common$4.g1_256 = g1_256$1; - var utils$e = utils$h; + var utils$s = utils$v; var common$3 = common$5; var shaCommon$1 = common$4; - var rotl32$1 = utils$e.rotl32; - var sum32$2 = utils$e.sum32; - var sum32_5$1 = utils$e.sum32_5; + var rotl32$1 = utils$s.rotl32; + var sum32$2 = utils$s.sum32; + var sum32_5$1 = utils$s.sum32_5; var ft_1 = shaCommon$1.ft_1; var BlockHash$3 = common$3.BlockHash; @@ -22552,7 +22560,7 @@ this.W = new Array(80); } - utils$e.inherits(SHA1, BlockHash$3); + utils$s.inherits(SHA1, BlockHash$3); var _1 = SHA1; SHA1.blockSize = 512; @@ -22594,19 +22602,19 @@ SHA1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$e.toHex32(this.h, 'big'); + return utils$s.toHex32(this.h, 'big'); else - return utils$e.split32(this.h, 'big'); + return utils$s.split32(this.h, 'big'); }; - var utils$d = utils$h; + var utils$r = utils$v; var common$2 = common$5; var shaCommon = common$4; var assert$9 = minimalisticAssert; - var sum32$1 = utils$d.sum32; - var sum32_4$1 = utils$d.sum32_4; - var sum32_5 = utils$d.sum32_5; + var sum32$1 = utils$r.sum32; + var sum32_4$1 = utils$r.sum32_4; + var sum32_5 = utils$r.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; @@ -22647,7 +22655,7 @@ this.k = sha256_K; this.W = new Array(64); } - utils$d.inherits(SHA256$1, BlockHash$2); + utils$r.inherits(SHA256$1, BlockHash$2); var _256 = SHA256$1; SHA256$1.blockSize = 512; @@ -22698,12 +22706,12 @@ SHA256$1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$d.toHex32(this.h, 'big'); + return utils$r.toHex32(this.h, 'big'); else - return utils$d.split32(this.h, 'big'); + return utils$r.split32(this.h, 'big'); }; - var utils$c = utils$h; + var utils$q = utils$v; var SHA256 = _256; function SHA224() { @@ -22715,7 +22723,7 @@ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } - utils$c.inherits(SHA224, SHA256); + utils$q.inherits(SHA224, SHA256); var _224 = SHA224; SHA224.blockSize = 512; @@ -22726,26 +22734,26 @@ SHA224.prototype._digest = function digest(enc) { // Just truncate output if (enc === 'hex') - return utils$c.toHex32(this.h.slice(0, 7), 'big'); + return utils$q.toHex32(this.h.slice(0, 7), 'big'); else - return utils$c.split32(this.h.slice(0, 7), 'big'); + return utils$q.split32(this.h.slice(0, 7), 'big'); }; - var utils$b = utils$h; + var utils$p = utils$v; var common$1 = common$5; var assert$8 = minimalisticAssert; - var rotr64_hi = utils$b.rotr64_hi; - var rotr64_lo = utils$b.rotr64_lo; - var shr64_hi = utils$b.shr64_hi; - var shr64_lo = utils$b.shr64_lo; - var sum64 = utils$b.sum64; - var sum64_hi = utils$b.sum64_hi; - var sum64_lo = utils$b.sum64_lo; - var sum64_4_hi = utils$b.sum64_4_hi; - var sum64_4_lo = utils$b.sum64_4_lo; - var sum64_5_hi = utils$b.sum64_5_hi; - var sum64_5_lo = utils$b.sum64_5_lo; + var rotr64_hi = utils$p.rotr64_hi; + var rotr64_lo = utils$p.rotr64_lo; + var shr64_hi = utils$p.shr64_hi; + var shr64_lo = utils$p.shr64_lo; + var sum64 = utils$p.sum64; + var sum64_hi = utils$p.sum64_hi; + var sum64_lo = utils$p.sum64_lo; + var sum64_4_hi = utils$p.sum64_4_hi; + var sum64_4_lo = utils$p.sum64_4_lo; + var sum64_5_hi = utils$p.sum64_5_hi; + var sum64_5_lo = utils$p.sum64_5_lo; var BlockHash$1 = common$1.BlockHash; @@ -22809,7 +22817,7 @@ this.k = sha512_K; this.W = new Array(160); } - utils$b.inherits(SHA512$1, BlockHash$1); + utils$p.inherits(SHA512$1, BlockHash$1); var _512 = SHA512$1; SHA512$1.blockSize = 1024; @@ -22939,9 +22947,9 @@ SHA512$1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$b.toHex32(this.h, 'big'); + return utils$p.toHex32(this.h, 'big'); else - return utils$b.split32(this.h, 'big'); + return utils$p.split32(this.h, 'big'); }; function ch64_hi(xh, xl, yh, yl, zh) { @@ -23060,7 +23068,7 @@ return r; } - var utils$a = utils$h; + var utils$o = utils$v; var SHA512 = _512; @@ -23079,7 +23087,7 @@ 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 ]; } - utils$a.inherits(SHA384, SHA512); + utils$o.inherits(SHA384, SHA512); var _384 = SHA384; SHA384.blockSize = 1024; @@ -23089,9 +23097,9 @@ SHA384.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$a.toHex32(this.h.slice(0, 12), 'big'); + return utils$o.toHex32(this.h.slice(0, 12), 'big'); else - return utils$a.split32(this.h.slice(0, 12), 'big'); + return utils$o.split32(this.h.slice(0, 12), 'big'); }; sha.sha1 = _1; @@ -23102,13 +23110,13 @@ var ripemd = {}; - var utils$9 = utils$h; + var utils$n = utils$v; var common = common$5; - var rotl32 = utils$9.rotl32; - var sum32 = utils$9.sum32; - var sum32_3 = utils$9.sum32_3; - var sum32_4 = utils$9.sum32_4; + var rotl32 = utils$n.rotl32; + var sum32 = utils$n.sum32; + var sum32_3 = utils$n.sum32_3; + var sum32_4 = utils$n.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { @@ -23120,7 +23128,7 @@ this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.endian = 'little'; } - utils$9.inherits(RIPEMD160, BlockHash); + utils$n.inherits(RIPEMD160, BlockHash); ripemd.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; @@ -23171,9 +23179,9 @@ RIPEMD160.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$9.toHex32(this.h, 'little'); + return utils$n.toHex32(this.h, 'little'); else - return utils$9.split32(this.h, 'little'); + return utils$n.split32(this.h, 'little'); }; function f(j, x, y, z) { @@ -23247,7 +23255,7 @@ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; - var utils$8 = utils$h; + var utils$m = utils$v; var assert$7 = minimalisticAssert; function Hmac(hash, key, enc) { @@ -23259,7 +23267,7 @@ this.inner = null; this.outer = null; - this._init(utils$8.toArray(key, enc)); + this._init(utils$m.toArray(key, enc)); } var hmac = Hmac; @@ -23296,7 +23304,7 @@ (function (exports) { var hash = exports; - hash.utils = utils$h; + hash.utils = utils$v; hash.common = common$5; hash.sha = sha; hash.ripemd = ripemd; @@ -23317,7 +23325,7 @@ var hash = hash$2; var curve$1 = curve; - var utils = utils$n; + var utils = utils$B; var assert = utils.assert; @@ -23520,7 +23528,7 @@ }(curves$2)); var hash$1 = hash$2; - var utils$7 = utils$m; + var utils$l = utils$A; var assert$6 = minimalisticAssert; function HmacDRBG$1(options) { @@ -23537,9 +23545,9 @@ this.K = null; this.V = null; - var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); + var entropy = utils$l.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$l.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$l.toArray(options.pers, options.persEnc || 'hex'); assert$6(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._init(entropy, nonce, pers); @@ -23592,8 +23600,8 @@ entropyEnc = null; } - entropy = utils$7.toArray(entropy, entropyEnc); - add = utils$7.toArray(add, addEnc); + entropy = utils$l.toArray(entropy, entropyEnc); + add = utils$l.toArray(add, addEnc); assert$6(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); @@ -23615,7 +23623,7 @@ // Optional additional data if (add) { - add = utils$7.toArray(add, addEnc || 'hex'); + add = utils$l.toArray(add, addEnc || 'hex'); this._update(add); } @@ -23628,12 +23636,12 @@ var res = temp.slice(0, len); this._update(add); this._reseed++; - return utils$7.encode(res, enc); + return utils$l.encode(res, enc); }; var BN$4 = bn.exports; - var utils$6 = utils$n; - var assert$5 = utils$6.assert; + var utils$k = utils$B; + var assert$5 = utils$k.assert; function KeyPair$4(ec, options) { this.ec = ec; @@ -23753,8 +23761,8 @@ var BN$3 = bn.exports; - var utils$5 = utils$n; - var assert$4 = utils$5.assert; + var utils$j = utils$B; + var assert$4 = utils$j.assert; function Signature$3(options, enc) { if (options instanceof Signature$3) @@ -23818,7 +23826,7 @@ } Signature$3.prototype._importDER = function _importDER(data, enc) { - data = utils$5.toArray(data, enc); + data = utils$j.toArray(data, enc); var p = new Position(); if (data[p.place++] !== 0x30) { return false; @@ -23913,15 +23921,15 @@ var res = [ 0x30 ]; constructLength(res, backHalf.length); res = res.concat(backHalf); - return utils$5.encode(res, enc); + return utils$j.encode(res, enc); }; var BN$2 = bn.exports; var HmacDRBG = hmacDrbg; - var utils$4 = utils$n; + var utils$i = utils$B; var curves$1 = curves$2; var rand = brorand.exports; - var assert$3 = utils$4.assert; + var assert$3 = utils$i.assert; var KeyPair$3 = key$1; var Signature$2 = signature$1; @@ -24158,10 +24166,10 @@ throw new Error('Unable to find valid recovery factor'); }; - var utils$3 = utils$n; - var assert$2 = utils$3.assert; - var parseBytes$2 = utils$3.parseBytes; - var cachedProperty$1 = utils$3.cachedProperty; + var utils$h = utils$B; + var assert$2 = utils$h.assert; + var parseBytes$2 = utils$h.parseBytes; + var cachedProperty$1 = utils$h.cachedProperty; /** * @param {EDDSA} eddsa - instance @@ -24243,20 +24251,20 @@ KeyPair$2.prototype.getSecret = function getSecret(enc) { assert$2(this._secret, 'KeyPair is public only'); - return utils$3.encode(this.secret(), enc); + return utils$h.encode(this.secret(), enc); }; KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$3.encode(this.pubBytes(), enc); + return utils$h.encode(this.pubBytes(), enc); }; var key = KeyPair$2; var BN$1 = bn.exports; - var utils$2 = utils$n; - var assert$1 = utils$2.assert; - var cachedProperty = utils$2.cachedProperty; - var parseBytes$1 = utils$2.parseBytes; + var utils$g = utils$B; + var assert$1 = utils$g.assert; + var cachedProperty = utils$g.cachedProperty; + var parseBytes$1 = utils$g.parseBytes; /** * @param {EDDSA} eddsa - eddsa instance @@ -24311,16 +24319,16 @@ }; Signature$1.prototype.toHex = function toHex() { - return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); + return utils$g.encode(this.toBytes(), 'hex').toUpperCase(); }; var signature = Signature$1; var hash = hash$2; var curves = curves$2; - var utils$1 = utils$n; - var assert = utils$1.assert; - var parseBytes = utils$1.parseBytes; + var utils$f = utils$B; + var assert = utils$f.assert; + var parseBytes = utils$f.parseBytes; var KeyPair$1 = key; var Signature = signature; @@ -24379,7 +24387,7 @@ var hash = this.hash(); for (var i = 0; i < arguments.length; i++) hash.update(arguments[i]); - return utils$1.intFromLE(hash.digest()).umod(this.curve.n); + return utils$f.intFromLE(hash.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { @@ -24411,13 +24419,13 @@ }; EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils$1.parseBytes(bytes); + bytes = utils$f.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$1.intFromLE(normed); + var y = utils$f.intFromLE(normed); return this.curve.pointFromY(y, xIsOdd); }; @@ -24426,7 +24434,7 @@ }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils$1.intFromLE(bytes); + return utils$f.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { @@ -24438,7 +24446,7 @@ var elliptic = exports; elliptic.version = require$$0$1.version; - elliptic.utils = utils$n; + elliptic.utils = utils$B; elliptic.rand = brorand.exports; elliptic.curve = curve; elliptic.curves = curves$2; @@ -24532,7 +24540,7 @@ const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; function isScalar (x) { - return isBuffer(x) && x.length === 32 + return isBuffer$1(x) && x.length === 32 } function isOrderScalar (x) { @@ -24541,7 +24549,7 @@ } function isPoint (p) { - if (!isBuffer(p)) return false + if (!isBuffer$1(p)) return false if (p.length < 33) return false const t = p[0]; @@ -24578,7 +24586,7 @@ function isSignature (value) { const r = value.slice(0, 32); const s = value.slice(32, 64); - return isBuffer(value) && value.length === 64 && + return isBuffer$1(value) && value.length === 64 && r.compare(EC_GROUP_ORDER) < 0 && s.compare(EC_GROUP_ORDER) < 0 } @@ -24931,7 +24939,7 @@ var ERRORS$1 = errors; function _Buffer (value) { - return isBuffer(value) + return isBuffer$1(value) } function Hex (value) { @@ -25325,7 +25333,7 @@ return decodeRaw(bs58check$4.decode(string), version) } - function encode$h (version, privateKey, compressed) { + function encode$i (version, privateKey, compressed) { if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) return bs58check$4.encode( @@ -25340,7 +25348,7 @@ var wif$2 = { decode: decode$g, decodeRaw: decodeRaw, - encode: encode$h, + encode: encode$i, encodeRaw: encodeRaw }; @@ -25738,7 +25746,7 @@ ? 1 : 0; } - function encode$g(_number) { + function encode$h(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); const buffer = Buffer$l.allocUnsafe(size); @@ -25754,7 +25762,7 @@ } return buffer; } - script_number.encode = encode$g; + script_number.encode = encode$h; var script_signature = {}; @@ -25899,7 +25907,7 @@ * 62300 => 0x00f35c * -62300 => 0xff0ca4 */ - function encode$f (r, s) { + function encode$g (r, s) { var lenR = r.length; var lenS = s.length; if (lenR === 0) throw new Error('R length is zero') @@ -25929,7 +25937,7 @@ var bip66$1 = { check: check$m, decode: decode$e, - encode: encode$f + encode: encode$g }; Object.defineProperty(script_signature, '__esModule', { value: true }); @@ -25965,7 +25973,7 @@ return { signature, hashType }; } script_signature.decode = decode$d; - function encode$e(signature, hashType) { + function encode$f(signature, hashType) { typeforce$8( { signature: types$9.BufferN(64), @@ -25982,7 +25990,7 @@ const s = toDER(signature.slice(32, 64)); return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); } - script_signature.encode = encode$e; + script_signature.encode = encode$f; var OP_FALSE = 0; var OP_0 = 0; @@ -26232,7 +26240,7 @@ : 5 } - function encode$d (buffer, number, offset) { + function encode$e (buffer, number, offset) { var size = encodingLength$2(number); // ~6 bit @@ -26297,7 +26305,7 @@ var pushdataBitcoin = { encodingLength: encodingLength$2, - encode: encode$d, + encode: encode$e, decode: decode$c }; @@ -26345,13 +26353,13 @@ if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; } function chunksIsBuffer(buf) { - return isBuffer(buf); + return isBuffer$1(buf); } function chunksIsArray(buf) { return types.Array(buf); } function singleChunkIsBuffer(buf) { - return isBuffer(buf); + return isBuffer$1(buf); } function compile(chunks) { // TODO: remove me @@ -26480,7 +26488,7 @@ } exports.isDefinedHashType = isDefinedHashType; function isCanonicalScriptSignature(buffer) { - if (!isBuffer(buffer)) return false; + if (!isBuffer$1(buffer)) return false; if (!isDefinedHashType(buffer[buffer.length - 1])) return false; return bip66.check(buffer.slice(0, -1)); } @@ -27120,7 +27128,7 @@ if (a.input) { const chunks = _chunks(); if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer(_redeem().output)) + if (!isBuffer$1(_redeem().output)) throw new TypeError('Input is invalid'); checkRedeem(_redeem()); } @@ -27189,7 +27197,7 @@ return chk } - function encode$c (prefix, words, LIMIT) { + function encode$d (prefix, words, LIMIT) { LIMIT = LIMIT || 90; if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') @@ -27326,7 +27334,7 @@ var bech32$3 = { decodeUnsafe: decodeUnsafe, decode: decode$b, - encode: encode$c, + encode: encode$d, toWordsUnsafe: toWordsUnsafe, toWords: toWords, fromWordsUnsafe: fromWordsUnsafe, @@ -27483,7 +27491,7 @@ } function chunkHasUncompressedPubkey(chunk) { if ( - isBuffer(chunk) && + isBuffer$1(chunk) && chunk.length === 65 && chunk[0] === 0x04 && ecc$1.isPoint(chunk) @@ -27952,7 +27960,7 @@ if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') } - function encode$b (number, buffer, offset) { + function encode$c (number, buffer, offset) { checkUInt53$1(number); if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); @@ -27962,26 +27970,26 @@ // 8 bit if (number < 0xfd) { buffer.writeUInt8(number, offset); - encode$b.bytes = 1; + encode$c.bytes = 1; // 16 bit } else if (number <= 0xffff) { buffer.writeUInt8(0xfd, offset); buffer.writeUInt16LE(number, offset + 1); - encode$b.bytes = 3; + encode$c.bytes = 3; // 32 bit } else if (number <= 0xffffffff) { buffer.writeUInt8(0xfe, offset); buffer.writeUInt32LE(number, offset + 1); - encode$b.bytes = 5; + encode$c.bytes = 5; // 64 bit } else { buffer.writeUInt8(0xff, offset); buffer.writeUInt32LE(number >>> 0, offset + 1); buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$b.bytes = 9; + encode$c.bytes = 9; } return buffer @@ -28031,7 +28039,7 @@ ) } - var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; + var varuintBitcoin = { encode: encode$c, decode: decode$a, encodingLength: encodingLength$1 }; Object.defineProperty(bufferutils, '__esModule', { value: true }); const types$6 = types$a; @@ -28916,7 +28924,7 @@ return data; } globalXpub$1.decode = decode$9; - function encode$a(data) { + function encode$b(data) { const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); const key = Buffer$l.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); @@ -28935,7 +28943,7 @@ value, }; } - globalXpub$1.encode = encode$a; + globalXpub$1.encode = encode$b; globalXpub$1.expected = '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; function check$l(data) { @@ -28943,10 +28951,10 @@ const mfp = data.masterFingerprint; const p = data.path; return ( - isBuffer(epk) && + isBuffer$1(epk) && epk.length === 78 && [2, 3].indexOf(epk[45]) > -1 && - isBuffer(mfp) && + isBuffer$1(mfp) && mfp.length === 4 && typeof p === 'string' && !!p.match(/^m(\/\d+'?)+$/) @@ -28967,13 +28975,13 @@ Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); const typeFields_1$a = typeFields; - function encode$9(data) { + function encode$a(data) { return { key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } - unsignedTx$1.encode = encode$9; + unsignedTx$1.encode = encode$a; var finalScriptSig$1 = {}; @@ -28989,17 +28997,17 @@ return keyVal.value; } finalScriptSig$1.decode = decode$8; - function encode$8(data) { + function encode$9(data) { const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, }; } - finalScriptSig$1.encode = encode$8; + finalScriptSig$1.encode = encode$9; finalScriptSig$1.expected = 'Buffer'; function check$k(data) { - return isBuffer(data); + return isBuffer$1(data); } finalScriptSig$1.check = check$k; function canAdd$5(currentData, newData) { @@ -29021,17 +29029,17 @@ return keyVal.value; } finalScriptWitness$1.decode = decode$7; - function encode$7(data) { + function encode$8(data) { const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, }; } - finalScriptWitness$1.encode = encode$7; + finalScriptWitness$1.encode = encode$8; finalScriptWitness$1.expected = 'Buffer'; function check$j(data) { - return isBuffer(data); + return isBuffer$1(data); } finalScriptWitness$1.check = check$j; function canAdd$4(currentData, newData) { @@ -29055,16 +29063,16 @@ return keyVal.value; } nonWitnessUtxo$1.decode = decode$6; - function encode$6(data) { + function encode$7(data) { return { key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } - nonWitnessUtxo$1.encode = encode$6; + nonWitnessUtxo$1.encode = encode$7; nonWitnessUtxo$1.expected = 'Buffer'; function check$i(data) { - return isBuffer(data); + return isBuffer$1(data); } nonWitnessUtxo$1.check = check$i; function canAdd$3(currentData, newData) { @@ -29099,19 +29107,19 @@ }; } partialSig$1.decode = decode$5; - function encode$5(pSig) { + function encode$6(pSig) { const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { key: Buffer$l.concat([head, pSig.pubkey]), value: pSig.signature, }; } - partialSig$1.encode = encode$5; + partialSig$1.encode = encode$6; partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; function check$h(data) { return ( - isBuffer(data.pubkey) && - isBuffer(data.signature) && + isBuffer$1(data.pubkey) && + isBuffer$1(data.signature) && [33, 65].includes(data.pubkey.length) && [2, 3, 4].includes(data.pubkey[0]) && isDerSigWithSighash(data.signature) @@ -29119,7 +29127,7 @@ } partialSig$1.check = check$h; function isDerSigWithSighash(buf) { - if (!isBuffer(buf) || buf.length < 9) return false; + if (!isBuffer$1(buf) || buf.length < 9) return false; if (buf[0] !== 0x30) return false; if (buf.length !== buf[1] + 3) return false; if (buf[2] !== 0x02) return false; @@ -29153,14 +29161,14 @@ return keyVal.value.toString('utf8'); } porCommitment$1.decode = decode$4; - function encode$4(data) { + function encode$5(data) { const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, value: Buffer$l.from(data, 'utf8'), }; } - porCommitment$1.encode = encode$4; + porCommitment$1.encode = encode$5; porCommitment$1.expected = 'string'; function check$g(data) { return typeof data === 'string'; @@ -29185,7 +29193,7 @@ return keyVal.value.readUInt32LE(0); } sighashType$1.decode = decode$3; - function encode$3(data) { + function encode$4(data) { const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); const value = Buffer$l.allocUnsafe(4); value.writeUInt32LE(data, 0); @@ -29194,7 +29202,7 @@ value, }; } - sighashType$1.encode = encode$3; + sighashType$1.encode = encode$4; sighashType$1.expected = 'number'; function check$f(data) { return typeof data === 'number'; @@ -29218,38 +29226,38 @@ if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) throw new RangeError('value out of range'); } - function encode$2(_number, buffer, offset) { + function encode$3(_number, buffer, offset) { checkUInt53(_number); if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); - if (!isBuffer(buffer)) + if (!isBuffer$1(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; // 8 bit if (_number < 0xfd) { buffer.writeUInt8(_number, offset); - Object.assign(encode$2, { bytes: 1 }); + Object.assign(encode$3, { bytes: 1 }); // 16 bit } else if (_number <= 0xffff) { buffer.writeUInt8(0xfd, offset); buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 3 }); + Object.assign(encode$3, { bytes: 3 }); // 32 bit } else if (_number <= 0xffffffff) { buffer.writeUInt8(0xfe, offset); buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$2, { bytes: 5 }); + Object.assign(encode$3, { bytes: 5 }); // 64 bit } else { buffer.writeUInt8(0xff, offset); buffer.writeUInt32LE(_number >>> 0, offset + 1); buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$2, { bytes: 9 }); + Object.assign(encode$3, { bytes: 9 }); } return buffer; } - varint$1.encode = encode$2; + varint$1.encode = encode$3; function decode$2(buffer, offset) { - if (!isBuffer(buffer)) + if (!isBuffer$1(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; const first = buffer.readUInt8(offset); @@ -29376,7 +29384,7 @@ }; } witnessUtxo$1.decode = decode$1; - function encode$1(data) { + function encode$2(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); @@ -29388,10 +29396,10 @@ value: result, }; } - witnessUtxo$1.encode = encode$1; + witnessUtxo$1.encode = encode$2; witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; function check$e(data) { - return isBuffer(data.script) && typeof data.value === 'number'; + return isBuffer$1(data.script) && typeof data.value === 'number'; } witnessUtxo$1.check = check$e; function canAdd(currentData, newData) { @@ -29462,8 +29470,8 @@ '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; function check(data) { return ( - isBuffer(data.pubkey) && - isBuffer(data.masterFingerprint) && + isBuffer$1(data.pubkey) && + isBuffer$1(data.masterFingerprint) && typeof data.path === 'string' && [33, 65].includes(data.pubkey.length) && [2, 3, 4].includes(data.pubkey[0]) && @@ -29531,7 +29539,7 @@ } const expected = 'Buffer'; function check(data) { - return isBuffer(data); + return isBuffer$1(data); } function canAdd(currentData, newData) { return !!currentData && !!newData && currentData.redeemScript === undefined; @@ -29568,7 +29576,7 @@ } const expected = 'Buffer'; function check(data) { - return isBuffer(data); + return isBuffer$1(data); } function canAdd(currentData, newData) { return ( @@ -30132,7 +30140,7 @@ return set; } - var utils = {}; + var utils$e = {}; (function (exports) { Object.defineProperty(exports, '__esModule', { value: true }); @@ -30257,7 +30265,7 @@ } exports.addOutputAttributes = addOutputAttributes; function defaultVersionSetter(version, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { + if (!isBuffer$1(txBuf) || txBuf.length < 4) { throw new Error('Set Version: Invalid Transaction'); } txBuf.writeUInt32LE(version, 0); @@ -30265,20 +30273,20 @@ } exports.defaultVersionSetter = defaultVersionSetter; function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer(txBuf) || txBuf.length < 4) { + if (!isBuffer$1(txBuf) || txBuf.length < 4) { throw new Error('Set Locktime: Invalid Transaction'); } txBuf.writeUInt32LE(locktime, txBuf.length - 4); return txBuf; } exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils)); + }(utils$e)); Object.defineProperty(psbt, '__esModule', { value: true }); const combiner_1 = combiner; const parser_1 = parser; const typeFields_1 = typeFields; - const utils_1$1 = utils; + const utils_1$1 = utils$e; class Psbt$1 { constructor(tx) { this.inputs = []; @@ -30425,7 +30433,7 @@ Object.defineProperty(psbt$1, '__esModule', { value: true }); const bip174_1 = psbt; const varuint = varint$1; - const utils_1 = utils; + const utils_1 = utils$e; const address_1 = address$1; const bufferutils_1$1 = bufferutils; const crypto_1$1 = crypto$2; @@ -31058,7 +31066,7 @@ if ( input.hash === undefined || input.index === undefined || - (!isBuffer(input.hash) && typeof input.hash !== 'string') || + (!isBuffer$1(input.hash) && typeof input.hash !== 'string') || typeof input.index !== 'number' ) { throw new Error('Error adding input.'); @@ -31073,7 +31081,7 @@ if ( output.script === undefined || output.value === undefined || - !isBuffer(output.script) || + !isBuffer$1(output.script) || typeof output.value !== 'number' ) { throw new Error('Error adding output.'); @@ -31482,7 +31490,7 @@ return scriptItems .concat(witnessItems) .filter(item => { - return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); + return isBuffer$1(item) && bscript$f.isCanonicalScriptSignature(item); }) .map(sig => ({ signature: sig })); } @@ -31728,7 +31736,7 @@ if (!decomp) return; const lastItem = decomp[decomp.length - 1]; if ( - !isBuffer(lastItem) || + !isBuffer$1(lastItem) || isPubkeyLike(lastItem) || isSigLike(lastItem) ) @@ -32046,7 +32054,7 @@ const chunks = bscript$5.decompile(script); if (chunks.length < 1) return false; const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer(lastChunk)) return false; + if (!isBuffer$1(lastChunk)) return false; const scriptSigChunks = bscript$5.decompile( bscript$5.compile(chunks.slice(0, -1)), ); @@ -32134,14 +32142,14 @@ check$2.toJSON = () => { return 'Witness commitment output'; }; - function encode(commitment) { + function encode$1(commitment) { typeforce$2(types$2.Hash256bit, commitment); const buffer = Buffer$l.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); } - output$3.encode = encode; + output$3.encode = encode$1; function decode(buffer) { typeforce$2(check$2, buffer); return bscript$3.decompile(buffer)[1].slice(4, 36); @@ -32196,7 +32204,7 @@ typeforce$1(typeforce$1.Array, chunks); if (chunks.length < 1) return false; const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer(witnessScript)) return false; + if (!isBuffer$1(witnessScript)) return false; const witnessScriptChunks = bscript$1.decompile(witnessScript); // is witnessScript a valid script? if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; @@ -34662,7 +34670,7 @@ throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity; - trim(this); + trim$1(this); } get max () { return this[MAX] @@ -34680,7 +34688,7 @@ throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA; - trim(this); + trim$1(this); } get maxAge () { return this[MAX_AGE] @@ -34699,7 +34707,7 @@ this[LENGTH] += hit.length; }); } - trim(this); + trim$1(this); } get lengthCalculator () { return this[LENGTH_CALCULATOR] } @@ -34788,7 +34796,7 @@ this[LENGTH] += len - item.length; item.length = len; this.get(key); - trim(this); + trim$1(this); return true } @@ -34805,7 +34813,7 @@ this[LENGTH] += hit.length; this[LRU_LIST].unshift(hit); this[CACHE].set(key, this[LRU_LIST].head); - trim(this); + trim$1(this); return true } @@ -34891,7 +34899,7 @@ : self[MAX_AGE] && (diff > self[MAX_AGE]) }; - const trim = self => { + const trim$1 = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { @@ -36285,7 +36293,7 @@ return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } - var __extends$6 = (undefined && undefined.__extends) || (function () { + var __extends$5 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36313,7 +36321,7 @@ * and calls an abstract method to do the actual work. */ var SingleKeyAccount = /** @class */ (function (_super) { - __extends$6(SingleKeyAccount, _super); + __extends$5(SingleKeyAccount, _super); function SingleKeyAccount() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36344,7 +36352,7 @@ return SingleKeyAccount; }(BaseAccount)); var p2pkh = /** @class */ (function (_super) { - __extends$6(p2pkh, _super); + __extends$5(p2pkh, _super); function p2pkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36372,7 +36380,7 @@ return p2pkh; }(SingleKeyAccount)); var p2tr = /** @class */ (function (_super) { - __extends$6(p2tr, _super); + __extends$5(p2tr, _super); function p2tr() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36438,7 +36446,7 @@ return p2tr; }(SingleKeyAccount)); var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$6(p2wpkhWrapped, _super); + __extends$5(p2wpkhWrapped, _super); function p2wpkhWrapped() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36481,7 +36489,7 @@ return p2wpkhWrapped; }(SingleKeyAccount)); var p2wpkh = /** @class */ (function (_super) { - __extends$6(p2wpkh, _super); + __extends$5(p2wpkh, _super); function p2wpkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36717,7 +36725,7 @@ return tx.buffer(); } - var __extends$5 = (undefined && undefined.__extends) || (function () { + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36778,7 +36786,7 @@ })(psbtOut || (psbtOut = {})); var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { - __extends$5(NoSuchEntry, _super); + __extends$4(NoSuchEntry, _super); function NoSuchEntry() { return _super !== null && _super.apply(this, arguments) || this; } @@ -38037,7 +38045,7 @@ */ var invariant = function(condition, format, a, b, c, d, e, f) { - { + if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } @@ -39724,7 +39732,7 @@ return MerkleMap; }()); - var __extends$4 = (undefined && undefined.__extends) || (function () { + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39776,7 +39784,7 @@ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt */ var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$4(MerkelizedPsbt, _super); + __extends$3(MerkelizedPsbt, _super); function MerkelizedPsbt(psbt) { var _this = _super.call(this) || this; _this.inputMerkleMaps = []; @@ -39820,7 +39828,7 @@ return MerkelizedPsbt; }(PsbtV2)); - var __extends$3 = (undefined && undefined.__extends) || (function () { + var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39885,7 +39893,7 @@ return ClientCommand; }()); var YieldCommand = /** @class */ (function (_super) { - __extends$3(YieldCommand, _super); + __extends$2(YieldCommand, _super); function YieldCommand(results, progressCallback) { var _this = _super.call(this) || this; _this.progressCallback = progressCallback; @@ -39901,7 +39909,7 @@ return YieldCommand; }(ClientCommand)); var GetPreimageCommand = /** @class */ (function (_super) { - __extends$3(GetPreimageCommand, _super); + __extends$2(GetPreimageCommand, _super); function GetPreimageCommand(known_preimages, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_PREIMAGE; @@ -39947,7 +39955,7 @@ return GetPreimageCommand; }(ClientCommand)); var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$3(GetMerkleLeafProofCommand, _super); + __extends$2(GetMerkleLeafProofCommand, _super); function GetMerkleLeafProofCommand(known_trees, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; @@ -39999,7 +40007,7 @@ return GetMerkleLeafProofCommand; }(ClientCommand)); var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$3(GetMerkleLeafIndexCommand, _super); + __extends$2(GetMerkleLeafIndexCommand, _super); function GetMerkleLeafIndexCommand(known_trees) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; @@ -40041,7 +40049,7 @@ return GetMerkleLeafIndexCommand; }(ClientCommand)); var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$3(GetMoreElementsCommand, _super); + __extends$2(GetMoreElementsCommand, _super); function GetMoreElementsCommand(queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MORE_ELEMENTS; @@ -41916,7 +41924,7 @@ typeof navigator.usb.getDevices === "function"); }; - var __extends$2 = (undefined && undefined.__extends) || (function () { + var __extends$1 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -41977,7 +41985,7 @@ * TransportWebUSB.create().then(transport => ...) */ var TransportWebUSB = /** @class */ (function (_super) { - __extends$2(TransportWebUSB, _super); + __extends$1(TransportWebUSB, _super); function TransportWebUSB(device, interfaceNumber) { var _this = _super.call(this) || this; _this.channel = Math.floor(Math.random() * 0xffff); @@ -42238,820 +42246,1812 @@ 'default': TransportWebUSB }); - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends$1(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isFunction(x) { - return typeof x === 'function'; - } - - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var _enable_super_gross_mode_that_will_cause_bad_things = false; - var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); - } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, + var axios$2 = {exports: {}}; + + var bind$2 = 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); + }; }; - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function hostReportError(err) { - setTimeout(function () { throw err; }, 0); + var bind$1 = bind$2; + + // utils is a library of generic helper functions non-specific to axios + + var toString = Object.prototype.toString; + + /** + * 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 toString.call(val) === '[object Array]'; } - /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ - var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); + /** + * 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 + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ + function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; + } + + /** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ + function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); + } + + /** + * 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) && (val.buffer instanceof ArrayBuffer); + } + 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 (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; + } + + /** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ + function isDate(val) { + return toString.call(val) === '[object Date]'; + } + + /** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ + function isFile(val) { + return toString.call(val) === '[object File]'; + } + + /** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ + function isBlob(val) { + return toString.call(val) === '[object Blob]'; + } + + /** + * 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 URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ + function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof 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$1(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; + } + + var utils$d = { + 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 + }; + + var utils$c = utils$d; + + 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 + */ + var buildURL$2 = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils$c.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils$c.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils$c.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils$c.forEach(val, function parseValue(v) { + if (utils$c.isDate(v)) { + v = v.toISOString(); + } else if (utils$c.isObject(v)) { + v = JSON.stringify(v); } - }, - complete: function () { } + 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; }; - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); + var utils$b = utils$d; - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function isObject(x) { - return x !== null && typeof x === 'object'; + function InterceptorManager$1() { + this.handlers = []; } - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; + /** + * 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$1.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$1.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$1.prototype.forEach = function forEach(fn) { + utils$b.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; - })(); - var UnsubscriptionError = UnsubscriptionErrorImpl; - - /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ - var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._ctorUnsubscribe = true; - this._unsubscribe = unsubscribe; - } + }); + }; + + var InterceptorManager_1 = InterceptorManager$1; + + var utils$a = utils$d; + + var normalizeHeaderName$1 = function normalizeHeaderName(headers, normalizedName) { + utils$a.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; - } - var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (isFunction(_unsubscribe)) { - if (_ctorUnsubscribe) { - this._unsubscribe = undefined; - } - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (isArray(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (isObject(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof UnsubscriptionError) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } + }); + }; + + /** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ + var enhanceError$2 = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } + + error.request = request; + error.response = response; + error.isAxiosError = true; + + 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 }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; - } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; - } - subscription._parentOrParents = [_parentOrParents, this]; - } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); - } - else { - return subscription; - } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; - } - else { - subscriptions.push(subscription); + }; + return error; + }; + + var enhanceError$1 = enhanceError$2; + + /** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ + var createError$2 = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError$1(error, config, code, request, response); + }; + + var createError$1 = createError$2; + + /** + * 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. + */ + var settle$1 = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError$1( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } + }; + + var utils$9 = utils$d; + + var cookies$1 = ( + utils$9.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$9.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils$9.isString(path)) { + cookie.push('path=' + path); + } + + if (utils$9.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); } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } + }; + })() : + + // 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() {} + }; + })() + ); + + /** + * 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 + */ + var isAbsoluteURL$1 = 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); + }; + + /** + * 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 + */ + var combineURLs$1 = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; + }; + + var isAbsoluteURL = isAbsoluteURL$1; + var combineURLs = combineURLs$1; + + /** + * 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 + */ + var buildFullPath$1 = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; + }; + + var utils$8 = utils$d; + + // 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 + */ + var parseHeaders$1 = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils$8.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils$8.trim(line.substr(0, i)).toLowerCase(); + val = utils$8.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; + }; + + var utils$7 = utils$d; + + var isURLSameOrigin$1 = ( + utils$7.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; } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; - }()); - function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); + + 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$7.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; + }; + })() + ); + + /** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ + function Cancel$3(message) { + this.message = message; } - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); - })(); + Cancel$3.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); + }; - /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ - var Subscriber = /*@__PURE__*/ (function (_super) { - __extends$1(Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = empty; - break; - case 1: - if (!destinationOrNext) { - _this.destination = empty; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; + Cancel$3.prototype.__CANCEL__ = true; + + var Cancel_1 = Cancel$3; + + var utils$6 = utils$d; + var settle = settle$1; + var cookies = cookies$1; + var buildURL$1 = buildURL$2; + var buildFullPath = buildFullPath$1; + var parseHeaders = parseHeaders$1; + var isURLSameOrigin = isURLSameOrigin$1; + var createError = createError$2; + var defaults$4 = defaults_1; + var Cancel$2 = Cancel_1; + + var xhr = 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); + } } - Subscriber.prototype[rxSubscriber] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; - }(Subscription)); - var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __extends$1(SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (isFunction(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== empty) { - context = Object.create(observerOrNext); - if (isFunction(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; + + if (utils$6.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - hostReportError(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - hostReportError(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - } + + 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$1(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(createError('Request aborted', config, 'ECONNABORTED', request)); + + // Clean up request + request = null; }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!config.useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - hostReportError(err); - return true; - } - } - return false; + + // 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(createError('Network Error', config, null, request)); + + // Clean up request + request = null; }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + var transitional = config.transitional || defaults$4.transitional; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError( + timeoutErrorMessage, + config, + transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', + request)); + + // Clean up request + request = null; }; - return SafeSubscriber; - }(Subscriber)); - /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ - function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; - } - else if (destination && destination instanceof Subscriber) { - observer = destination; - } - else { - observer = 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$6.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } } - return true; - } - /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ - function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber) { - return nextOrObserver; + // Add headers to the request + if ('setRequestHeader' in request) { + utils$6.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); } - if (nextOrObserver[rxSubscriber]) { - return nextOrObserver[rxSubscriber](); + }); + } + + // Add withCredentials to request if needed + if (!utils$6.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 Cancel$2('canceled') : cancel); + request.abort(); + request = null; + }; + + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } } - if (!nextOrObserver && !error && !complete) { - return new Subscriber(empty); + + if (!requestData) { + requestData = null; } - return new Subscriber(nextOrObserver, error, complete); + + // Send the request + request.send(requestData); + }); + }; + + var utils$5 = utils$d; + var normalizeHeaderName = normalizeHeaderName$1; + var enhanceError = enhanceError$2; + + var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' + }; + + function setContentTypeIfUnset(headers, value) { + if (!utils$5.isUndefined(headers) && utils$5.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } } - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); + function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = xhr; + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = xhr; + } + return adapter; + } + + function stringifySafely(rawValue, parser, encoder) { + if (utils$5.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$5.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - function identity(x) { - return x; + return (encoder || JSON.stringify)(rawValue); } - /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ - function pipeFromArray(fns) { - if (fns.length === 0) { - return identity; + var defaults$3 = { + + transitional: { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }, + + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + + if (utils$5.isFormData(data) || + utils$5.isArrayBuffer(data) || + utils$5.isBuffer(data) || + utils$5.isStream(data) || + utils$5.isFile(data) || + utils$5.isBlob(data) + ) { + return data; } - if (fns.length === 1) { - return fns[0]; + if (utils$5.isArrayBufferView(data)) { + return data.buffer; } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; - } + if (utils$5.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils$5.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + var transitional = this.transitional || defaults$3.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ - var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; + if (strictJSONParsing || (forcedJSONParsing && utils$5.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw enhanceError(e, this, 'E_JSON_PARSE'); + } + throw e; } + } } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = toSubscriber(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); - } - else { - sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (config.useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (canReportError(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; - }()); - function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = config.Promise || Promise; + + 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, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' } - if (!promiseCtor) { - throw new Error('no Promise impl found'); + } + }; + + utils$5.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults$3.headers[method] = {}; + }); + + utils$5.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults$3.headers[method] = utils$5.merge(DEFAULT_CONTENT_TYPE); + }); + + var defaults_1 = defaults$3; + + var utils$4 = utils$d; + var defaults$2 = defaults_1; + + /** + * 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 + */ + var transformData$1 = function transformData(data, headers, fns) { + var context = this || defaults$2; + /*eslint no-param-reassign:0*/ + utils$4.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); + + return data; + }; + + var isCancel$1 = function isCancel(value) { + return !!(value && value.__CANCEL__); + }; + + var utils$3 = utils$d; + var transformData = transformData$1; + var isCancel = isCancel$1; + var defaults$1 = defaults_1; + var Cancel$1 = Cancel_1; + + /** + * Throws a `Cancel` if cancellation has been requested. + */ + function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new Cancel$1('canceled'); + } + } + + /** + * 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 + */ + var dispatchRequest$1 = 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$3.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils$3.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; } - return promiseCtor; + ); + + var adapter = config.adapter || defaults$1.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); + }); + }; + + var utils$2 = utils$d; + + /** + * 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 + */ + var mergeConfig$2 = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + function getMergedValue(target, source) { + if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { + return utils$2.merge(target, source); + } else if (utils$2.isPlainObject(source)) { + return utils$2.merge({}, source); + } else if (utils$2.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(prop) { + if (!utils$2.isUndefined(config2[prop])) { + return getMergedValue(config1[prop], config2[prop]); + } else if (!utils$2.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(prop) { + if (!utils$2.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(prop) { + if (!utils$2.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } else if (!utils$2.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, + 'transport': defaultToConfig2, + 'httpAgent': defaultToConfig2, + 'httpsAgent': defaultToConfig2, + 'cancelToken': defaultToConfig2, + 'socketPath': defaultToConfig2, + 'responseEncoding': defaultToConfig2, + 'validateStatus': mergeDirectKeys + }; + + utils$2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { + var merge = mergeMap[prop] || mergeDeepProperties; + var configValue = merge(prop); + (utils$2.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; + }; + + var data = { + "version": "0.24.0" + }; + + var VERSION = data.version; + + var validators$1 = {}; + + // eslint-disable-next-line func-names + ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators$1[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$1.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 Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); + } + + 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 TypeError('options must be an object'); + } + 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 TypeError('option ' + opt + ' must be ' + result); + } + continue; + } + if (allowUnknown !== true) { + throw Error('Unknown option ' + opt); + } + } } - /** PURE_IMPORTS_START PURE_IMPORTS_END */ - var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; + var validator$1 = { + assertOptions: assertOptions, + validators: validators$1 + }; + + var utils$1 = utils$d; + var buildURL = buildURL$2; + var InterceptorManager = InterceptorManager_1; + var dispatchRequest = dispatchRequest$1; + var mergeConfig$1 = mergeConfig$2; + var validator = validator$1; + + var validators = validator.validators; + /** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ + function Axios$1(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$1.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } + + config = mergeConfig$1(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; } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; - })(); - var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ - var SubjectSubscription = /*@__PURE__*/ (function (_super) { - __extends$1(SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; + 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()); } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; - }(Subscription)); - /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ - var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __extends$1(SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; + 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; } - return SubjectSubscriber; - }(Subscriber)); - var Subject = /*@__PURE__*/ (function (_super) { - __extends$1(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; + } + + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + } + + return promise; + }; + + Axios$1.prototype.getUri = function getUri(config) { + config = mergeConfig$1(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); + }; + + // Provide aliases for supported request methods + utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios$1.prototype[method] = function(url, config) { + return this.request(mergeConfig$1(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; + }); + + utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios$1.prototype[method] = function(url, data, config) { + return this.request(mergeConfig$1(config || {}, { + method: method, + url: url, + data: data + })); + }; + }); + + var Axios_1 = Axios$1; + + var Cancel = Cancel_1; + + /** + * 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); } - Subject.prototype[rxSubscriber] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - return new SubjectSubscription(this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); + 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 Subject; - }(Observable)); - var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __extends$1(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; + + return promise; + }; + + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return Subscription.EMPTY; - } - }; - return AnonymousSubject; - }(Subject)); - var net = {}; + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); + } + + /** + * Throws a `Cancel` 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 + }; + }; + + var CancelToken_1 = CancelToken; + + /** + * 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} + */ + var spread = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + }; + + /** + * 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 + */ + var isAxiosError = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); + }; + + var utils = utils$d; + var bind = bind$2; + var Axios = Axios_1; + var mergeConfig = mergeConfig$2; + var defaults = defaults_1; + + /** + * 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$1 = createInstance(defaults); + + // Expose Axios class to allow class inheritance + axios$1.Axios = Axios; + + // Expose Cancel & CancelToken + axios$1.Cancel = Cancel_1; + axios$1.CancelToken = CancelToken_1; + axios$1.isCancel = isCancel$1; + axios$1.VERSION = data.version; + + // Expose all/spread + axios$1.all = function all(promises) { + return Promise.all(promises); + }; + axios$1.spread = spread; + + // Expose isAxiosError + axios$1.isAxiosError = isAxiosError; + + axios$2.exports = axios$1; + + // Allow use of default import syntax in TypeScript + axios$2.exports.default = axios$1; + + var axios = axios$2.exports; var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { @@ -43108,168 +44108,104 @@ * Speculos TCP transport implementation * * @example - * import SpeculosTransport from "@ledgerhq/hw-transport-node-speculos"; - * const transport = await SpeculosTransport.open({ apduPort }); + * import SpeculosHttpTransport from "@ledgerhq/hw-transport-node-speculos-http"; + * const transport = await SpeculosHttpTransport.open(); * const res = await transport.send(0xE0, 0x01, 0, 0); */ - var SpeculosTransport = /** @class */ (function (_super) { - __extends(SpeculosTransport, _super); - function SpeculosTransport(apduSocket, opts) { + var SpeculosHttpTransport = /** @class */ (function (_super) { + __extends(SpeculosHttpTransport, _super); + function SpeculosHttpTransport(instance, opts) { var _this = _super.call(this) || this; - _this.rejectExchange = function (_e) { }; - _this.resolveExchange = function (_b) { }; - _this.automationEvents = new Subject(); /** - * Send a speculos button command - * typically "Ll" would press and release the left button - * typically "Rr" would press and release the right button - * @param {*} command + * Press and release button + * buttons available: left, right, both + * @param {*} but */ - _this.button = function (command) { + _this.button = function (but) { return new Promise(function (resolve, reject) { - log("speculos-button", command); - var _a = _this.opts, buttonPort = _a.buttonPort, host = _a.host; - if (!buttonPort) - throw new Error("buttonPort is missing"); - var socket = new net.Socket(); - socket.on("error", function (e) { - socket.destroy(); + var action = { action: "press-and-release" }; + log("speculos-button", "press-and-release", but); + _this.instance + .post("/button/".concat(but), action) + .then(function (response) { + resolve(response.data); + })["catch"](function (e) { reject(e); }); - socket.connect(buttonPort, host || "127.0.0.1", function () { - socket.write(Buffer$l.from(command, "ascii")); - socket.destroy(); - resolve(); - }); }); }; + _this.instance = instance; _this.opts = opts; - _this.apduSocket = apduSocket; - apduSocket.on("error", function (e) { - _this.emit("disconnect", new DisconnectedDevice(e.message)); - _this.rejectExchange(e); - _this.apduSocket.destroy(); - }); - apduSocket.on("end", function () { - _this.emit("disconnect", new DisconnectedDevice()); - _this.rejectExchange(new DisconnectedDeviceDuringOperation()); - }); - apduSocket.on("data", function (data) { - try { - _this.resolveExchange(decodeAPDUPayload(data)); - } - catch (e) { - _this.rejectExchange(e); - } - }); - var automationPort = opts.automationPort; - if (automationPort) { - var socket_1 = new net.Socket(); - _this.automationSocket = socket_1; - socket_1.on("error", function (e) { - log("speculos-automation-error", String(e)); - socket_1.destroy(); - }); - socket_1.on("data", function (data) { - log("speculos-automation-data", data.toString("ascii")); - var split = data.toString("ascii").split("\n"); - split - .filter(function (ascii) { return !!ascii; }) - .forEach(function (ascii) { - var json = JSON.parse(ascii); - _this.automationEvents.next(json); - }); - }); - socket_1.connect(automationPort, opts.host || "127.0.0.1"); - } return _this; } - SpeculosTransport.prototype.exchange = function (apdu) { + SpeculosHttpTransport.prototype.exchange = function (apdu) { return __awaiter(this, void 0, void 0, function () { - var hex, encoded, res; - var _this = this; + var hex; return __generator(this, function (_a) { - switch (_a.label) { - case 0: - hex = apdu.toString("hex"); - log("apdu", "=> " + hex); - encoded = encodeAPDU(apdu); - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.rejectExchange = reject; - _this.resolveExchange = resolve; - _this.apduSocket.write(encoded); - })]; - case 1: - res = _a.sent(); - log("apdu", "<= " + res.toString("hex")); - return [2 /*return*/, res]; - } + hex = apdu.toString("hex"); + log("apdu", "=> " + hex); + return [2 /*return*/, this.instance.post("/apdu", { data: hex }).then(function (r) { + // r.data is {"data": "hex value of response"} + var data = r.data.data; + log("apdu", "<= " + data); + return Buffer$l.from(data, "hex"); + })]; }); }); }; - SpeculosTransport.prototype.setScrambleKey = function () { }; - SpeculosTransport.prototype.close = function () { + SpeculosHttpTransport.prototype.close = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { - if (this.automationSocket) - this.automationSocket.destroy(); - this.apduSocket.destroy(); + // close event stream + this.eventStream.destroy(); return [2 /*return*/, Promise.resolve()]; }); }); }; - SpeculosTransport.isSupported = function () { return Promise.resolve(true); }; + SpeculosHttpTransport.isSupported = function () { return Promise.resolve(true); }; // this transport is not discoverable - SpeculosTransport.list = function () { return Promise.resolve([]); }; - SpeculosTransport.listen = function (_observer) { return ({ + SpeculosHttpTransport.list = function () { return Promise.resolve([]); }; + SpeculosHttpTransport.listen = function (_observer) { return ({ unsubscribe: function () { } }); }; - /** - * - */ - SpeculosTransport.open = function (opts) { + SpeculosHttpTransport.open = function (opts) { return new Promise(function (resolve, reject) { - var socket = new net.Socket(); - socket.on("error", function (e) { - socket.destroy(); - reject(e); - }); - socket.on("end", function () { - reject(new DisconnectedDevice("tcp closed")); - }); - socket.connect(opts.apduPort, opts.host || "127.0.0.1", function () { - // we delay a bit the transport creation to make sure the tcp does not hang up - setTimeout(function () { - resolve(new SpeculosTransport(socket, opts)); - }, 100); + var instance = axios.create(opts); + instance.defaults.baseURL = "http://localhost:5000"; + var transport = new SpeculosHttpTransport(instance, opts); + instance({ + url: "/events?stream=true", + responseType: "stream" + }) + .then(function (response) { + response.data.on("data", function (chunk) { + log("speculos-event", chunk.toString()); + // XXX: we could process display events here + // client side automation or UI tests/checks + }); + response.data.on("close", function () { + log("speculos-event", "close"); + transport.emit("disconnect", new DisconnectedDevice("Speculos exited!")); + }); + transport.eventStream = response.data; + // we are connected to speculos + resolve(transport); + })["catch"](function (error) { + reject(error); }); }); }; - return SpeculosTransport; + return SpeculosHttpTransport; }(Transport)); - function encodeAPDU(apdu) { - var size = Buffer$l.allocUnsafe(4); - size.writeUIntBE(apdu.length, 0, 4); - return Buffer$l.concat([size, apdu]); - } - function decodeAPDUPayload(data) { - var dataLength = data.readUIntBE(0, 4); // 4 bytes tells the data length - var size = dataLength + 2; // size does not include the status code so we add 2 - var payload = data.slice(4); - if (payload.length !== size) { - throw new TransportError("Expected payload of length ".concat(size, " but got ").concat(payload.length), ""); - } - return payload; - } - var SpeculosTransport$1 = /*#__PURE__*/Object.freeze({ + var SpeculosHttpTransport$1 = /*#__PURE__*/Object.freeze({ __proto__: null, - 'default': SpeculosTransport + 'default': SpeculosHttpTransport }); exports.Btc = Btc$1; exports.Log = index; - exports.SpeculosTransport = SpeculosTransport$1; + exports.SpeculosTransport = SpeculosHttpTransport$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; From 0f8c3e109e8917819bcd050ddbd7ba36ab599350 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 17 Feb 2022 00:07:48 +1100 Subject: [PATCH 68/78] revert speculos --- js/cointoolkit.js | 7 +- js/ledger.js | 3141 +++++++++------------------------------------ 2 files changed, 589 insertions(+), 2559 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index cacafb59..f16b53b3 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -676,8 +676,7 @@ $(document).ready(function() { async function getLedgerAddress(format, callback) { try { - //const transport = await window.TransportWebUSB.create(); - const transport = await window.SpeculosTransport.open(); + const transport = await window.TransportWebUSB.create(); const appBtc = new window.Btc(transport); result = await appBtc.getWalletPublicKey( coinjs.ledgerPath, @@ -705,9 +704,7 @@ $(document).ready(function() { async function getLedgerSignatures(currenttransaction, hashType, callback) { try { - //const transport = await window.TransportWebUSB.create(); - const apduPort = 40000; - const transport = await window.SpeculosTransport.open({ apduPort }); + const transport = await window.TransportWebUSB.create(); const appBtc = new window.Btc(transport); var isPeercoin = true; diff --git a/js/ledger.js b/js/ledger.js index 3af7fba0..13e4770a 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -997,10 +997,10 @@ buffer[offset + i - d] |= s * 128; } - var toString$1 = {}.toString; + var toString = {}.toString; - var isArray$2 = Array.isArray || function (arr) { - return toString$1.call(arr) == '[object Array]'; + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; @@ -1267,7 +1267,7 @@ return fromArrayLike(that, obj) } - if (obj.type === 'Buffer' && isArray$2(obj.data)) { + if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } @@ -1284,7 +1284,7 @@ } return length | 0 } - Buffer$l.isBuffer = isBuffer$1; + Buffer$l.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } @@ -1332,7 +1332,7 @@ }; Buffer$l.concat = function concat (list, length) { - if (!isArray$2(list)) { + if (!isArray$1(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } @@ -2750,7 +2750,7 @@ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { + function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) } @@ -10236,7 +10236,7 @@ var formatRegExp = /%[sdj%]/g; function format(f) { - if (!isString$1(f)) { + if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); @@ -10264,7 +10264,7 @@ } }); for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject$1(x)) { + if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); @@ -10278,24 +10278,16 @@ // If --no-deprecation is set, then it is a no-op. function deprecate(fn, msg) { // Allow for deprecating things in the process of starting up. - if (isUndefined$1(global$1.process)) { + if (isUndefined(global$1.process)) { return function() { return deprecate(fn, msg).apply(this, arguments); }; } - if (process.noDeprecation === true) { - return fn; - } - 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; @@ -10309,8 +10301,8 @@ var debugs = {}; var debugEnviron; function debuglog(set) { - if (isUndefined$1(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; + if (isUndefined(debugEnviron)) + debugEnviron = ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { @@ -10351,10 +10343,10 @@ _extend(ctx, opts); } // set default options - if (isUndefined$1(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined$1(ctx.depth)) ctx.depth = 2; - if (isUndefined$1(ctx.colors)) ctx.colors = false; - if (isUndefined$1(ctx.customInspect)) ctx.customInspect = true; + 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); } @@ -10423,13 +10415,13 @@ // Check that value is an object with an inspect function on it if (ctx.customInspect && value && - isFunction$1(value.inspect) && + isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== 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$1(ret)) { + if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; @@ -10458,14 +10450,14 @@ // Some type of object without properties can be shortcutted. if (keys.length === 0) { - if (isFunction$1(value)) { + 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$1(value)) { + if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { @@ -10476,13 +10468,13 @@ var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array - if (isArray$1(value)) { + if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions - if (isFunction$1(value)) { + if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } @@ -10493,7 +10485,7 @@ } // Make dates with properties first say the date - if (isDate$1(value)) { + if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } @@ -10532,15 +10524,15 @@ function formatPrimitive(ctx, value) { - if (isUndefined$1(value)) + if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { + if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } - if (isNumber$1(value)) + if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); @@ -10614,7 +10606,7 @@ str = ctx.stylize('[Circular]', 'special'); } } - if (isUndefined$1(name)) { + if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } @@ -10655,7 +10647,7 @@ // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. - function isArray$1(ar) { + function isArray(ar) { return Array.isArray(ar); } @@ -10667,36 +10659,36 @@ return arg === null; } - function isNumber$1(arg) { + function isNumber(arg) { return typeof arg === 'number'; } - function isString$1(arg) { + function isString(arg) { return typeof arg === 'string'; } - function isUndefined$1(arg) { + function isUndefined(arg) { return arg === void 0; } function isRegExp(re) { - return isObject$1(re) && objectToString(re) === '[object RegExp]'; + return isObject(re) && objectToString(re) === '[object RegExp]'; } - function isObject$1(arg) { + function isObject(arg) { return typeof arg === 'object' && arg !== null; } - function isDate$1(d) { - return isObject$1(d) && objectToString(d) === '[object Date]'; + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; } function isError(e) { - return isObject$1(e) && + return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } - function isFunction$1(arg) { + function isFunction(arg) { return typeof arg === 'function'; } @@ -10706,7 +10698,7 @@ function _extend(origin, add) { // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; + if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; @@ -11117,7 +11109,7 @@ function chunkInvalid(state, chunk) { var er = null; - if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; @@ -11507,7 +11499,7 @@ // proxy certain important events. var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach$1(events, function (ev) { + forEach(events, function (ev) { stream.on(ev, self.emit.bind(self, ev)); }); @@ -11649,7 +11641,7 @@ } } - function forEach$1(xs, f) { + function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } @@ -16455,7 +16447,7 @@ dependencies: dependencies }; - var utils$B = {}; + var utils$n = {}; var bn = {exports: {}}; @@ -19917,7 +19909,7 @@ throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; - var utils$A = {}; + var utils$m = {}; (function (exports) { @@ -19977,14 +19969,14 @@ else return arr; }; - }(utils$A)); + }(utils$m)); (function (exports) { var utils = exports; var BN = bn.exports; var minAssert = minimalisticAssert; - var minUtils = utils$A; + var minUtils = utils$m; utils.assert = minAssert; utils.toArray = minUtils.toArray; @@ -20097,7 +20089,7 @@ return new BN(bytes, 'hex', 'le'); } utils.intFromLE = intFromLE; - }(utils$B)); + }(utils$n)); var brorand = {exports: {}}; @@ -20170,10 +20162,10 @@ var curve = {}; var BN$8 = bn.exports; - var utils$z = utils$B; - var getNAF = utils$z.getNAF; - var getJSF = utils$z.getJSF; - var assert$e = utils$z.assert; + var utils$l = utils$n; + var getNAF = utils$l.getNAF; + var getJSF = utils$l.getJSF; + var assert$e = utils$l.assert; function BaseCurve(type, conf) { this.type = type; @@ -20436,7 +20428,7 @@ }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils$z.toArray(bytes, enc); + bytes = utils$l.toArray(bytes, enc); var len = this.p.byteLength(); @@ -20474,7 +20466,7 @@ }; BasePoint.prototype.encode = function encode(enc, compact) { - return utils$z.encode(this._encode(compact), enc); + return utils$l.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { @@ -20548,12 +20540,12 @@ return r; }; - var utils$y = utils$B; + var utils$k = utils$n; var BN$7 = bn.exports; var inherits$3 = inherits_browser.exports; var Base$2 = base; - var assert$d = utils$y.assert; + var assert$d = utils$k.assert; function ShortCurve(conf) { Base$2.call(this, 'short', conf); @@ -21489,7 +21481,7 @@ var inherits$2 = inherits_browser.exports; var Base$1 = base; - var utils$x = utils$B; + var utils$j = utils$n; function MontCurve(conf) { Base$1.call(this, 'mont', conf); @@ -21529,7 +21521,7 @@ inherits$2(Point$1, Base$1.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils$x.toArray(bytes, enc), 1); + return this.point(utils$j.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point(x, z) { @@ -21662,12 +21654,12 @@ return this.x.fromRed(); }; - var utils$w = utils$B; + var utils$i = utils$n; var BN$5 = bn.exports; var inherits$1 = inherits_browser.exports; var Base = base; - var assert$c = utils$w.assert; + var assert$c = utils$i.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() @@ -22110,12 +22102,12 @@ var hash$2 = {}; - var utils$v = {}; + var utils$h = {}; var assert$b = minimalisticAssert; var inherits = inherits_browser.exports; - utils$v.inherits = inherits; + utils$h.inherits = inherits; function isSurrogatePair(msg, i) { if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { @@ -22172,7 +22164,7 @@ } return res; } - utils$v.toArray = toArray; + utils$h.toArray = toArray; function toHex(msg) { var res = ''; @@ -22180,7 +22172,7 @@ res += zero2(msg[i].toString(16)); return res; } - utils$v.toHex = toHex; + utils$h.toHex = toHex; function htonl(w) { var res = (w >>> 24) | @@ -22189,7 +22181,7 @@ ((w & 0xff) << 24); return res >>> 0; } - utils$v.htonl = htonl; + utils$h.htonl = htonl; function toHex32(msg, endian) { var res = ''; @@ -22201,7 +22193,7 @@ } return res; } - utils$v.toHex32 = toHex32; + utils$h.toHex32 = toHex32; function zero2(word) { if (word.length === 1) @@ -22209,7 +22201,7 @@ else return word; } - utils$v.zero2 = zero2; + utils$h.zero2 = zero2; function zero8(word) { if (word.length === 7) @@ -22229,7 +22221,7 @@ else return word; } - utils$v.zero8 = zero8; + utils$h.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; @@ -22245,7 +22237,7 @@ } return res; } - utils$v.join32 = join32; + utils$h.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); @@ -22265,37 +22257,37 @@ } return res; } - utils$v.split32 = split32; + utils$h.split32 = split32; function rotr32$1(w, b) { return (w >>> b) | (w << (32 - b)); } - utils$v.rotr32 = rotr32$1; + utils$h.rotr32 = rotr32$1; function rotl32$2(w, b) { return (w << b) | (w >>> (32 - b)); } - utils$v.rotl32 = rotl32$2; + utils$h.rotl32 = rotl32$2; function sum32$3(a, b) { return (a + b) >>> 0; } - utils$v.sum32 = sum32$3; + utils$h.sum32 = sum32$3; function sum32_3$1(a, b, c) { return (a + b + c) >>> 0; } - utils$v.sum32_3 = sum32_3$1; + utils$h.sum32_3 = sum32_3$1; function sum32_4$2(a, b, c, d) { return (a + b + c + d) >>> 0; } - utils$v.sum32_4 = sum32_4$2; + utils$h.sum32_4 = sum32_4$2; function sum32_5$2(a, b, c, d, e) { return (a + b + c + d + e) >>> 0; } - utils$v.sum32_5 = sum32_5$2; + utils$h.sum32_5 = sum32_5$2; function sum64$1(buf, pos, ah, al) { var bh = buf[pos]; @@ -22306,20 +22298,20 @@ buf[pos] = hi >>> 0; buf[pos + 1] = lo; } - utils$v.sum64 = sum64$1; + utils$h.sum64 = sum64$1; function sum64_hi$1(ah, al, bh, bl) { var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } - utils$v.sum64_hi = sum64_hi$1; + utils$h.sum64_hi = sum64_hi$1; function sum64_lo$1(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } - utils$v.sum64_lo = sum64_lo$1; + utils$h.sum64_lo = sum64_lo$1; function sum64_4_hi$1(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; @@ -22334,13 +22326,13 @@ var hi = ah + bh + ch + dh + carry; return hi >>> 0; } - utils$v.sum64_4_hi = sum64_4_hi$1; + utils$h.sum64_4_hi = sum64_4_hi$1; function sum64_4_lo$1(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } - utils$v.sum64_4_lo = sum64_4_lo$1; + utils$h.sum64_4_lo = sum64_4_lo$1; function sum64_5_hi$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; @@ -22357,41 +22349,41 @@ var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } - utils$v.sum64_5_hi = sum64_5_hi$1; + utils$h.sum64_5_hi = sum64_5_hi$1; function sum64_5_lo$1(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } - utils$v.sum64_5_lo = sum64_5_lo$1; + utils$h.sum64_5_lo = sum64_5_lo$1; function rotr64_hi$1(ah, al, num) { var r = (al << (32 - num)) | (ah >>> num); return r >>> 0; } - utils$v.rotr64_hi = rotr64_hi$1; + utils$h.rotr64_hi = rotr64_hi$1; function rotr64_lo$1(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } - utils$v.rotr64_lo = rotr64_lo$1; + utils$h.rotr64_lo = rotr64_lo$1; function shr64_hi$1(ah, al, num) { return ah >>> num; } - utils$v.shr64_hi = shr64_hi$1; + utils$h.shr64_hi = shr64_hi$1; function shr64_lo$1(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } - utils$v.shr64_lo = shr64_lo$1; + utils$h.shr64_lo = shr64_lo$1; var common$5 = {}; - var utils$u = utils$v; + var utils$g = utils$h; var assert$a = minimalisticAssert; function BlockHash$4() { @@ -22410,7 +22402,7 @@ BlockHash$4.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks - msg = utils$u.toArray(msg, enc); + msg = utils$g.toArray(msg, enc); if (!this.pending) this.pending = msg; else @@ -22427,7 +22419,7 @@ if (this.pending.length === 0) this.pending = null; - msg = utils$u.join32(msg, 0, msg.length - r, this.endian); + msg = utils$g.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); } @@ -22486,8 +22478,8 @@ var common$4 = {}; - var utils$t = utils$v; - var rotr32 = utils$t.rotr32; + var utils$f = utils$h; + var rotr32 = utils$f.rotr32; function ft_1$1(s, x, y, z) { if (s === 0) @@ -22534,13 +22526,13 @@ } common$4.g1_256 = g1_256$1; - var utils$s = utils$v; + var utils$e = utils$h; var common$3 = common$5; var shaCommon$1 = common$4; - var rotl32$1 = utils$s.rotl32; - var sum32$2 = utils$s.sum32; - var sum32_5$1 = utils$s.sum32_5; + var rotl32$1 = utils$e.rotl32; + var sum32$2 = utils$e.sum32; + var sum32_5$1 = utils$e.sum32_5; var ft_1 = shaCommon$1.ft_1; var BlockHash$3 = common$3.BlockHash; @@ -22560,7 +22552,7 @@ this.W = new Array(80); } - utils$s.inherits(SHA1, BlockHash$3); + utils$e.inherits(SHA1, BlockHash$3); var _1 = SHA1; SHA1.blockSize = 512; @@ -22602,19 +22594,19 @@ SHA1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$s.toHex32(this.h, 'big'); + return utils$e.toHex32(this.h, 'big'); else - return utils$s.split32(this.h, 'big'); + return utils$e.split32(this.h, 'big'); }; - var utils$r = utils$v; + var utils$d = utils$h; var common$2 = common$5; var shaCommon = common$4; var assert$9 = minimalisticAssert; - var sum32$1 = utils$r.sum32; - var sum32_4$1 = utils$r.sum32_4; - var sum32_5 = utils$r.sum32_5; + var sum32$1 = utils$d.sum32; + var sum32_4$1 = utils$d.sum32_4; + var sum32_5 = utils$d.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; @@ -22655,7 +22647,7 @@ this.k = sha256_K; this.W = new Array(64); } - utils$r.inherits(SHA256$1, BlockHash$2); + utils$d.inherits(SHA256$1, BlockHash$2); var _256 = SHA256$1; SHA256$1.blockSize = 512; @@ -22706,12 +22698,12 @@ SHA256$1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$r.toHex32(this.h, 'big'); + return utils$d.toHex32(this.h, 'big'); else - return utils$r.split32(this.h, 'big'); + return utils$d.split32(this.h, 'big'); }; - var utils$q = utils$v; + var utils$c = utils$h; var SHA256 = _256; function SHA224() { @@ -22723,7 +22715,7 @@ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } - utils$q.inherits(SHA224, SHA256); + utils$c.inherits(SHA224, SHA256); var _224 = SHA224; SHA224.blockSize = 512; @@ -22734,26 +22726,26 @@ SHA224.prototype._digest = function digest(enc) { // Just truncate output if (enc === 'hex') - return utils$q.toHex32(this.h.slice(0, 7), 'big'); + return utils$c.toHex32(this.h.slice(0, 7), 'big'); else - return utils$q.split32(this.h.slice(0, 7), 'big'); + return utils$c.split32(this.h.slice(0, 7), 'big'); }; - var utils$p = utils$v; + var utils$b = utils$h; var common$1 = common$5; var assert$8 = minimalisticAssert; - var rotr64_hi = utils$p.rotr64_hi; - var rotr64_lo = utils$p.rotr64_lo; - var shr64_hi = utils$p.shr64_hi; - var shr64_lo = utils$p.shr64_lo; - var sum64 = utils$p.sum64; - var sum64_hi = utils$p.sum64_hi; - var sum64_lo = utils$p.sum64_lo; - var sum64_4_hi = utils$p.sum64_4_hi; - var sum64_4_lo = utils$p.sum64_4_lo; - var sum64_5_hi = utils$p.sum64_5_hi; - var sum64_5_lo = utils$p.sum64_5_lo; + var rotr64_hi = utils$b.rotr64_hi; + var rotr64_lo = utils$b.rotr64_lo; + var shr64_hi = utils$b.shr64_hi; + var shr64_lo = utils$b.shr64_lo; + var sum64 = utils$b.sum64; + var sum64_hi = utils$b.sum64_hi; + var sum64_lo = utils$b.sum64_lo; + var sum64_4_hi = utils$b.sum64_4_hi; + var sum64_4_lo = utils$b.sum64_4_lo; + var sum64_5_hi = utils$b.sum64_5_hi; + var sum64_5_lo = utils$b.sum64_5_lo; var BlockHash$1 = common$1.BlockHash; @@ -22817,7 +22809,7 @@ this.k = sha512_K; this.W = new Array(160); } - utils$p.inherits(SHA512$1, BlockHash$1); + utils$b.inherits(SHA512$1, BlockHash$1); var _512 = SHA512$1; SHA512$1.blockSize = 1024; @@ -22947,9 +22939,9 @@ SHA512$1.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$p.toHex32(this.h, 'big'); + return utils$b.toHex32(this.h, 'big'); else - return utils$p.split32(this.h, 'big'); + return utils$b.split32(this.h, 'big'); }; function ch64_hi(xh, xl, yh, yl, zh) { @@ -23068,7 +23060,7 @@ return r; } - var utils$o = utils$v; + var utils$a = utils$h; var SHA512 = _512; @@ -23087,7 +23079,7 @@ 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 ]; } - utils$o.inherits(SHA384, SHA512); + utils$a.inherits(SHA384, SHA512); var _384 = SHA384; SHA384.blockSize = 1024; @@ -23097,9 +23089,9 @@ SHA384.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$o.toHex32(this.h.slice(0, 12), 'big'); + return utils$a.toHex32(this.h.slice(0, 12), 'big'); else - return utils$o.split32(this.h.slice(0, 12), 'big'); + return utils$a.split32(this.h.slice(0, 12), 'big'); }; sha.sha1 = _1; @@ -23110,13 +23102,13 @@ var ripemd = {}; - var utils$n = utils$v; + var utils$9 = utils$h; var common = common$5; - var rotl32 = utils$n.rotl32; - var sum32 = utils$n.sum32; - var sum32_3 = utils$n.sum32_3; - var sum32_4 = utils$n.sum32_4; + var rotl32 = utils$9.rotl32; + var sum32 = utils$9.sum32; + var sum32_3 = utils$9.sum32_3; + var sum32_4 = utils$9.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { @@ -23128,7 +23120,7 @@ this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.endian = 'little'; } - utils$n.inherits(RIPEMD160, BlockHash); + utils$9.inherits(RIPEMD160, BlockHash); ripemd.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; @@ -23179,9 +23171,9 @@ RIPEMD160.prototype._digest = function digest(enc) { if (enc === 'hex') - return utils$n.toHex32(this.h, 'little'); + return utils$9.toHex32(this.h, 'little'); else - return utils$n.split32(this.h, 'little'); + return utils$9.split32(this.h, 'little'); }; function f(j, x, y, z) { @@ -23255,7 +23247,7 @@ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; - var utils$m = utils$v; + var utils$8 = utils$h; var assert$7 = minimalisticAssert; function Hmac(hash, key, enc) { @@ -23267,7 +23259,7 @@ this.inner = null; this.outer = null; - this._init(utils$m.toArray(key, enc)); + this._init(utils$8.toArray(key, enc)); } var hmac = Hmac; @@ -23304,7 +23296,7 @@ (function (exports) { var hash = exports; - hash.utils = utils$v; + hash.utils = utils$h; hash.common = common$5; hash.sha = sha; hash.ripemd = ripemd; @@ -23325,7 +23317,7 @@ var hash = hash$2; var curve$1 = curve; - var utils = utils$B; + var utils = utils$n; var assert = utils.assert; @@ -23528,7 +23520,7 @@ }(curves$2)); var hash$1 = hash$2; - var utils$l = utils$A; + var utils$7 = utils$m; var assert$6 = minimalisticAssert; function HmacDRBG$1(options) { @@ -23545,9 +23537,9 @@ this.K = null; this.V = null; - var entropy = utils$l.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils$l.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils$l.toArray(options.pers, options.persEnc || 'hex'); + var entropy = utils$7.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils$7.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils$7.toArray(options.pers, options.persEnc || 'hex'); assert$6(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._init(entropy, nonce, pers); @@ -23600,8 +23592,8 @@ entropyEnc = null; } - entropy = utils$l.toArray(entropy, entropyEnc); - add = utils$l.toArray(add, addEnc); + entropy = utils$7.toArray(entropy, entropyEnc); + add = utils$7.toArray(add, addEnc); assert$6(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); @@ -23623,7 +23615,7 @@ // Optional additional data if (add) { - add = utils$l.toArray(add, addEnc || 'hex'); + add = utils$7.toArray(add, addEnc || 'hex'); this._update(add); } @@ -23636,12 +23628,12 @@ var res = temp.slice(0, len); this._update(add); this._reseed++; - return utils$l.encode(res, enc); + return utils$7.encode(res, enc); }; var BN$4 = bn.exports; - var utils$k = utils$B; - var assert$5 = utils$k.assert; + var utils$6 = utils$n; + var assert$5 = utils$6.assert; function KeyPair$4(ec, options) { this.ec = ec; @@ -23761,8 +23753,8 @@ var BN$3 = bn.exports; - var utils$j = utils$B; - var assert$4 = utils$j.assert; + var utils$5 = utils$n; + var assert$4 = utils$5.assert; function Signature$3(options, enc) { if (options instanceof Signature$3) @@ -23826,7 +23818,7 @@ } Signature$3.prototype._importDER = function _importDER(data, enc) { - data = utils$j.toArray(data, enc); + data = utils$5.toArray(data, enc); var p = new Position(); if (data[p.place++] !== 0x30) { return false; @@ -23921,15 +23913,15 @@ var res = [ 0x30 ]; constructLength(res, backHalf.length); res = res.concat(backHalf); - return utils$j.encode(res, enc); + return utils$5.encode(res, enc); }; var BN$2 = bn.exports; var HmacDRBG = hmacDrbg; - var utils$i = utils$B; + var utils$4 = utils$n; var curves$1 = curves$2; var rand = brorand.exports; - var assert$3 = utils$i.assert; + var assert$3 = utils$4.assert; var KeyPair$3 = key$1; var Signature$2 = signature$1; @@ -24166,10 +24158,10 @@ throw new Error('Unable to find valid recovery factor'); }; - var utils$h = utils$B; - var assert$2 = utils$h.assert; - var parseBytes$2 = utils$h.parseBytes; - var cachedProperty$1 = utils$h.cachedProperty; + var utils$3 = utils$n; + var assert$2 = utils$3.assert; + var parseBytes$2 = utils$3.parseBytes; + var cachedProperty$1 = utils$3.cachedProperty; /** * @param {EDDSA} eddsa - instance @@ -24251,20 +24243,20 @@ KeyPair$2.prototype.getSecret = function getSecret(enc) { assert$2(this._secret, 'KeyPair is public only'); - return utils$h.encode(this.secret(), enc); + return utils$3.encode(this.secret(), enc); }; KeyPair$2.prototype.getPublic = function getPublic(enc) { - return utils$h.encode(this.pubBytes(), enc); + return utils$3.encode(this.pubBytes(), enc); }; var key = KeyPair$2; var BN$1 = bn.exports; - var utils$g = utils$B; - var assert$1 = utils$g.assert; - var cachedProperty = utils$g.cachedProperty; - var parseBytes$1 = utils$g.parseBytes; + var utils$2 = utils$n; + var assert$1 = utils$2.assert; + var cachedProperty = utils$2.cachedProperty; + var parseBytes$1 = utils$2.parseBytes; /** * @param {EDDSA} eddsa - eddsa instance @@ -24319,16 +24311,16 @@ }; Signature$1.prototype.toHex = function toHex() { - return utils$g.encode(this.toBytes(), 'hex').toUpperCase(); + return utils$2.encode(this.toBytes(), 'hex').toUpperCase(); }; var signature = Signature$1; var hash = hash$2; var curves = curves$2; - var utils$f = utils$B; - var assert = utils$f.assert; - var parseBytes = utils$f.parseBytes; + var utils$1 = utils$n; + var assert = utils$1.assert; + var parseBytes = utils$1.parseBytes; var KeyPair$1 = key; var Signature = signature; @@ -24387,7 +24379,7 @@ var hash = this.hash(); for (var i = 0; i < arguments.length; i++) hash.update(arguments[i]); - return utils$f.intFromLE(hash.digest()).umod(this.curve.n); + return utils$1.intFromLE(hash.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { @@ -24419,13 +24411,13 @@ }; EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils$f.parseBytes(bytes); + bytes = utils$1.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$f.intFromLE(normed); + var y = utils$1.intFromLE(normed); return this.curve.pointFromY(y, xIsOdd); }; @@ -24434,7 +24426,7 @@ }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils$f.intFromLE(bytes); + return utils$1.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { @@ -24446,7 +24438,7 @@ var elliptic = exports; elliptic.version = require$$0$1.version; - elliptic.utils = utils$B; + elliptic.utils = utils$n; elliptic.rand = brorand.exports; elliptic.curve = curve; elliptic.curves = curves$2; @@ -24540,7 +24532,7 @@ const THROW_BAD_EXTRA_DATA = 'Expected Extra Data (32 bytes)'; function isScalar (x) { - return isBuffer$1(x) && x.length === 32 + return isBuffer(x) && x.length === 32 } function isOrderScalar (x) { @@ -24549,7 +24541,7 @@ } function isPoint (p) { - if (!isBuffer$1(p)) return false + if (!isBuffer(p)) return false if (p.length < 33) return false const t = p[0]; @@ -24586,7 +24578,7 @@ function isSignature (value) { const r = value.slice(0, 32); const s = value.slice(32, 64); - return isBuffer$1(value) && value.length === 64 && + return isBuffer(value) && value.length === 64 && r.compare(EC_GROUP_ORDER) < 0 && s.compare(EC_GROUP_ORDER) < 0 } @@ -24939,7 +24931,7 @@ var ERRORS$1 = errors; function _Buffer (value) { - return isBuffer$1(value) + return isBuffer(value) } function Hex (value) { @@ -25333,7 +25325,7 @@ return decodeRaw(bs58check$4.decode(string), version) } - function encode$i (version, privateKey, compressed) { + function encode$h (version, privateKey, compressed) { if (typeof version === 'number') return bs58check$4.encode(encodeRaw(version, privateKey, compressed)) return bs58check$4.encode( @@ -25348,7 +25340,7 @@ var wif$2 = { decode: decode$g, decodeRaw: decodeRaw, - encode: encode$i, + encode: encode$h, encodeRaw: encodeRaw }; @@ -25746,7 +25738,7 @@ ? 1 : 0; } - function encode$h(_number) { + function encode$g(_number) { let value = Math.abs(_number); const size = scriptNumSize(value); const buffer = Buffer$l.allocUnsafe(size); @@ -25762,7 +25754,7 @@ } return buffer; } - script_number.encode = encode$h; + script_number.encode = encode$g; var script_signature = {}; @@ -25907,7 +25899,7 @@ * 62300 => 0x00f35c * -62300 => 0xff0ca4 */ - function encode$g (r, s) { + function encode$f (r, s) { var lenR = r.length; var lenS = s.length; if (lenR === 0) throw new Error('R length is zero') @@ -25937,7 +25929,7 @@ var bip66$1 = { check: check$m, decode: decode$e, - encode: encode$g + encode: encode$f }; Object.defineProperty(script_signature, '__esModule', { value: true }); @@ -25973,7 +25965,7 @@ return { signature, hashType }; } script_signature.decode = decode$d; - function encode$f(signature, hashType) { + function encode$e(signature, hashType) { typeforce$8( { signature: types$9.BufferN(64), @@ -25990,7 +25982,7 @@ const s = toDER(signature.slice(32, 64)); return Buffer$l.concat([bip66.encode(r, s), hashTypeBuffer]); } - script_signature.encode = encode$f; + script_signature.encode = encode$e; var OP_FALSE = 0; var OP_0 = 0; @@ -26240,7 +26232,7 @@ : 5 } - function encode$e (buffer, number, offset) { + function encode$d (buffer, number, offset) { var size = encodingLength$2(number); // ~6 bit @@ -26305,7 +26297,7 @@ var pushdataBitcoin = { encodingLength: encodingLength$2, - encode: encode$e, + encode: encode$d, decode: decode$c }; @@ -26353,13 +26345,13 @@ if (buffer[0] === 0x81) return exports.OPS.OP_1NEGATE; } function chunksIsBuffer(buf) { - return isBuffer$1(buf); + return isBuffer(buf); } function chunksIsArray(buf) { return types.Array(buf); } function singleChunkIsBuffer(buf) { - return isBuffer$1(buf); + return isBuffer(buf); } function compile(chunks) { // TODO: remove me @@ -26488,7 +26480,7 @@ } exports.isDefinedHashType = isDefinedHashType; function isCanonicalScriptSignature(buffer) { - if (!isBuffer$1(buffer)) return false; + if (!isBuffer(buffer)) return false; if (!isDefinedHashType(buffer[buffer.length - 1])) return false; return bip66.check(buffer.slice(0, -1)); } @@ -27128,7 +27120,7 @@ if (a.input) { const chunks = _chunks(); if (!chunks || chunks.length < 1) throw new TypeError('Input too short'); - if (!isBuffer$1(_redeem().output)) + if (!isBuffer(_redeem().output)) throw new TypeError('Input is invalid'); checkRedeem(_redeem()); } @@ -27197,7 +27189,7 @@ return chk } - function encode$d (prefix, words, LIMIT) { + function encode$c (prefix, words, LIMIT) { LIMIT = LIMIT || 90; if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') @@ -27334,7 +27326,7 @@ var bech32$3 = { decodeUnsafe: decodeUnsafe, decode: decode$b, - encode: encode$d, + encode: encode$c, toWordsUnsafe: toWordsUnsafe, toWords: toWords, fromWordsUnsafe: fromWordsUnsafe, @@ -27491,7 +27483,7 @@ } function chunkHasUncompressedPubkey(chunk) { if ( - isBuffer$1(chunk) && + isBuffer(chunk) && chunk.length === 65 && chunk[0] === 0x04 && ecc$1.isPoint(chunk) @@ -27960,7 +27952,7 @@ if (n < 0 || n > MAX_SAFE_INTEGER$3 || n % 1 !== 0) throw new RangeError('value out of range') } - function encode$c (number, buffer, offset) { + function encode$b (number, buffer, offset) { checkUInt53$1(number); if (!buffer) buffer = Buffer.allocUnsafe(encodingLength$1(number)); @@ -27970,26 +27962,26 @@ // 8 bit if (number < 0xfd) { buffer.writeUInt8(number, offset); - encode$c.bytes = 1; + encode$b.bytes = 1; // 16 bit } else if (number <= 0xffff) { buffer.writeUInt8(0xfd, offset); buffer.writeUInt16LE(number, offset + 1); - encode$c.bytes = 3; + encode$b.bytes = 3; // 32 bit } else if (number <= 0xffffffff) { buffer.writeUInt8(0xfe, offset); buffer.writeUInt32LE(number, offset + 1); - encode$c.bytes = 5; + encode$b.bytes = 5; // 64 bit } else { buffer.writeUInt8(0xff, offset); buffer.writeUInt32LE(number >>> 0, offset + 1); buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5); - encode$c.bytes = 9; + encode$b.bytes = 9; } return buffer @@ -28039,7 +28031,7 @@ ) } - var varuintBitcoin = { encode: encode$c, decode: decode$a, encodingLength: encodingLength$1 }; + var varuintBitcoin = { encode: encode$b, decode: decode$a, encodingLength: encodingLength$1 }; Object.defineProperty(bufferutils, '__esModule', { value: true }); const types$6 = types$a; @@ -28924,7 +28916,7 @@ return data; } globalXpub$1.decode = decode$9; - function encode$b(data) { + function encode$a(data) { const head = Buffer$l.from([typeFields_1$b.GlobalTypes.GLOBAL_XPUB]); const key = Buffer$l.concat([head, data.extendedPubkey]); const splitPath = data.path.split('/'); @@ -28943,7 +28935,7 @@ value, }; } - globalXpub$1.encode = encode$b; + globalXpub$1.encode = encode$a; globalXpub$1.expected = '{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }'; function check$l(data) { @@ -28951,10 +28943,10 @@ const mfp = data.masterFingerprint; const p = data.path; return ( - isBuffer$1(epk) && + isBuffer(epk) && epk.length === 78 && [2, 3].indexOf(epk[45]) > -1 && - isBuffer$1(mfp) && + isBuffer(mfp) && mfp.length === 4 && typeof p === 'string' && !!p.match(/^m(\/\d+'?)+$/) @@ -28975,13 +28967,13 @@ Object.defineProperty(unsignedTx$1, '__esModule', { value: true }); const typeFields_1$a = typeFields; - function encode$a(data) { + function encode$9(data) { return { key: Buffer$l.from([typeFields_1$a.GlobalTypes.UNSIGNED_TX]), value: data.toBuffer(), }; } - unsignedTx$1.encode = encode$a; + unsignedTx$1.encode = encode$9; var finalScriptSig$1 = {}; @@ -28997,17 +28989,17 @@ return keyVal.value; } finalScriptSig$1.decode = decode$8; - function encode$9(data) { + function encode$8(data) { const key = Buffer$l.from([typeFields_1$9.InputTypes.FINAL_SCRIPTSIG]); return { key, value: data, }; } - finalScriptSig$1.encode = encode$9; + finalScriptSig$1.encode = encode$8; finalScriptSig$1.expected = 'Buffer'; function check$k(data) { - return isBuffer$1(data); + return isBuffer(data); } finalScriptSig$1.check = check$k; function canAdd$5(currentData, newData) { @@ -29029,17 +29021,17 @@ return keyVal.value; } finalScriptWitness$1.decode = decode$7; - function encode$8(data) { + function encode$7(data) { const key = Buffer$l.from([typeFields_1$8.InputTypes.FINAL_SCRIPTWITNESS]); return { key, value: data, }; } - finalScriptWitness$1.encode = encode$8; + finalScriptWitness$1.encode = encode$7; finalScriptWitness$1.expected = 'Buffer'; function check$j(data) { - return isBuffer$1(data); + return isBuffer(data); } finalScriptWitness$1.check = check$j; function canAdd$4(currentData, newData) { @@ -29063,16 +29055,16 @@ return keyVal.value; } nonWitnessUtxo$1.decode = decode$6; - function encode$7(data) { + function encode$6(data) { return { key: Buffer$l.from([typeFields_1$7.InputTypes.NON_WITNESS_UTXO]), value: data, }; } - nonWitnessUtxo$1.encode = encode$7; + nonWitnessUtxo$1.encode = encode$6; nonWitnessUtxo$1.expected = 'Buffer'; function check$i(data) { - return isBuffer$1(data); + return isBuffer(data); } nonWitnessUtxo$1.check = check$i; function canAdd$3(currentData, newData) { @@ -29107,19 +29099,19 @@ }; } partialSig$1.decode = decode$5; - function encode$6(pSig) { + function encode$5(pSig) { const head = Buffer$l.from([typeFields_1$6.InputTypes.PARTIAL_SIG]); return { key: Buffer$l.concat([head, pSig.pubkey]), value: pSig.signature, }; } - partialSig$1.encode = encode$6; + partialSig$1.encode = encode$5; partialSig$1.expected = '{ pubkey: Buffer; signature: Buffer; }'; function check$h(data) { return ( - isBuffer$1(data.pubkey) && - isBuffer$1(data.signature) && + isBuffer(data.pubkey) && + isBuffer(data.signature) && [33, 65].includes(data.pubkey.length) && [2, 3, 4].includes(data.pubkey[0]) && isDerSigWithSighash(data.signature) @@ -29127,7 +29119,7 @@ } partialSig$1.check = check$h; function isDerSigWithSighash(buf) { - if (!isBuffer$1(buf) || buf.length < 9) return false; + if (!isBuffer(buf) || buf.length < 9) return false; if (buf[0] !== 0x30) return false; if (buf.length !== buf[1] + 3) return false; if (buf[2] !== 0x02) return false; @@ -29161,14 +29153,14 @@ return keyVal.value.toString('utf8'); } porCommitment$1.decode = decode$4; - function encode$5(data) { + function encode$4(data) { const key = Buffer$l.from([typeFields_1$5.InputTypes.POR_COMMITMENT]); return { key, value: Buffer$l.from(data, 'utf8'), }; } - porCommitment$1.encode = encode$5; + porCommitment$1.encode = encode$4; porCommitment$1.expected = 'string'; function check$g(data) { return typeof data === 'string'; @@ -29193,7 +29185,7 @@ return keyVal.value.readUInt32LE(0); } sighashType$1.decode = decode$3; - function encode$4(data) { + function encode$3(data) { const key = Buffer$l.from([typeFields_1$4.InputTypes.SIGHASH_TYPE]); const value = Buffer$l.allocUnsafe(4); value.writeUInt32LE(data, 0); @@ -29202,7 +29194,7 @@ value, }; } - sighashType$1.encode = encode$4; + sighashType$1.encode = encode$3; sighashType$1.expected = 'number'; function check$f(data) { return typeof data === 'number'; @@ -29226,38 +29218,38 @@ if (n < 0 || n > MAX_SAFE_INTEGER$2 || n % 1 !== 0) throw new RangeError('value out of range'); } - function encode$3(_number, buffer, offset) { + function encode$2(_number, buffer, offset) { checkUInt53(_number); if (!buffer) buffer = Buffer$l.allocUnsafe(encodingLength(_number)); - if (!isBuffer$1(buffer)) + if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; // 8 bit if (_number < 0xfd) { buffer.writeUInt8(_number, offset); - Object.assign(encode$3, { bytes: 1 }); + Object.assign(encode$2, { bytes: 1 }); // 16 bit } else if (_number <= 0xffff) { buffer.writeUInt8(0xfd, offset); buffer.writeUInt16LE(_number, offset + 1); - Object.assign(encode$3, { bytes: 3 }); + Object.assign(encode$2, { bytes: 3 }); // 32 bit } else if (_number <= 0xffffffff) { buffer.writeUInt8(0xfe, offset); buffer.writeUInt32LE(_number, offset + 1); - Object.assign(encode$3, { bytes: 5 }); + Object.assign(encode$2, { bytes: 5 }); // 64 bit } else { buffer.writeUInt8(0xff, offset); buffer.writeUInt32LE(_number >>> 0, offset + 1); buffer.writeUInt32LE((_number / 0x100000000) | 0, offset + 5); - Object.assign(encode$3, { bytes: 9 }); + Object.assign(encode$2, { bytes: 9 }); } return buffer; } - varint$1.encode = encode$3; + varint$1.encode = encode$2; function decode$2(buffer, offset) { - if (!isBuffer$1(buffer)) + if (!isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance'); if (!offset) offset = 0; const first = buffer.readUInt8(offset); @@ -29384,7 +29376,7 @@ }; } witnessUtxo$1.decode = decode$1; - function encode$2(data) { + function encode$1(data) { const { script, value } = data; const varintLen = varuint$2.encodingLength(script.length); const result = Buffer$l.allocUnsafe(8 + varintLen + script.length); @@ -29396,10 +29388,10 @@ value: result, }; } - witnessUtxo$1.encode = encode$2; + witnessUtxo$1.encode = encode$1; witnessUtxo$1.expected = '{ script: Buffer; value: number; }'; function check$e(data) { - return isBuffer$1(data.script) && typeof data.value === 'number'; + return isBuffer(data.script) && typeof data.value === 'number'; } witnessUtxo$1.check = check$e; function canAdd(currentData, newData) { @@ -29470,8 +29462,8 @@ '{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }'; function check(data) { return ( - isBuffer$1(data.pubkey) && - isBuffer$1(data.masterFingerprint) && + isBuffer(data.pubkey) && + isBuffer(data.masterFingerprint) && typeof data.path === 'string' && [33, 65].includes(data.pubkey.length) && [2, 3, 4].includes(data.pubkey[0]) && @@ -29539,7 +29531,7 @@ } const expected = 'Buffer'; function check(data) { - return isBuffer$1(data); + return isBuffer(data); } function canAdd(currentData, newData) { return !!currentData && !!newData && currentData.redeemScript === undefined; @@ -29576,7 +29568,7 @@ } const expected = 'Buffer'; function check(data) { - return isBuffer$1(data); + return isBuffer(data); } function canAdd(currentData, newData) { return ( @@ -30140,7 +30132,7 @@ return set; } - var utils$e = {}; + var utils = {}; (function (exports) { Object.defineProperty(exports, '__esModule', { value: true }); @@ -30265,7 +30257,7 @@ } exports.addOutputAttributes = addOutputAttributes; function defaultVersionSetter(version, txBuf) { - if (!isBuffer$1(txBuf) || txBuf.length < 4) { + if (!isBuffer(txBuf) || txBuf.length < 4) { throw new Error('Set Version: Invalid Transaction'); } txBuf.writeUInt32LE(version, 0); @@ -30273,20 +30265,20 @@ } exports.defaultVersionSetter = defaultVersionSetter; function defaultLocktimeSetter(locktime, txBuf) { - if (!isBuffer$1(txBuf) || txBuf.length < 4) { + if (!isBuffer(txBuf) || txBuf.length < 4) { throw new Error('Set Locktime: Invalid Transaction'); } txBuf.writeUInt32LE(locktime, txBuf.length - 4); return txBuf; } exports.defaultLocktimeSetter = defaultLocktimeSetter; - }(utils$e)); + }(utils)); Object.defineProperty(psbt, '__esModule', { value: true }); const combiner_1 = combiner; const parser_1 = parser; const typeFields_1 = typeFields; - const utils_1$1 = utils$e; + const utils_1$1 = utils; class Psbt$1 { constructor(tx) { this.inputs = []; @@ -30433,7 +30425,7 @@ Object.defineProperty(psbt$1, '__esModule', { value: true }); const bip174_1 = psbt; const varuint = varint$1; - const utils_1 = utils$e; + const utils_1 = utils; const address_1 = address$1; const bufferutils_1$1 = bufferutils; const crypto_1$1 = crypto$2; @@ -31066,7 +31058,7 @@ if ( input.hash === undefined || input.index === undefined || - (!isBuffer$1(input.hash) && typeof input.hash !== 'string') || + (!isBuffer(input.hash) && typeof input.hash !== 'string') || typeof input.index !== 'number' ) { throw new Error('Error adding input.'); @@ -31081,7 +31073,7 @@ if ( output.script === undefined || output.value === undefined || - !isBuffer$1(output.script) || + !isBuffer(output.script) || typeof output.value !== 'number' ) { throw new Error('Error adding output.'); @@ -31490,7 +31482,7 @@ return scriptItems .concat(witnessItems) .filter(item => { - return isBuffer$1(item) && bscript$f.isCanonicalScriptSignature(item); + return isBuffer(item) && bscript$f.isCanonicalScriptSignature(item); }) .map(sig => ({ signature: sig })); } @@ -31736,7 +31728,7 @@ if (!decomp) return; const lastItem = decomp[decomp.length - 1]; if ( - !isBuffer$1(lastItem) || + !isBuffer(lastItem) || isPubkeyLike(lastItem) || isSigLike(lastItem) ) @@ -32054,7 +32046,7 @@ const chunks = bscript$5.decompile(script); if (chunks.length < 1) return false; const lastChunk = chunks[chunks.length - 1]; - if (!isBuffer$1(lastChunk)) return false; + if (!isBuffer(lastChunk)) return false; const scriptSigChunks = bscript$5.decompile( bscript$5.compile(chunks.slice(0, -1)), ); @@ -32142,14 +32134,14 @@ check$2.toJSON = () => { return 'Witness commitment output'; }; - function encode$1(commitment) { + function encode(commitment) { typeforce$2(types$2.Hash256bit, commitment); const buffer = Buffer$l.allocUnsafe(36); HEADER.copy(buffer, 0); commitment.copy(buffer, 4); return bscript$3.compile([script_1$3.OPS.OP_RETURN, buffer]); } - output$3.encode = encode$1; + output$3.encode = encode; function decode(buffer) { typeforce$2(check$2, buffer); return bscript$3.decompile(buffer)[1].slice(4, 36); @@ -32204,7 +32196,7 @@ typeforce$1(typeforce$1.Array, chunks); if (chunks.length < 1) return false; const witnessScript = chunks[chunks.length - 1]; - if (!isBuffer$1(witnessScript)) return false; + if (!isBuffer(witnessScript)) return false; const witnessScriptChunks = bscript$1.decompile(witnessScript); // is witnessScript a valid script? if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false; @@ -34670,7 +34662,7 @@ throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity; - trim$1(this); + trim(this); } get max () { return this[MAX] @@ -34688,7 +34680,7 @@ throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA; - trim$1(this); + trim(this); } get maxAge () { return this[MAX_AGE] @@ -34707,7 +34699,7 @@ this[LENGTH] += hit.length; }); } - trim$1(this); + trim(this); } get lengthCalculator () { return this[LENGTH_CALCULATOR] } @@ -34796,7 +34788,7 @@ this[LENGTH] += len - item.length; item.length = len; this.get(key); - trim$1(this); + trim(this); return true } @@ -34813,7 +34805,7 @@ this[LENGTH] += hit.length; this[LRU_LIST].unshift(hit); this[CACHE].set(key, this[LRU_LIST].head); - trim$1(this); + trim(this); return true } @@ -34899,7 +34891,7 @@ : self[MAX_AGE] && (diff > self[MAX_AGE]) }; - const trim$1 = self => { + const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { @@ -36293,7 +36285,7 @@ return new ripemd160$2().update(sha$3("sha256").update(buffer).digest()).digest(); } - var __extends$5 = (undefined && undefined.__extends) || (function () { + var __extends$4 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36321,7 +36313,7 @@ * and calls an abstract method to do the actual work. */ var SingleKeyAccount = /** @class */ (function (_super) { - __extends$5(SingleKeyAccount, _super); + __extends$4(SingleKeyAccount, _super); function SingleKeyAccount() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36352,7 +36344,7 @@ return SingleKeyAccount; }(BaseAccount)); var p2pkh = /** @class */ (function (_super) { - __extends$5(p2pkh, _super); + __extends$4(p2pkh, _super); function p2pkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36380,7 +36372,7 @@ return p2pkh; }(SingleKeyAccount)); var p2tr = /** @class */ (function (_super) { - __extends$5(p2tr, _super); + __extends$4(p2tr, _super); function p2tr() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36446,7 +36438,7 @@ return p2tr; }(SingleKeyAccount)); var p2wpkhWrapped = /** @class */ (function (_super) { - __extends$5(p2wpkhWrapped, _super); + __extends$4(p2wpkhWrapped, _super); function p2wpkhWrapped() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36489,7 +36481,7 @@ return p2wpkhWrapped; }(SingleKeyAccount)); var p2wpkh = /** @class */ (function (_super) { - __extends$5(p2wpkh, _super); + __extends$4(p2wpkh, _super); function p2wpkh() { return _super !== null && _super.apply(this, arguments) || this; } @@ -36725,7 +36717,7 @@ return tx.buffer(); } - var __extends$4 = (undefined && undefined.__extends) || (function () { + var __extends$3 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -36786,7 +36778,7 @@ })(psbtOut || (psbtOut = {})); var PSBT_MAGIC_BYTES = Buffer$l.from([0x70, 0x73, 0x62, 0x74, 0xff]); var NoSuchEntry = /** @class */ (function (_super) { - __extends$4(NoSuchEntry, _super); + __extends$3(NoSuchEntry, _super); function NoSuchEntry() { return _super !== null && _super.apply(this, arguments) || this; } @@ -37458,7 +37450,7 @@ ]); } - var __awaiter$f = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37467,7 +37459,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$f = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37548,9 +37540,9 @@ */ BtcNew.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, xpubComponents; - return __generator$f(this, function (_b) { + return __generator$e(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -37575,9 +37567,9 @@ */ BtcNew.prototype.getWalletPublicKey = function (path, opts) { var _a, _b; - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElements, xpub, display, address, components, uncompressedPubkey; - return __generator$f(this, function (_c) { + return __generator$e(this, function (_c) { switch (_c.label) { case 0: pathElements = pathStringToArray(path); @@ -37615,9 +37607,9 @@ * ourselves, but we don't at this time, and instead return an empty ("") address. */ BtcNew.prototype.getWalletAddress = function (pathElements, descrTempl, display) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var accountPath, accountXpub, masterFingerprint, policy, changeAndIndex; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: accountPath = hardenedPathOf(pathElements); @@ -37646,9 +37638,9 @@ * transaction is returned. */ BtcNew.prototype.createPaymentTransactionNew = function (arg) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputCount, psbt, masterFp, accountType, notifyCount, progress, accountXpub, accountPath, i, pathElems, outputsConcat, outputsBufferReader, outputCount, changeData, changeFound, i, amount, outputScript, isChange, changePath, pubkey, key, p, firstSigned, progressCallback, serializedTx; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputCount = arg.inputs.length; @@ -37759,9 +37751,9 @@ * properties depend on the accountType used. */ BtcNew.prototype.outputScriptAt = function (accountPath, accountType, path) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var pathElems, i, xpub, pubkey, cond; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: if (!path) @@ -37790,9 +37782,9 @@ * public key and its derivation path. */ BtcNew.prototype.setInput = function (psbt, i, input, pathElements, accountType, masterFP, sigHashType) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var inputTx, spentOutputIndex, redeemScript, sequence, inputTxBuffer, inputTxid, xpubBase58, pubkey, spentTxOutput, spendCondition, spentOutput; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: inputTx = input[0]; @@ -37837,9 +37829,9 @@ * to the appropriate input fields of the PSBT. */ BtcNew.prototype.signPsbt = function (psbt, walletPolicy, progressCallback) { - return __awaiter$f(this, void 0, void 0, function () { + return __awaiter$e(this, void 0, void 0, function () { var sigs; - return __generator$f(this, function (_a) { + return __generator$e(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.client.signPsbt(psbt, walletPolicy, Buffer$l.alloc(32, 0), progressCallback)]; case 1: @@ -37956,7 +37948,7 @@ }; return __assign$4.apply(this, arguments); }; - var __awaiter$e = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -37965,7 +37957,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$e = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -37999,9 +37991,9 @@ cashaddr: 3 }; function getWalletPublicKey(transport, options) { - return __awaiter$e(this, void 0, void 0, function () { + return __awaiter$d(this, void 0, void 0, function () { var _a, path, verify, format, buffer, p1, p2, response, publicKeyLength, addressLength, publicKey, bitcoinAddress, chainCode; - return __generator$e(this, function (_b) { + return __generator$d(this, function (_b) { switch (_b.label) { case 0: _a = __assign$4({ verify: false, format: "legacy" }, options), path = _a.path, verify = _a.verify, format = _a.format; @@ -38045,7 +38037,7 @@ */ var invariant = function(condition, format, a, b, c, d, e, f) { - if (process.env.NODE_ENV !== 'production') { + { if (format === undefined) { throw new Error('invariant requires an error message argument'); } @@ -38074,7 +38066,7 @@ var browser = invariant; - var __awaiter$d = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38083,7 +38075,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$d = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38122,9 +38114,9 @@ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; function getTrustedInputRaw(transport, transactionData, indexLookup) { - return __awaiter$d(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var data, firstRound, prefix, trustedInput, res; - return __generator$d(this, function (_a) { + return __generator$c(this, function (_a) { switch (_a.label) { case 0: firstRound = false; @@ -38148,11 +38140,11 @@ } function getTrustedInput(transport, indexLookup, transaction, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$d(this, void 0, void 0, function () { + return __awaiter$c(this, void 0, void 0, function () { var version, inputs, outputs, locktime, nExpiryHeight, extraData, isDecred, isXST, processScriptBlocks, processWholeScriptBlock, inputs_1, inputs_1_1, input, isXSTV2, treeField, data, e_1_1, outputs_1, outputs_1_1, output, data, e_2_1, endData, extraPart, data, res; var e_1, _a, e_2, _b; var _this = this; - return __generator$d(this, function (_c) { + return __generator$c(this, function (_c) { switch (_c.label) { case 0: version = transaction.version, inputs = transaction.inputs, outputs = transaction.outputs, locktime = transaction.locktime, nExpiryHeight = transaction.nExpiryHeight, extraData = transaction.extraData; @@ -38161,10 +38153,10 @@ } isDecred = additionals.includes("decred"); isXST = additionals.includes("stealthcoin"); - processScriptBlocks = function (script, sequence) { return __awaiter$d(_this, void 0, void 0, function () { + processScriptBlocks = function (script, sequence) { return __awaiter$c(_this, void 0, void 0, function () { var seq, scriptBlocks, offset, blockSize, res, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_3_1; var e_3, _a; - return __generator$d(this, function (_b) { + return __generator$c(this, function (_b) { switch (_b.label) { case 0: seq = sequence || Buffer$l.alloc(0); @@ -38338,7 +38330,7 @@ }); } - var __awaiter$c = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38347,7 +38339,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$c = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38405,10 +38397,10 @@ if (overwinter === void 0) { overwinter = false; } if (additionals === void 0) { additionals = []; } if (useTrustedInputForSegwit === void 0) { useTrustedInputForSegwit = false; } - return __awaiter$c(this, void 0, void 0, function () { + return __awaiter$b(this, void 0, void 0, function () { var data, i, isDecred, _a, _b, input, prefix, inputValue, scriptBlocks, offset, blockSize, scriptBlocks_1, scriptBlocks_1_1, scriptBlock, e_1_1, e_2_1; var e_2, _c, e_1, _d; - return __generator$c(this, function (_e) { + return __generator$b(this, function (_e) { switch (_e.label) { case 0: data = Buffer$l.concat([ @@ -38591,7 +38583,7 @@ }); } - var __awaiter$b = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38600,7 +38592,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$b = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38633,9 +38625,9 @@ } function hashOutputFull(transport, outputScript, additionals) { if (additionals === void 0) { additionals = []; } - return __awaiter$b(this, void 0, void 0, function () { + return __awaiter$a(this, void 0, void 0, function () { var offset, p1, isDecred, blockSize, p1_1, data; - return __generator$b(this, function (_a) { + return __generator$a(this, function (_a) { switch (_a.label) { case 0: offset = 0; @@ -38665,7 +38657,7 @@ }); } - var __awaiter$a = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38674,7 +38666,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$a = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38701,9 +38693,9 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; - var getAppAndVersion = function (transport) { return __awaiter$a(void 0, void 0, void 0, function () { + var getAppAndVersion = function (transport) { return __awaiter$9(void 0, void 0, void 0, function () { var r, i, format, nameLength, name, versionLength, version, flagLength, flags; - return __generator$a(this, function (_a) { + return __generator$9(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, transport.send(0xb0, 0x01, 0x00, 0x00)]; case 1: @@ -38746,7 +38738,7 @@ }; return __assign$3.apply(this, arguments); }; - var __awaiter$9 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -38755,7 +38747,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$9 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -38803,10 +38795,10 @@ onDeviceSignatureRequested: function () { } }; function createTransaction(transport, arg) { - return __awaiter$9(this, void 0, void 0, function () { + return __awaiter$8(this, void 0, void 0, function () { var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; var e_2, _a; - return __generator$9(this, function (_b) { + return __generator$8(this, function (_b) { switch (_b.label) { case 0: signTx = __assign$3(__assign$3({}, defaultsSignTransaction), arg); @@ -39129,7 +39121,7 @@ }); } - var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -39138,7 +39130,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$8 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -39167,9 +39159,9 @@ }; function signMessage(transport, _a) { var path = _a.path, messageHex = _a.messageHex; - return __awaiter$8(this, void 0, void 0, function () { + return __awaiter$7(this, void 0, void 0, function () { var paths, message, offset, _loop_1, res, v, r, s; - return __generator$8(this, function (_b) { + return __generator$7(this, function (_b) { switch (_b.label) { case 0: paths = bip32Path.fromString(path).toPathArray(); @@ -39177,7 +39169,7 @@ offset = 0; _loop_1 = function () { var maxChunkSize, chunkSize, buffer; - return __generator$8(this, function (_c) { + return __generator$7(this, function (_c) { switch (_c.label) { case 0: maxChunkSize = offset === 0 @@ -39249,210 +39241,6 @@ }; return __assign$2.apply(this, arguments); }; - var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator$7 = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - var __values$4 = (undefined && undefined.__values) || function(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - var defaultArg = { - lockTime: DEFAULT_LOCKTIME, - sigHashType: SIGHASH_ALL, - segwit: false, - transactionVersion: DEFAULT_VERSION - }; - function signP2SHTransaction(transport, arg) { - return __awaiter$7(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; - var e_1, _b; - return __generator$7(this, function (_c) { - switch (_c.label) { - case 0: - _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; - nullScript = Buffer$l.alloc(0); - nullPrevout = Buffer$l.alloc(0); - defaultVersion = Buffer$l.alloc(4); - defaultVersion.writeUInt32LE(transactionVersion, 0); - trustedInputs = []; - regularOutputs = []; - signatures = []; - firstRun = true; - resuming = false; - startTime = Date.now(); - targetTransaction = { - inputs: [], - timestamp: Buffer$l.alloc(0), - version: defaultVersion - }; - getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; - outputScript = Buffer$l.from(outputScriptHex, "hex"); - _c.label = 1; - case 1: - _c.trys.push([1, 7, 8, 9]); - inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); - _c.label = 2; - case 2: - if (!!inputs_1_1.done) return [3 /*break*/, 6]; - input = inputs_1_1.value; - if (!!resuming) return [3 /*break*/, 4]; - return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; - case 3: - trustedInput = _c.sent(); - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" - ? input[3] - : DEFAULT_SEQUENCE, 0); - trustedInputs.push({ - trustedInput: false, - value: segwit - ? Buffer$l.from(trustedInput, "hex") - : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), - sequence: sequence - }); - _c.label = 4; - case 4: - outputs = input[0].outputs; - index = input[1]; - if (outputs && index <= outputs.length - 1) { - regularOutputs.push(outputs[index]); - } - _c.label = 5; - case 5: - inputs_1_1 = inputs_1.next(); - return [3 /*break*/, 2]; - case 6: return [3 /*break*/, 9]; - case 7: - e_1_1 = _c.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 9]; - case 8: - try { - if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 9: - // Pre-build the target transaction - for (i = 0; i < inputs.length; i++) { - sequence = Buffer$l.alloc(4); - sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" - ? inputs[i][3] - : DEFAULT_SEQUENCE, 0); - targetTransaction.inputs.push({ - script: nullScript, - prevout: nullPrevout, - sequence: sequence - }); - } - if (!segwit) return [3 /*break*/, 12]; - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; - case 10: - _c.sent(); - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 11: - _c.sent(); - _c.label = 12; - case 12: - i = 0; - _c.label = 13; - case 13: - if (!(i < inputs.length)) return [3 /*break*/, 19]; - input = inputs[i]; - script = inputs[i].length >= 3 && typeof input[2] === "string" - ? Buffer$l.from(input[2], "hex") - : regularOutputs[i].script; - pseudoTX = Object.assign({}, targetTransaction); - pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; - if (initialTimestamp !== undefined) { - pseudoTX.timestamp = Buffer$l.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); - } - if (segwit) { - pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; - } - else { - pseudoTX.inputs[i].script = script; - } - return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; - case 14: - _c.sent(); - if (!!segwit) return [3 /*break*/, 16]; - return [4 /*yield*/, hashOutputFull(transport, outputScript)]; - case 15: - _c.sent(); - _c.label = 16; - case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; - case 17: - signature = _c.sent(); - signatures.push(segwit - ? signature.toString("hex") - : signature.slice(0, signature.length - 1).toString("hex")); - targetTransaction.inputs[i].script = nullScript; - if (firstRun) { - firstRun = false; - } - _c.label = 18; - case 18: - i++; - return [3 /*break*/, 13]; - case 19: return [2 /*return*/, signatures]; - } - }); - }); - } - - var __assign$1 = (undefined && undefined.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -39489,6 +39277,210 @@ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; + var __values$4 = (undefined && undefined.__values) || function(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + var defaultArg = { + lockTime: DEFAULT_LOCKTIME, + sigHashType: SIGHASH_ALL, + segwit: false, + transactionVersion: DEFAULT_VERSION + }; + function signP2SHTransaction(transport, arg) { + return __awaiter$6(this, void 0, void 0, function () { + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var e_1, _b; + return __generator$6(this, function (_c) { + switch (_c.label) { + case 0: + _a = __assign$2(__assign$2({}, defaultArg), arg), inputs = _a.inputs, associatedKeysets = _a.associatedKeysets, outputScriptHex = _a.outputScriptHex, lockTime = _a.lockTime, sigHashType = _a.sigHashType, segwit = _a.segwit, transactionVersion = _a.transactionVersion, initialTimestamp = _a.initialTimestamp; + nullScript = Buffer$l.alloc(0); + nullPrevout = Buffer$l.alloc(0); + defaultVersion = Buffer$l.alloc(4); + defaultVersion.writeUInt32LE(transactionVersion, 0); + trustedInputs = []; + regularOutputs = []; + signatures = []; + firstRun = true; + resuming = false; + startTime = Date.now(); + targetTransaction = { + inputs: [], + timestamp: Buffer$l.alloc(0), + version: defaultVersion + }; + getTrustedInputCall = segwit ? getTrustedInputBIP143 : getTrustedInput; + outputScript = Buffer$l.from(outputScriptHex, "hex"); + _c.label = 1; + case 1: + _c.trys.push([1, 7, 8, 9]); + inputs_1 = __values$4(inputs), inputs_1_1 = inputs_1.next(); + _c.label = 2; + case 2: + if (!!inputs_1_1.done) return [3 /*break*/, 6]; + input = inputs_1_1.value; + if (!!resuming) return [3 /*break*/, 4]; + return [4 /*yield*/, getTrustedInputCall(transport, input[1], input[0])]; + case 3: + trustedInput = _c.sent(); + sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(input.length >= 4 && typeof input[3] === "number" + ? input[3] + : DEFAULT_SEQUENCE, 0); + trustedInputs.push({ + trustedInput: false, + value: segwit + ? Buffer$l.from(trustedInput, "hex") + : Buffer$l.from(trustedInput, "hex").slice(4, 4 + 0x24), + sequence: sequence + }); + _c.label = 4; + case 4: + outputs = input[0].outputs; + index = input[1]; + if (outputs && index <= outputs.length - 1) { + regularOutputs.push(outputs[index]); + } + _c.label = 5; + case 5: + inputs_1_1 = inputs_1.next(); + return [3 /*break*/, 2]; + case 6: return [3 /*break*/, 9]; + case 7: + e_1_1 = _c.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 9]; + case 8: + try { + if (inputs_1_1 && !inputs_1_1.done && (_b = inputs_1["return"])) _b.call(inputs_1); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 9: + // Pre-build the target transaction + for (i = 0; i < inputs.length; i++) { + sequence = Buffer$l.alloc(4); + sequence.writeUInt32LE(inputs[i].length >= 4 && typeof inputs[i][3] === "number" + ? inputs[i][3] + : DEFAULT_SEQUENCE, 0); + targetTransaction.inputs.push({ + script: nullScript, + prevout: nullPrevout, + sequence: sequence + }); + } + if (!segwit) return [3 /*break*/, 12]; + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, true, targetTransaction, trustedInputs, true)]; + case 10: + _c.sent(); + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 11: + _c.sent(); + _c.label = 12; + case 12: + i = 0; + _c.label = 13; + case 13: + if (!(i < inputs.length)) return [3 /*break*/, 19]; + input = inputs[i]; + script = inputs[i].length >= 3 && typeof input[2] === "string" + ? Buffer$l.from(input[2], "hex") + : regularOutputs[i].script; + pseudoTX = Object.assign({}, targetTransaction); + pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; + if (initialTimestamp !== undefined) { + pseudoTX.timestamp = Buffer$l.alloc(4); + pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + } + if (segwit) { + pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; + } + else { + pseudoTX.inputs[i].script = script; + } + return [4 /*yield*/, startUntrustedHashTransactionInput(transport, firstRun, pseudoTX, pseudoTrustedInputs, segwit)]; + case 14: + _c.sent(); + if (!!segwit) return [3 /*break*/, 16]; + return [4 /*yield*/, hashOutputFull(transport, outputScript)]; + case 15: + _c.sent(); + _c.label = 16; + case 16: return [4 /*yield*/, signTransaction(transport, associatedKeysets[i], lockTime, sigHashType)]; + case 17: + signature = _c.sent(); + signatures.push(segwit + ? signature.toString("hex") + : signature.slice(0, signature.length - 1).toString("hex")); + targetTransaction.inputs[i].script = nullScript; + if (firstRun) { + firstRun = false; + } + _c.label = 18; + case 18: + i++; + return [3 /*break*/, 13]; + case 19: return [2 /*return*/, signatures]; + } + }); + }); + } + + var __assign$1 = (undefined && undefined.__assign) || function () { + __assign$1 = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; /** * Bitcoin API. * @@ -39502,9 +39494,9 @@ this.derivationsCache = {}; } BtcOld.prototype.derivatePath = function (path) { - return __awaiter$6(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var res; - return __generator$6(this, function (_a) { + return __generator$5(this, function (_a) { switch (_a.label) { case 0: if (this.derivationsCache[path]) @@ -39522,9 +39514,9 @@ }; BtcOld.prototype.getWalletXpub = function (_a) { var path = _a.path, xpubVersion = _a.xpubVersion; - return __awaiter$6(this, void 0, void 0, function () { + return __awaiter$5(this, void 0, void 0, function () { var pathElements, parentPath, parentDerivation, accountDerivation, fingerprint, xpub; - return __generator$6(this, function (_b) { + return __generator$5(this, function (_b) { switch (_b.label) { case 0: pathElements = pathStringToArray(path); @@ -39732,7 +39724,7 @@ return MerkleMap; }()); - var __extends$3 = (undefined && undefined.__extends) || (function () { + var __extends$2 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39784,7 +39776,7 @@ * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#sign_psbt */ var MerkelizedPsbt = /** @class */ (function (_super) { - __extends$3(MerkelizedPsbt, _super); + __extends$2(MerkelizedPsbt, _super); function MerkelizedPsbt(psbt) { var _this = _super.call(this) || this; _this.inputMerkleMaps = []; @@ -39828,7 +39820,7 @@ return MerkelizedPsbt; }(PsbtV2)); - var __extends$2 = (undefined && undefined.__extends) || (function () { + var __extends$1 = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -39893,7 +39885,7 @@ return ClientCommand; }()); var YieldCommand = /** @class */ (function (_super) { - __extends$2(YieldCommand, _super); + __extends$1(YieldCommand, _super); function YieldCommand(results, progressCallback) { var _this = _super.call(this) || this; _this.progressCallback = progressCallback; @@ -39909,7 +39901,7 @@ return YieldCommand; }(ClientCommand)); var GetPreimageCommand = /** @class */ (function (_super) { - __extends$2(GetPreimageCommand, _super); + __extends$1(GetPreimageCommand, _super); function GetPreimageCommand(known_preimages, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_PREIMAGE; @@ -39955,7 +39947,7 @@ return GetPreimageCommand; }(ClientCommand)); var GetMerkleLeafProofCommand = /** @class */ (function (_super) { - __extends$2(GetMerkleLeafProofCommand, _super); + __extends$1(GetMerkleLeafProofCommand, _super); function GetMerkleLeafProofCommand(known_trees, queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_PROOF; @@ -40007,7 +39999,7 @@ return GetMerkleLeafProofCommand; }(ClientCommand)); var GetMerkleLeafIndexCommand = /** @class */ (function (_super) { - __extends$2(GetMerkleLeafIndexCommand, _super); + __extends$1(GetMerkleLeafIndexCommand, _super); function GetMerkleLeafIndexCommand(known_trees) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MERKLE_LEAF_INDEX; @@ -40049,7 +40041,7 @@ return GetMerkleLeafIndexCommand; }(ClientCommand)); var GetMoreElementsCommand = /** @class */ (function (_super) { - __extends$2(GetMoreElementsCommand, _super); + __extends$1(GetMoreElementsCommand, _super); function GetMoreElementsCommand(queue) { var _this = _super.call(this) || this; _this.code = ClientCommandCode.GET_MORE_ELEMENTS; @@ -40168,7 +40160,7 @@ return ClientCommandInterpreter; }()); - var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40177,7 +40169,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40239,9 +40231,9 @@ this.transport = transport; } AppClient.prototype.makeRequest = function (ins, data, cci) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var response, hwRequest, commandResponse; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.transport.send(CLA_BTC, ins, 0, 0, data, [ 0x9000, @@ -40267,9 +40259,9 @@ }); }; AppClient.prototype.getExtendedPubkey = function (display, pathElements) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var response; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: if (pathElements.length > 6) { @@ -40287,9 +40279,9 @@ }); }; AppClient.prototype.getWalletAddress = function (walletPolicy, walletHMAC, change, addressIndex, display) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var clientInterpreter, addressIndexBuffer, response; - return __generator$5(this, function (_a) { + return __generator$4(this, function (_a) { switch (_a.label) { case 0: if (change !== 0 && change !== 1) @@ -40319,10 +40311,10 @@ }); }; AppClient.prototype.signPsbt = function (psbt, walletPolicy, walletHMAC, progressCallback) { - return __awaiter$5(this, void 0, void 0, function () { + return __awaiter$4(this, void 0, void 0, function () { var merkelizedPsbt, clientInterpreter, _a, _b, map, _c, _d, map, inputMapsRoot, outputMapsRoot, yielded, ret, yielded_1, yielded_1_1, inputAndSig; var e_1, _e, e_2, _f, e_3, _g; - return __generator$5(this, function (_h) { + return __generator$4(this, function (_h) { switch (_h.label) { case 0: merkelizedPsbt = new MerkelizedPsbt(psbt); @@ -40396,8 +40388,8 @@ }); }; AppClient.prototype.getMasterFingerprint = function () { - return __awaiter$5(this, void 0, void 0, function () { - return __generator$5(this, function (_a) { + return __awaiter$4(this, void 0, void 0, function () { + return __generator$4(this, function (_a) { return [2 /*return*/, this.makeRequest(BitcoinIns.GET_MASTER_FINGERPRINT, Buffer$l.from([]))]; }); }); @@ -40577,7 +40569,7 @@ return t; } - var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -40586,7 +40578,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -40822,9 +40814,9 @@ return getTrustedInputBIP143(this.transport, indexLookup, transaction, additionals); }; Btc.prototype.getCorrectImpl = function () { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$3(this, void 0, void 0, function () { var _lazyImpl, impl; - return __generator$4(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: _lazyImpl = this._lazyImpl; @@ -40840,9 +40832,9 @@ }); }; Btc.prototype.inferCorrectImpl = function () { - return __awaiter$4(this, void 0, void 0, function () { + return __awaiter$3(this, void 0, void 0, function () { var appAndVersion, canUseNewImplementation; - return __generator$4(this, function (_a) { + return __generator$3(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getAppAndVersion(this.transport)]; case 1: @@ -41318,7 +41310,7 @@ TransportStatusError: TransportStatusError }); - var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41327,7 +41319,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41415,9 +41407,9 @@ this.send = function (cla, ins, p1, p2, data, statusList) { if (data === void 0) { data = Buffer$l.alloc(0); } if (statusList === void 0) { statusList = [StatusCodes.OK]; } - return __awaiter$3(_this, void 0, void 0, function () { + return __awaiter$2(_this, void 0, void 0, function () { var response, sw; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: if (data.length >= 256) { @@ -41439,10 +41431,10 @@ }); }); }; - this.exchangeAtomicImpl = function (f) { return __awaiter$3(_this, void 0, void 0, function () { + this.exchangeAtomicImpl = function (f) { return __awaiter$2(_this, void 0, void 0, function () { var resolveBusy, busyPromise, unresponsiveReached, timeout, res; var _this = this; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: if (this.exchangeBusyPromise) { @@ -41607,9 +41599,9 @@ for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - return __awaiter$3(_this, void 0, void 0, function () { + return __awaiter$2(_this, void 0, void 0, function () { var _appAPIlock; - return __generator$3(this, function (_a) { + return __generator$2(this, function (_a) { switch (_a.label) { case 0: _appAPIlock = this._appAPIlock; @@ -41834,7 +41826,7 @@ } } - var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41843,7 +41835,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41876,9 +41868,9 @@ }, ]; function requestLedgerDevice() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var device; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.requestDevice({ filters: ledgerDevices @@ -41891,9 +41883,9 @@ }); } function getLedgerDevices() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var devices; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, navigator.usb.getDevices()]; case 1: @@ -41904,9 +41896,9 @@ }); } function getFirstLedgerDevice() { - return __awaiter$2(this, void 0, void 0, function () { + return __awaiter$1(this, void 0, void 0, function () { var existingDevices; - return __generator$2(this, function (_a) { + return __generator$1(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -41924,7 +41916,7 @@ typeof navigator.usb.getDevices === "function"); }; - var __extends$1 = (undefined && undefined.__extends) || (function () { + var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -41939,7 +41931,7 @@ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); - var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } @@ -41948,7 +41940,7 @@ step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) { + var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } @@ -41985,7 +41977,7 @@ * TransportWebUSB.create().then(transport => ...) */ var TransportWebUSB = /** @class */ (function (_super) { - __extends$1(TransportWebUSB, _super); + __extends(TransportWebUSB, _super); function TransportWebUSB(device, interfaceNumber) { var _this = _super.call(this) || this; _this.channel = Math.floor(Math.random() * 0xffff); @@ -42006,9 +41998,9 @@ * Similar to create() except it will always display the device permission (even if some devices are already accepted). */ TransportWebUSB.request = function () { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var device; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, requestLedgerDevice()]; case 1: @@ -42022,9 +42014,9 @@ * Similar to create() except it will never display the device permission (it returns a Promise, null if it fails to find a device). */ TransportWebUSB.openConnected = function () { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var devices; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLedgerDevices()]; case 1: @@ -42040,9 +42032,9 @@ * Create a Ledger transport with a USBDevice */ TransportWebUSB.open = function (device) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var iface, interfaceNumber, e_1, transport, onDisconnect; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, device.open()]; case 1: @@ -42096,8 +42088,8 @@ * Release the transport device */ TransportWebUSB.prototype.close = function () { - return __awaiter$1(this, void 0, void 0, function () { - return __generator$1(this, function (_a) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.exchangeBusyPromise]; case 1: @@ -42122,14 +42114,14 @@ * @returns a promise of apdu response */ TransportWebUSB.prototype.exchange = function (apdu) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var b; var _this = this; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { - case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter$1(_this, void 0, void 0, function () { + case 0: return [4 /*yield*/, this.exchangeAtomicImpl(function () { return __awaiter(_this, void 0, void 0, function () { var _a, channel, packetSize, framing, blocks, i, result, acc, r, buffer; - return __generator$1(this, function (_b) { + return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this, channel = _a.channel, packetSize = _a.packetSize; @@ -42221,9 +42213,9 @@ return TransportWebUSB; }(Transport)); function gracefullyResetDevice(device) { - return __awaiter$1(this, void 0, void 0, function () { + return __awaiter(this, void 0, void 0, function () { var err_1; - return __generator$1(this, function (_a) { + return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); @@ -42246,1966 +42238,8 @@ 'default': TransportWebUSB }); - var axios$2 = {exports: {}}; - - var bind$2 = 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); - }; - }; - - var bind$1 = bind$2; - - // utils is a library of generic helper functions non-specific to axios - - var toString = Object.prototype.toString; - - /** - * 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 toString.call(val) === '[object Array]'; - } - - /** - * 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 - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; - } - - /** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ - function isFormData(val) { - return (typeof FormData !== 'undefined') && (val instanceof FormData); - } - - /** - * 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) && (val.buffer instanceof ArrayBuffer); - } - 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 (toString.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; - } - - /** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ - function isDate(val) { - return toString.call(val) === '[object Date]'; - } - - /** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ - function isFile(val) { - return toString.call(val) === '[object File]'; - } - - /** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ - function isBlob(val) { - return toString.call(val) === '[object Blob]'; - } - - /** - * 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 URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ - function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof 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$1(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; - } - - var utils$d = { - 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 - }; - - var utils$c = utils$d; - - 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 - */ - var buildURL$2 = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils$c.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils$c.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils$c.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils$c.forEach(val, function parseValue(v) { - if (utils$c.isDate(v)) { - v = v.toISOString(); - } else if (utils$c.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; - }; - - var utils$b = utils$d; - - function InterceptorManager$1() { - 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$1.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$1.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$1.prototype.forEach = function forEach(fn) { - utils$b.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - }; - - var InterceptorManager_1 = InterceptorManager$1; - - var utils$a = utils$d; - - var normalizeHeaderName$1 = function normalizeHeaderName(headers, normalizedName) { - utils$a.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); - }; - - /** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ - var enhanceError$2 = function enhanceError(error, config, code, request, response) { - error.config = config; - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - 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 - }; - }; - return error; - }; - - var enhanceError$1 = enhanceError$2; - - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ - var createError$2 = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError$1(error, config, code, request, response); - }; - - var createError$1 = createError$2; - - /** - * 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. - */ - var settle$1 = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError$1( - 'Request failed with status code ' + response.status, - response.config, - null, - response.request, - response - )); - } - }; - - var utils$9 = utils$d; - - var cookies$1 = ( - utils$9.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$9.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils$9.isString(path)) { - cookie.push('path=' + path); - } - - if (utils$9.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() {} - }; - })() - ); - - /** - * 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 - */ - var isAbsoluteURL$1 = 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); - }; - - /** - * 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 - */ - var combineURLs$1 = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; - }; - - var isAbsoluteURL = isAbsoluteURL$1; - var combineURLs = combineURLs$1; - - /** - * 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 - */ - var buildFullPath$1 = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; - }; - - var utils$8 = utils$d; - - // 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 - */ - var parseHeaders$1 = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { return parsed; } - - utils$8.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils$8.trim(line.substr(0, i)).toLowerCase(); - val = utils$8.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; - }; - - var utils$7 = utils$d; - - var isURLSameOrigin$1 = ( - utils$7.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$7.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; - }; - })() - ); - - /** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ - function Cancel$3(message) { - this.message = message; - } - - Cancel$3.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); - }; - - Cancel$3.prototype.__CANCEL__ = true; - - var Cancel_1 = Cancel$3; - - var utils$6 = utils$d; - var settle = settle$1; - var cookies = cookies$1; - var buildURL$1 = buildURL$2; - var buildFullPath = buildFullPath$1; - var parseHeaders = parseHeaders$1; - var isURLSameOrigin = isURLSameOrigin$1; - var createError = createError$2; - var defaults$4 = defaults_1; - var Cancel$2 = Cancel_1; - - var xhr = 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$6.isFormData(requestData)) { - 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$1(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(createError('Request aborted', config, 'ECONNABORTED', 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(createError('Network Error', config, null, 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 || defaults$4.transitional; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(createError( - timeoutErrorMessage, - config, - transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', - 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$6.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$6.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$6.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 Cancel$2('canceled') : 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; - } - - // Send the request - request.send(requestData); - }); - }; - - var utils$5 = utils$d; - var normalizeHeaderName = normalizeHeaderName$1; - var enhanceError = enhanceError$2; - - var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - function setContentTypeIfUnset(headers, value) { - if (!utils$5.isUndefined(headers) && utils$5.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } - } - - function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = xhr; - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = xhr; - } - return adapter; - } - - function stringifySafely(rawValue, parser, encoder) { - if (utils$5.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$5.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); - } - - var defaults$3 = { - - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - - if (utils$5.isFormData(data) || - utils$5.isArrayBuffer(data) || - utils$5.isBuffer(data) || - utils$5.isStream(data) || - utils$5.isFile(data) || - utils$5.isBlob(data) - ) { - return data; - } - if (utils$5.isArrayBufferView(data)) { - return data.buffer; - } - if (utils$5.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils$5.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } - return data; - }], - - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults$3.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || (forcedJSONParsing && utils$5.isString(data) && data.length)) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError(e, this, 'E_JSON_PARSE'); - } - 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, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } - }; - - utils$5.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults$3.headers[method] = {}; - }); - - utils$5.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults$3.headers[method] = utils$5.merge(DEFAULT_CONTENT_TYPE); - }); - - var defaults_1 = defaults$3; - - var utils$4 = utils$d; - var defaults$2 = defaults_1; - - /** - * 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 - */ - var transformData$1 = function transformData(data, headers, fns) { - var context = this || defaults$2; - /*eslint no-param-reassign:0*/ - utils$4.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); - - return data; - }; - - var isCancel$1 = function isCancel(value) { - return !!(value && value.__CANCEL__); - }; - - var utils$3 = utils$d; - var transformData = transformData$1; - var isCancel = isCancel$1; - var defaults$1 = defaults_1; - var Cancel$1 = Cancel_1; - - /** - * Throws a `Cancel` if cancellation has been requested. - */ - function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel$1('canceled'); - } - } - - /** - * 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 - */ - var dispatchRequest$1 = 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$3.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); - - utils$3.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); - - var adapter = config.adapter || defaults$1.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); - }); - }; - - var utils$2 = utils$d; - - /** - * 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 - */ - var mergeConfig$2 = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { - return utils$2.merge(target, source); - } else if (utils$2.isPlainObject(source)) { - return utils$2.merge({}, source); - } else if (utils$2.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils$2.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils$2.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, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - - utils$2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - (utils$2.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; - }; - - var data = { - "version": "0.24.0" - }; - - var VERSION = data.version; - - var validators$1 = {}; - - // eslint-disable-next-line func-names - ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { - validators$1[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$1.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 Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } - - 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 TypeError('options must be an object'); - } - 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 TypeError('option ' + opt + ' must be ' + result); - } - continue; - } - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } - } - - var validator$1 = { - assertOptions: assertOptions, - validators: validators$1 - }; - - var utils$1 = utils$d; - var buildURL = buildURL$2; - var InterceptorManager = InterceptorManager_1; - var dispatchRequest = dispatchRequest$1; - var mergeConfig$1 = mergeConfig$2; - var validator = validator$1; - - var validators = validator.validators; - /** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ - function Axios$1(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$1.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig$1(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$1.prototype.getUri = function getUri(config) { - config = mergeConfig$1(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); - }; - - // Provide aliases for supported request methods - utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function(url, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; - }); - - utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function(url, data, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: data - })); - }; - }); - - var Axios_1 = Axios$1; - - var Cancel = Cancel_1; - - /** - * 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 Cancel(message); - resolvePromise(token.reason); - }); - } - - /** - * Throws a `Cancel` 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 - }; - }; - - var CancelToken_1 = CancelToken; - - /** - * 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} - */ - var spread = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - }; - - /** - * 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 - */ - var isAxiosError = function isAxiosError(payload) { - return (typeof payload === 'object') && (payload.isAxiosError === true); - }; - - var utils = utils$d; - var bind = bind$2; - var Axios = Axios_1; - var mergeConfig = mergeConfig$2; - var defaults = defaults_1; - - /** - * 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$1 = createInstance(defaults); - - // Expose Axios class to allow class inheritance - axios$1.Axios = Axios; - - // Expose Cancel & CancelToken - axios$1.Cancel = Cancel_1; - axios$1.CancelToken = CancelToken_1; - axios$1.isCancel = isCancel$1; - axios$1.VERSION = data.version; - - // Expose all/spread - axios$1.all = function all(promises) { - return Promise.all(promises); - }; - axios$1.spread = spread; - - // Expose isAxiosError - axios$1.isAxiosError = isAxiosError; - - axios$2.exports = axios$1; - - // Allow use of default import syntax in TypeScript - axios$2.exports.default = axios$1; - - var axios = axios$2.exports; - - var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __generator = (undefined && undefined.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - /** - * Speculos TCP transport implementation - * - * @example - * import SpeculosHttpTransport from "@ledgerhq/hw-transport-node-speculos-http"; - * const transport = await SpeculosHttpTransport.open(); - * const res = await transport.send(0xE0, 0x01, 0, 0); - */ - var SpeculosHttpTransport = /** @class */ (function (_super) { - __extends(SpeculosHttpTransport, _super); - function SpeculosHttpTransport(instance, opts) { - var _this = _super.call(this) || this; - /** - * Press and release button - * buttons available: left, right, both - * @param {*} but - */ - _this.button = function (but) { - return new Promise(function (resolve, reject) { - var action = { action: "press-and-release" }; - log("speculos-button", "press-and-release", but); - _this.instance - .post("/button/".concat(but), action) - .then(function (response) { - resolve(response.data); - })["catch"](function (e) { - reject(e); - }); - }); - }; - _this.instance = instance; - _this.opts = opts; - return _this; - } - SpeculosHttpTransport.prototype.exchange = function (apdu) { - return __awaiter(this, void 0, void 0, function () { - var hex; - return __generator(this, function (_a) { - hex = apdu.toString("hex"); - log("apdu", "=> " + hex); - return [2 /*return*/, this.instance.post("/apdu", { data: hex }).then(function (r) { - // r.data is {"data": "hex value of response"} - var data = r.data.data; - log("apdu", "<= " + data); - return Buffer$l.from(data, "hex"); - })]; - }); - }); - }; - SpeculosHttpTransport.prototype.close = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - // close event stream - this.eventStream.destroy(); - return [2 /*return*/, Promise.resolve()]; - }); - }); - }; - SpeculosHttpTransport.isSupported = function () { return Promise.resolve(true); }; - // this transport is not discoverable - SpeculosHttpTransport.list = function () { return Promise.resolve([]); }; - SpeculosHttpTransport.listen = function (_observer) { return ({ - unsubscribe: function () { } - }); }; - SpeculosHttpTransport.open = function (opts) { - return new Promise(function (resolve, reject) { - var instance = axios.create(opts); - instance.defaults.baseURL = "http://localhost:5000"; - var transport = new SpeculosHttpTransport(instance, opts); - instance({ - url: "/events?stream=true", - responseType: "stream" - }) - .then(function (response) { - response.data.on("data", function (chunk) { - log("speculos-event", chunk.toString()); - // XXX: we could process display events here - // client side automation or UI tests/checks - }); - response.data.on("close", function () { - log("speculos-event", "close"); - transport.emit("disconnect", new DisconnectedDevice("Speculos exited!")); - }); - transport.eventStream = response.data; - // we are connected to speculos - resolve(transport); - })["catch"](function (error) { - reject(error); - }); - }); - }; - return SpeculosHttpTransport; - }(Transport)); - - var SpeculosHttpTransport$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': SpeculosHttpTransport - }); - exports.Btc = Btc$1; exports.Log = index; - exports.SpeculosTransport = SpeculosHttpTransport$1; exports.TransportWebUSB = TransportWebUSB$1; exports.createHash = browser$4; @@ -44215,6 +42249,5 @@ window.Btc = NewLedger.Btc.default; window.TransportWebUSB = NewLedger.TransportWebUSB.default; -window.SpeculosTransport = NewLedger.SpeculosTransport.default; window.Log = NewLedger.Log.default; window.createHash = NewLedger.createHash.default; From 6eeffe0d7fa2f38c1aa73c3c2497abea8e409fdf Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 17 Feb 2022 00:33:37 +1100 Subject: [PATCH 69/78] wtf --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index f16b53b3..039039bb 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -762,7 +762,7 @@ $(document).ready(function() { // check if public key is part of multisig var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; if (timeStamp) { - params.initialTimestamp = timeStamp; + params.initialTimestamp = txn.timestamp; } result = await appBtc.signP2SHTransaction(params); From 40f02473695b8c675fc4915e6e2983200b06e090 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 18 Feb 2022 11:59:15 +1100 Subject: [PATCH 70/78] fix timestamp --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 039039bb..b2977a9b 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -783,7 +783,7 @@ $(document).ready(function() { } } else { - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:timeStamp, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:txn.timeStamp, additionals: ["peercoin"]}; result = await appBtc.createPaymentTransactionNew(params); callback(result); } From c3da3580229f7ae37e868a9a5fb64ada9336c2db Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 18 Feb 2022 13:03:09 +1100 Subject: [PATCH 71/78] wtf --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index b2977a9b..bad9b4ac 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -771,7 +771,7 @@ $(document).ready(function() { console.log("signature result",result); $.each(result, function(idx,itm) { var signature = Crypto.util.hexToBytes(itm+hashType.toString(16)); - if (currenttransaction.signmultisig(idx,undefined,Crypto.util.hexToBytes(hashType.toString(16)),signature)) { + if (currenttransaction.signmultisig(idx,undefined,hashType*1,signature)) { success=true; } }); From 26e6ae185504d57106cf452f81e5d3116446957b Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 18 Feb 2022 13:42:00 +1100 Subject: [PATCH 72/78] differnet timesmtmp --- js/cointoolkit.js | 2 +- js/ledger.js | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index bad9b4ac..9fcce393 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -762,7 +762,7 @@ $(document).ready(function() { // check if public key is part of multisig var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; if (timeStamp) { - params.initialTimestamp = txn.timestamp; + params.initialTimestamp = currenttransaction.nTime; } result = await appBtc.signP2SHTransaction(params); diff --git a/js/ledger.js b/js/ledger.js index 13e4770a..d2d30b5b 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -39296,7 +39296,7 @@ }; function signP2SHTransaction(transport, arg) { return __awaiter$6(this, void 0, void 0, function () { - var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, startTime, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; + var _a, inputs, associatedKeysets, outputScriptHex, lockTime, sigHashType, segwit, transactionVersion, initialTimestamp, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_1_1, i, sequence, i, input, script, pseudoTX, pseudoTrustedInputs, signature; var e_1, _b; return __generator$6(this, function (_c) { switch (_c.label) { @@ -39311,7 +39311,6 @@ signatures = []; firstRun = true; resuming = false; - startTime = Date.now(); targetTransaction = { inputs: [], timestamp: Buffer$l.alloc(0), @@ -39398,7 +39397,7 @@ pseudoTrustedInputs = segwit ? [trustedInputs[i]] : trustedInputs; if (initialTimestamp !== undefined) { pseudoTX.timestamp = Buffer$l.alloc(4); - pseudoTX.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + pseudoTX.timestamp.writeUInt32LE(initialTimestamp, 0); } if (segwit) { pseudoTX.inputs = [__assign$2(__assign$2({}, pseudoTX.inputs[i]), { script: script })]; From 68840004cfde1476fbbe0a474c8ee659087db055 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Thu, 24 Feb 2022 12:07:39 +1100 Subject: [PATCH 73/78] fixup parameters --- js/cointoolkit.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 9fcce393..40e66e86 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -760,9 +760,9 @@ $(document).ready(function() { var result=false; if (currenttransaction.ins[0].script.buffer.slice(-1) == coinjs.opcode.OP_CHECKMULTISIG) { // check if public key is part of multisig - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false}; if (timeStamp) { - params.initialTimestamp = currenttransaction.nTime; + params.initialTimestamp = timeStamp; } result = await appBtc.signP2SHTransaction(params); @@ -783,7 +783,11 @@ $(document).ready(function() { } } else { - var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, initialTimestamp:txn.timeStamp, additionals: ["peercoin"]}; + var params = {inputs:inputs, associatedKeysets:paths, outputScriptHex:outputsBuffer, transactionVersion:currenttransaction.version, sigHashType: hashType, segwit:false}; + if (timeStamp) { + params.initialTimestamp = timeStamp; + } + result = await appBtc.createPaymentTransactionNew(params); callback(result); } From 27548b81de866fd3d1af2e22849c0140d10e9857 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 25 Feb 2022 12:51:41 +1100 Subject: [PATCH 74/78] allow non multisig to sign properly --- js/ledger.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/js/ledger.js b/js/ledger.js index d2d30b5b..233d2253 100644 --- a/js/ledger.js +++ b/js/ledger.js @@ -38796,7 +38796,7 @@ }; function createTransaction(transport, arg) { return __awaiter$8(this, void 0, void 0, function () { - var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, startTime, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; + var signTx, inputs, associatedKeysets, changePath, outputScriptHex, lockTime, sigHashType, segwit, initialTimestamp, additionals, expiryHeight, onDeviceStreaming, onDeviceSignatureGranted, onDeviceSignatureRequested, useTrustedInputForSegwit, a, e_1, notify, isDecred, isXST, sapling, bech32, useBip143, nullScript, nullPrevout, defaultVersion, trustedInputs, regularOutputs, signatures, publicKeys, firstRun, resuming, targetTransaction, getTrustedInputCall, outputScript, inputs_1, inputs_1_1, input, trustedInput, sequence, outputs, index, e_2_1, result_1, i, r, i, i, input, script, pseudoTX, pseudoTrustedInputs, signature, i, signatureSize, keySize, offset, lockTimeBuffer, result, witness, i, tmpScriptData, decredWitness_1; var e_2, _a; return __generator$8(this, function (_b) { switch (_b.label) { @@ -38838,7 +38838,6 @@ }; isDecred = additionals.includes("decred"); isXST = additionals.includes("stealthcoin"); - startTime = Date.now(); sapling = additionals.includes("sapling"); bech32 = segwit && additionals.includes("bech32"); useBip143 = segwit || @@ -38964,7 +38963,7 @@ case 18: if (initialTimestamp !== undefined) { targetTransaction.timestamp = Buffer$l.alloc(4); - targetTransaction.timestamp.writeUInt32LE(Math.floor(initialTimestamp + (Date.now() - startTime) / 1000), 0); + targetTransaction.timestamp.writeUInt32LE(initialTimestamp, 0); } onDeviceSignatureRequested(); if (!useBip143) return [3 /*break*/, 23]; From 9fbdd43c6e13e26bc6fc8394caa9f5d71e4a5b97 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 25 Feb 2022 13:04:51 +1100 Subject: [PATCH 75/78] allow to broadcast from sign page --- js/cointoolkit.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 40e66e86..de554b2d 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -2547,7 +2547,7 @@ $(document).ready(function() { }); $("#signedData .signedToBroadcast").on( "click", function() { - $("#broadcast #rawTransaction").val(signed).fadeOut().fadeIn(); + $("#broadcast #rawTransaction").val($("#signedData textarea").val()).fadeOut().fadeIn(); window.location.hash = "#broadcast"; }); } catch(e) { From 88fd63de2494b3ab76d9e620b0e6d96bef03f7ac Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Sat, 30 Mar 2024 10:39:04 +1100 Subject: [PATCH 76/78] trim inputs during signing --- js/cointoolkit.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index de554b2d..6caf72ea 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -2370,6 +2370,14 @@ $(document).ready(function() { $(this).val($(this).val().replace(/\s/g, "")); }); + $("#signPrivateKey").focusout(function(){ + $(this).val($(this).val().replace(/\s/g, "")); + }); + + $("#signTransaction").focusout(function(){ + $(this).val($(this).val().replace(/\s/g, "")); + }); + /* redeem from button code */ $("#redeemFromBtn").click(function(){ var redeem = redeemingFrom($("#redeemFrom").val()); From 0134e71e83661a9ba0af467276b494fc699c5b98 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Fri, 12 Apr 2024 15:52:17 +1000 Subject: [PATCH 77/78] throw error if transaction unchanged --- js/cointoolkit.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/js/cointoolkit.js b/js/cointoolkit.js index 6caf72ea..f36af61f 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -2495,6 +2495,9 @@ $(document).ready(function() { // var signed = t.sign(wifkey.val()); var signed = t.sign(wifkey.val(), $("#sighashType option:selected").val()); + if (script.val() == signed) { + throw("transaction unchanged"); + } $("#signedData textarea").val(signed); $("#signedData .txSize").html(t.size()); $("#signedData").removeClass('hidden').fadeIn(); From 0a35c3852028596dd369f30b4fbf3b23c41678b9 Mon Sep 17 00:00:00 2001 From: backpacker69 Date: Mon, 22 Apr 2024 12:13:59 +1000 Subject: [PATCH 78/78] default to version 3 --- index.html | 12 +++++++++--- js/cointoolkit.js | 4 ++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index eccde99b..c1e32322 100644 --- a/index.html +++ b/index.html @@ -700,9 +700,9 @@

New Transaction Create a new transaction


- -

The locktime indicates the earliest time a transaction can be added to the block chain.

- + +

Desired version of transaction to be created.

+
@@ -714,6 +714,12 @@

New Transaction Create a new transaction


+ +

The locktime indicates the earliest time a transaction can be added to the block chain.

+ + +
+

The settings page can be used to select alternative networks of which you can retrieve your unspent outputs and broadcast a signed transaction into.

diff --git a/js/cointoolkit.js b/js/cointoolkit.js index f36af61f..48a5c6f7 100644 --- a/js/cointoolkit.js +++ b/js/cointoolkit.js @@ -2185,6 +2185,10 @@ $(document).ready(function() { tx.lock_time = $("#nLockTime").val()*1; } + if(($("#nVersion").val()).match(/^[0-9]+$/g)){ + tx.version = $("#nVersion").val()*1; + } + if(($("#nTime").val()).match(/^[0-9]+$/g)){ tx.nTime = $("#nTime").val()*1; }